diff --git a/android/acclorite-book-story/LICENSE b/android/acclorite-book-story/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f288702d2fa16d3cdf0035b15a9fcbc552cd88e7 --- /dev/null +++ b/android/acclorite-book-story/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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 for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know 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 License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of 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 of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification 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 of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. 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 work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a 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 visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation 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 to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients 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 to +produce it from the Program, in the form of source code under the +terms 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 independent +works, 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 not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-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 excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the 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 install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional 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 you +add to a covered work, you may (if authorized by the copyright holders of +that 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 "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form 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 expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered 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 automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent 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 anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain 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 limiting +any implied license or other defenses to infringement that may +otherwise 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 or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License 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 have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License 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 the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES 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 OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy 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 greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + 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 appropriate +parts of the General Public License. Of course, your program's commands +might 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 +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/android/acclorite-book-story/instance.json b/android/acclorite-book-story/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..1dc9845ce5b4c76a12d0f0207b261243491c09f1 --- /dev/null +++ b/android/acclorite-book-story/instance.json @@ -0,0 +1,17 @@ +{ + "schema_version": 1, + "instance_id": "android/acclorite-book-story", + "platform": "android", + "repo": "https://github.com/Acclorite/book-story", + "commit": "b0ab7d320aed903b56be6eff47b0049b8a7e48bf", + "patches": [ + { + "path": "reference/patches/local-source.patch", + "reason": "suppress_nondeterminism", + "note": "Skip the first-launch onboarding screen used by the frozen reference app.", + "sha256": "ed7f7cc4a6dc59f617fc616a49729025409e744bce5c1a98abaa7822560fd93f" + } + ], + "package": "ua.acclorite.book_story.debug", + "license": null +} diff --git a/android/acclorite-book-story/reference/launch.sh b/android/acclorite-book-story/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8 --- /dev/null +++ b/android/acclorite-book-story/reference/launch.sh @@ -0,0 +1,9 @@ +#!/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 1 diff --git a/android/acclorite-book-story/reference/patches/local-source.patch b/android/acclorite-book-story/reference/patches/local-source.patch new file mode 100644 index 0000000000000000000000000000000000000000..464f5827a987bfbfff6d16a3414a2524fa0932b3 --- /dev/null +++ b/android/acclorite-book-story/reference/patches/local-source.patch @@ -0,0 +1,14 @@ +diff --git a/app/src/main/java/ua/acclorite/book_story/data/settings/SettingsManager.kt b/app/src/main/java/ua/acclorite/book_story/data/settings/SettingsManager.kt +index 8d4bf1866ca3bb43f4b1041ec8054fabf45ff3ed..5e5f84465a89617c5e5e54b52633f946b44a5a02 100644 +--- a/app/src/main/java/ua/acclorite/book_story/data/settings/SettingsManager.kt ++++ b/app/src/main/java/ua/acclorite/book_story/data/settings/SettingsManager.kt +@@ -105,7 +105,8 @@ class SettingsManager @Inject constructor( + serialize = { it.name }, deserialize = { ThemeContrast.valueOf(it) } + ) + val showStartScreen = setting( +- key = booleanPreferencesKey("guide"), default = true ++ // Bloatware removed: skip first-launch onboarding/start screen by default ++ key = booleanPreferencesKey("guide"), default = false + ) + val doublePressExit = setting( + key = booleanPreferencesKey("double_press_exit"), default = false diff --git a/android/acclorite-book-story/tests/android_computation_eval.json b/android/acclorite-book-story/tests/android_computation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..24fcff2dd72e3037aa6a83d99222e3d9a7804035 --- /dev/null +++ b/android/acclorite-book-story/tests/android_computation_eval.json @@ -0,0 +1,197 @@ +{ + "module": "computation", + "total": 18, + "passed": 18, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 15, + "passed": 15, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 3, + "passed": 3, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.2, + "audit": { + "kit_api_version": 1, + "existence": 3, + "liveness": 0, + "interactive": 15, + "depth_ge1": 7, + "depth_ge2": 6, + "value": 15, + "vlm_fine": 3 + }, + "results": [ + { + "test": "computation_search_alpha", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "search 'alpha' -> alpha_wonderland only" + }, + { + "test": "computation_search_testbook", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "search 'testbook' -> testbook only" + }, + { + "test": "computation_search_book", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "search 'book' -> testbook only (alpha_wonderland excluded)" + }, + { + "test": "computation_search_wonderland", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "search 'wonderland' -> alpha_wonderland only" + }, + { + "test": "computation_search_no_match", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "search 'zzz' -> no books" + }, + { + "test": "computation_search_clear_restores", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "after 'alpha' then Exit search -> both books restored" + }, + { + "test": "computation_library_count_badge", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "Library count badge == 2 (== 2 cards)" + }, + { + "test": "computation_search_count_badge", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "after 'alpha' the count badge reads '1' (one visible book)" + }, + { + "test": "computation_book_info_progress", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Book Info progress reads '0%'" + }, + { + "test": "computation_reader_progress", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "reader progress reads '0% (20%)' (leading '0%')" + }, + { + "test": "computation_font_size_label", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "reader 'Font size' value label reads '16pt'" + }, + { + "test": "computation_letter_spacing_label", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "reader 'Letter spacing' value label reads '0pt'" + }, + { + "test": "computation_size_percent_label", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "reader 'Size' value label reads '80%'" + }, + { + "test": "computation_bg_color_red", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "Background color Red channel reads '250'" + }, + { + "test": "computation_font_color_red", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "Font color Red channel reads '68'" + }, + { + "test": "computation_bg_swatch_vlm", + "passed": true, + "message": "VLM: Q='In the 'Background color' section of this colour settings screen, is the colour preview swatch rendered white or a very pale/near-white shade (not a dark or saturated colour)?' A=YES expect=YES", + "depth": 3, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the 'Background color' section of this colour settings screen, is the colour preview swatch rendered white or a very pale/near-white shade (not a dark or saturated colour)?", + "tag": "color" + }, + { + "test": "computation_font_swatch_vlm", + "passed": true, + "message": "VLM: Q='In the 'Font color' section of this colour settings screen, is the colour preview swatch rendered a dark, near-black colour (not white or a pale shade)?' A=YES expect=YES", + "depth": 3, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the 'Font color' section of this colour settings screen, is the colour preview swatch rendered a dark, near-black colour (not white or a pale shade)?", + "tag": "color" + }, + { + "test": "computation_swatches_differ_vlm", + "passed": true, + "message": "VLM: Q='This colour settings screen shows a light/pale 'Background color' preview swatch and a dark 'Font color' preview swatch. Are those two preview swatches clearly different colours from each other (one light, one dark)?' A=YES expect=YES", + "depth": 3, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: This colour settings screen shows a light/pale 'Background color' preview swatch and a dark 'Font color' preview swatch. Are those two preview swatches clearly different colours from each other (one light, one dark)?", + "tag": "color" + } + ] +} \ No newline at end of file diff --git a/android/acclorite-book-story/tests/android_interaction_eval.json b/android/acclorite-book-story/tests/android_interaction_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..685813b57b0e7157b94b0712bdbd9e599bc77e8d --- /dev/null +++ b/android/acclorite-book-story/tests/android_interaction_eval.json @@ -0,0 +1,191 @@ +{ + "module": "interaction", + "total": 17, + "passed": 17, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 11, + "passed": 11, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 6, + "passed": 6, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.5455, + "audit": { + "kit_api_version": 1, + "existence": 6, + "liveness": 0, + "interactive": 11, + "depth_ge1": 4, + "depth_ge2": 1, + "value": 2, + "vlm_fine": 1 + }, + "results": [ + { + "test": "interaction_book_survives_process_death", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "'testbook' present before (True) and after force_stop_and_relaunch (True)" + }, + { + "test": "interaction_book_survives_process_death_vlm", + "passed": true, + "message": "VLM: Q='After relaunching the app, does the Library screen still show at least one book card (a cover tile with a title label beneath it)?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: After relaunching the app, does the Library screen still show at least one book card (a cover tile with a title label beneath it)?", + "tag": "layout" + }, + { + "test": "interaction_second_book_survives_process_death", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "'alpha_wonderland' present before (True) and after force_stop_and_relaunch (True)" + }, + { + "test": "interaction_history_survives_process_death", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "History row 'testbook' present after force_stop_and_relaunch" + }, + { + "test": "interaction_longpress_enters_selection", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "'1 selected' absent before long-press, present after" + }, + { + "test": "interaction_longpress_selection_actions", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "content-desc 'Select all books' + 'Move selected books' + 'Delete selected books' all present" + }, + { + "test": "interaction_longpress_selection_vlm", + "passed": true, + "message": "VLM: Q='One of the book covers is now selected. Does exactly one book cover show a selection indicator on it (a check mark or a highlighted/outlined overlay) that the other cover does not have?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: One of the book covers is now selected. Does exactly one book cover show a selection indicator on it (a check mark or a highlighted/outlined overlay) that the other cover does not have?", + "tag": "shape" + }, + { + "test": "interaction_clear_selection_exits", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "'1 selected' present in selection mode, absent after Clear selected items" + }, + { + "test": "interaction_reading_creates_history", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "'Today' group + History row 'testbook' present after reading" + }, + { + "test": "interaction_history_entry_vlm", + "passed": true, + "message": "VLM: Q='This is a reading-history screen. Is there a list row that shows a small book cover thumbnail on the left with a book title and a time (HH:MM) beside it?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: This is a reading-history screen. Is there a list row that shows a small book cover thumbnail on the left with a book title and a time (HH:MM) beside it?", + "tag": "layout" + }, + { + "test": "interaction_multi_record_integrity", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "'testbook' present and ordered before 'alpha_wonderland' in the same Library" + }, + { + "test": "interaction_multi_record_survives_death", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "both 'testbook' and 'alpha_wonderland' present before (True) and after death (True)" + }, + { + "test": "interaction_library_two_cards_vlm", + "passed": true, + "message": "VLM: Q='How many distinct book cards (each a cover tile with its own title label) are shown in this library grid? Answer YES only if there are exactly two.' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: How many distinct book cards (each a cover tile with its own title label) are shown in this library grid? Answer YES only if there are exactly two.", + "tag": "layout" + }, + { + "test": "interaction_open_reader_shows_text", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "reader shows 'Chapter One' heading and 'The quick brown fox' opening sentence" + }, + { + "test": "interaction_reader_page_vlm", + "passed": true, + "message": "VLM: Q='Is this screen showing a page of readable book text (multiple lines/paragraphs of body text with margins), rather than an empty screen, a list, or a dialog?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is this screen showing a page of readable book text (multiple lines/paragraphs of body text with margins), rather than an empty screen, a list, or a dialog?", + "tag": "layout" + }, + { + "test": "interaction_move_sheet_opens", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Cancel+OK move sheet present after Move, gone after Cancel" + }, + { + "test": "interaction_book_info_actions_vlm", + "passed": true, + "message": "VLM: Q='This is a book-detail screen. Does it show the book's title near the top and two labelled action buttons reading 'Move' and 'Delete'?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: This is a book-detail screen. Does it show the book's title near the top and two labelled action buttons reading 'Move' and 'Delete'?", + "tag": "layout" + } + ] +} \ No newline at end of file diff --git a/android/acclorite-book-story/tests/android_navigation_eval.json b/android/acclorite-book-story/tests/android_navigation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..23a8cc2e60a00794f0f6631e84dd557fbf6d00c4 --- /dev/null +++ b/android/acclorite-book-story/tests/android_navigation_eval.json @@ -0,0 +1,308 @@ +{ + "module": "navigation", + "total": 30, + "passed": 30, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 24, + "passed": 24, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 6, + "passed": 6, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.25, + "audit": { + "kit_api_version": 1, + "existence": 6, + "liveness": 0, + "interactive": 24, + "depth_ge1": 24, + "depth_ge2": 17, + "value": 0, + "vlm_fine": 4 + }, + "results": [ + { + "test": "nav_reach_history", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "History surface (Delete whole history) shown; Library 'Continue reading' no longer showing" + }, + { + "test": "nav_reach_history_vlm", + "passed": true, + "message": "VLM: Q='Is this a reading-history screen showing either a list of book entries grouped by date, or a centered empty-state illustration with a message — and NOT a grid of book covers?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is this a reading-history screen showing either a list of book entries grouped by date, or a centered empty-state illustration with a message — and NOT a grid of book covers?", + "tag": "layout" + }, + { + "test": "nav_reach_browse", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Browse surface (scanned-folder path row) shown; History 'Delete whole history' no longer showing" + }, + { + "test": "nav_reach_library_from_browse", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Library surface ('Continue reading') restored; Browse folder path no longer showing" + }, + { + "test": "nav_backstack_tab_history", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Library ('Continue reading') restored after one BACK from History" + }, + { + "test": "nav_reach_more_sheet", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "More bottom sheet (rows 'Settings'/'About app') shown; toolbar 'Filter' no longer showing" + }, + { + "test": "nav_reach_more_sheet_vlm", + "passed": true, + "message": "VLM: Q='Is there a small menu panel anchored to the BOTTOM edge of the screen (a bottom sheet with a drag handle), rather than a full-screen page?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is there a small menu panel anchored to the BOTTOM edge of the screen (a bottom sheet with a drag handle), rather than a full-screen page?", + "tag": "position" + }, + { + "test": "nav_reach_settings", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Settings root ('Reset start guide') shown; More sheet 'About app' no longer showing" + }, + { + "test": "nav_reach_settings_vlm", + "passed": true, + "message": "VLM: Q='In the top-left corner of this settings screen, is there a left-pointing back arrow, above a vertical list of category rows?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the top-left corner of this settings screen, is there a left-pointing back arrow, above a vertical list of category rows?", + "tag": "position" + }, + { + "test": "nav_reach_appearance", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "Appearance ('Dark theme') shown; Settings 'Reset start guide' no longer showing" + }, + { + "test": "nav_reach_reader_settings_screen", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "Reader settings ('Font thickness') shown; Settings 'Reset start guide' no longer showing" + }, + { + "test": "nav_reach_general", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "General ('Double back press to exit') shown; Settings 'Reset start guide' no longer showing" + }, + { + "test": "nav_reach_library_settings", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "Library settings ('Create category') shown; Settings 'Reset start guide' no longer showing" + }, + { + "test": "nav_reach_browse_settings", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "Browse settings ('Add folder') shown; Settings 'Reset start guide' no longer showing" + }, + { + "test": "nav_backstack_settings_to_library", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "First BACK restores Settings ('Reset start guide'), second BACK restores Library ('Continue reading')" + }, + { + "test": "nav_reach_book_info", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Book Info ('No description.') shown; Library 'Continue reading' no longer showing" + }, + { + "test": "nav_reach_book_info_vlm", + "passed": true, + "message": "VLM: Q='Is a single large book-cover image positioned in the upper part of this screen, with a button to start/read the book lower down — i.e. one book detail page, not a grid of many covers?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a single large book-cover image positioned in the upper part of this screen, with a button to start/read the book lower down — i.e. one book detail page, not a grid of many covers?", + "tag": "position" + }, + { + "test": "nav_reach_reader", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Reader body ('Chapter One') shown; Book Info 'Start' button no longer showing" + }, + { + "test": "nav_reach_reader_vlm", + "passed": true, + "message": "VLM: Q='Is this an ebook reading page filled mostly with paragraphs of body text (a page of prose), rather than a list, a grid, or a form?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is this an ebook reading page filled mostly with paragraphs of body text (a page of prose), rather than a list, a grid, or a form?", + "tag": "layout" + }, + { + "test": "nav_backstack_reader_to_info", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Book Info ('Start') restored after one BACK from the Reader" + }, + { + "test": "nav_backstack_info_to_library", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Library ('Continue reading') restored after one BACK from Book Info" + }, + { + "test": "nav_reach_reader_settings_sheet", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "Reader settings sheet ('Reading mode') shown; bar 'Reader settings' icon no longer showing" + }, + { + "test": "nav_reach_chapters_drawer", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "Chapters drawer ('Chapters' heading) shown; bar 'Reader settings' icon no longer showing" + }, + { + "test": "nav_reach_about", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "About screen ('App version') shown; More sheet 'Settings' no longer showing" + }, + { + "test": "nav_reach_about_vlm", + "passed": true, + "message": "VLM: Q='Is an app icon positioned near the TOP of this About screen, with a vertical list of tappable link rows below it (e.g. report a bug, credits, licenses)?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is an app icon positioned near the TOP of this About screen, with a vertical list of tappable link rows below it (e.g. report a bug, credits, licenses)?", + "tag": "position" + }, + { + "test": "nav_reach_credits", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "Credits ('Tachiyomi (Mihon)') shown; About 'App version' no longer showing" + }, + { + "test": "nav_reach_licenses", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "Licenses ('AboutLibraries') shown; About 'App version' no longer showing" + }, + { + "test": "nav_backstack_credits_to_about", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "About ('App version') restored after one BACK from Credits" + }, + { + "test": "nav_reach_search", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Search surface ('Exit search') shown; toolbar 'Filter' no longer showing" + }, + { + "test": "nav_backstack_exit_search", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Library toolbar ('Filter') restored after Exit search" + } + ] +} \ No newline at end of file diff --git a/android/acclorite-book-story/tests/android_states_eval.json b/android/acclorite-book-story/tests/android_states_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..51f19db83559c1b4e594121b77813cbe385faf5c --- /dev/null +++ b/android/acclorite-book-story/tests/android_states_eval.json @@ -0,0 +1,279 @@ +{ + "module": "states", + "total": 26, + "passed": 26, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 13, + "passed": 13, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 13, + "passed": 13, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 1.0, + "audit": { + "kit_api_version": 1, + "existence": 13, + "liveness": 0, + "interactive": 13, + "depth_ge1": 12, + "depth_ge2": 12, + "value": 0, + "vlm_fine": 10 + }, + "results": [ + { + "test": "states_dark_theme_enable", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Dark theme selected System->Enabled; 'Pure dark' section now showing" + }, + { + "test": "states_dark_theme_enable_vlm", + "passed": true, + "message": "VLM: Q='Is the background of this settings screen a dark/near-black colour with light-coloured text (dark mode), rather than a white/light background?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is the background of this settings screen a dark/near-black colour with light-coloured text (dark mode), rather than a white/light background?", + "tag": "color" + }, + { + "test": "states_dark_theme_persists", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "after process death Dark theme is STILL Enabled; app still renders dark" + }, + { + "test": "states_dark_theme_persists_vlm", + "passed": true, + "message": "VLM: Q='After the app was restarted, is this settings screen still rendered in dark mode — a dark/near-black background with light text (not a white/light background)?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: After the app was restarted, is this settings screen still rendered in dark mode — a dark/near-black background with light text (not a white/light background)?", + "tag": "color" + }, + { + "test": "states_dark_theme_highlight_vlm", + "passed": true, + "message": "VLM: Q='In the 'Dark theme' row (segments System, Disabled, Enabled), is the 'Enabled' segment visually highlighted with a coloured/filled background pill that the other two segments do NOT have?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the 'Dark theme' row (segments System, Disabled, Enabled), is the 'Enabled' segment visually highlighted with a coloured/filled background pill that the other two segments do NOT have?", + "tag": "shape" + }, + { + "test": "states_app_theme_select", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "App theme selected Mercury->Neptune (marker moves into the Neptune card)" + }, + { + "test": "states_app_theme_select_vlm", + "passed": true, + "message": "VLM: Q='In this 'App theme' setting, is the currently selected theme card (the one with a check mark) labelled 'Neptune' and showing a blue/indigo colour swatch?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In this 'App theme' setting, is the currently selected theme card (the one with a check mark) labelled 'Neptune' and showing a blue/indigo colour swatch?", + "tag": "color" + }, + { + "test": "states_app_theme_ring_vlm", + "passed": true, + "message": "VLM: Q='In this 'App theme' card row (Mercury, Neptune, Earth), does exactly one card show a check-mark / selection badge marking it as the chosen theme?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In this 'App theme' card row (Mercury, Neptune, Earth), does exactly one card show a check-mark / selection badge marking it as the chosen theme?", + "tag": "shape" + }, + { + "test": "states_nav_labels_hide", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "nav-bar text labels present -> gone after toggling 'Show navigation labels' off" + }, + { + "test": "states_nav_labels_hide_vlm", + "passed": true, + "message": "VLM: Q='Look at the bottom navigation bar of this app. Are the icons shown WITHOUT any text labels underneath them (no 'Library'/'History'/'Browse' words under the bottom-bar icons)?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Look at the bottom navigation bar of this app. Are the icons shown WITHOUT any text labels underneath them (no 'Library'/'History'/'Browse' words under the bottom-bar icons)?", + "tag": "position" + }, + { + "test": "states_nav_labels_persist", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "nav labels hidden survive process death (still gone after restart)" + }, + { + "test": "states_display_mode_list_grid_vlm", + "passed": true, + "message": "VLM: Q='On this Library screen, are the book covers arranged side by side in a GRID (two or more covers in the same horizontal row), rather than stacked vertically in a single-column list?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: On this Library screen, are the book covers arranged side by side in a GRID (two or more covers in the same horizontal row), rather than stacked vertically in a single-column list?", + "tag": "layout" + }, + { + "test": "states_display_mode_list", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Display mode Grid->List; Library covers restack from a row to a column" + }, + { + "test": "states_display_mode_list_list_vlm", + "passed": true, + "message": "VLM: Q='On this Library screen, are the book covers now stacked vertically in a single-column LIST (each book on its own row, one above the other), rather than side by side in a grid?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: On this Library screen, are the book covers now stacked vertically in a single-column LIST (each book on its own row, one above the other), rather than side by side in a grid?", + "tag": "layout" + }, + { + "test": "states_display_mode_persists", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "after process death Display mode is STILL List; Library still a column" + }, + { + "test": "states_display_mode_persists_vlm", + "passed": true, + "message": "VLM: Q='After the app was restarted, on this Library screen are the book covers still stacked vertically in a single-column LIST (one book per row) rather than in a side-by-side grid?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: After the app was restarted, on this Library screen are the book covers still stacked vertically in a single-column LIST (one book per row) rather than in a side-by-side grid?", + "tag": "layout" + }, + { + "test": "states_display_highlight_vlm", + "passed": true, + "message": "VLM: Q='In the 'Display mode' row (segments 'Grid' and 'List'), is exactly one of the two segments visually highlighted with a coloured/filled background pill (the selected one) while the other is plain?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the 'Display mode' row (segments 'Grid' and 'List'), is exactly one of the two segments visually highlighted with a coloured/filled background pill (the selected one) while the other is plain?", + "tag": "color" + }, + { + "test": "states_title_position_toggle", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Title position checked: Below true->false, Hidden false->true" + }, + { + "test": "states_font_style_italic", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "Font style selected Normal->Italic (marker moves to Italic)" + }, + { + "test": "states_font_style_italic_highlight_vlm", + "passed": true, + "message": "VLM: Q='In the 'Font style' row (segments 'Normal' and 'Italic'), is the 'Italic' segment the one visually highlighted with a coloured/filled background pill (marking it selected) rather than 'Normal'?' A=YES expect=YES", + "depth": 3, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the 'Font style' row (segments 'Normal' and 'Italic'), is the 'Italic' segment the one visually highlighted with a coloured/filled background pill (marking it selected) rather than 'Normal'?", + "tag": "shape" + }, + { + "test": "states_progress_count_change", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "Progress count selected Percentage->Quantity (marker moves)" + }, + { + "test": "states_progress_count_change_highlight_vlm", + "passed": true, + "message": "VLM: Q='In the 'Progress count' row (segments 'Percentage' and 'Quantity'), is the 'Quantity' segment the one visually highlighted with a coloured/filled background pill (marking it selected)?' A=YES expect=YES", + "depth": 3, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the 'Progress count' row (segments 'Percentage' and 'Quantity'), is the 'Quantity' segment the one visually highlighted with a coloured/filled background pill (marking it selected)?", + "tag": "color" + }, + { + "test": "states_text_alignment_change", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "Text alignment selection moves to Center (marker on a different segment)" + }, + { + "test": "states_text_align_highlight_vlm", + "passed": true, + "message": "VLM: Q='In the 'Text alignment' row (segments Start, Justify, Center, End), is the 'Center' segment the one visually highlighted with a coloured/filled background pill (marking it selected)?' A=YES expect=YES", + "depth": 3, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the 'Text alignment' row (segments Start, Justify, Center, End), is the 'Center' segment the one visually highlighted with a coloured/filled background pill (marking it selected)?", + "tag": "shape" + }, + { + "test": "states_chapter_title_align", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "Chapter title alignment selection moves to Center" + }, + { + "test": "states_search_focus", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "after tapping Search, the search EditText reports focused=true" + } + ] +} \ No newline at end of file diff --git a/android/acclorite-book-story/tests/android_structure_eval.json b/android/acclorite-book-story/tests/android_structure_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..828061eeb48965a78a94978fc1dda6ef6213b247 --- /dev/null +++ b/android/acclorite-book-story/tests/android_structure_eval.json @@ -0,0 +1,265 @@ +{ + "module": "structure", + "total": 25, + "passed": 25, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 17, + "passed": 17, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 8, + "passed": 8, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.4706, + "audit": { + "kit_api_version": 1, + "existence": 11, + "liveness": 0, + "interactive": 14, + "depth_ge1": 6, + "depth_ge2": 4, + "value": 0, + "vlm_fine": 8 + }, + "results": [ + { + "test": "structure_gate_launch", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_gate_topbar", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_gate_topbar_vlm", + "passed": true, + "message": "VLM: Q='Are there exactly three icon buttons grouped together in the top-right corner of the screen (in the app's top bar)?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Are there exactly three icon buttons grouped together in the top-right corner of the screen (in the app's top bar)?", + "tag": "position" + }, + { + "test": "structure_gate_bottomnav", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_gate_bottomnav_vlm", + "passed": true, + "message": "VLM: Q='Is there a bottom navigation bar with exactly 3 evenly spaced items (each an icon with a label) across the bottom of the screen?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is there a bottom navigation bar with exactly 3 evenly spaced items (each an icon with a label) across the bottom of the screen?", + "tag": "position" + }, + { + "test": "structure_search_shape", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "EditText 0->1 on Search, restored on Exit search" + }, + { + "test": "structure_filter_sheet", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Sort-sheet appears (Sort/Display/Alphabetically), restored on back" + }, + { + "test": "structure_filter_sheet_vlm", + "passed": true, + "message": "VLM: Q='Is there a bottom sheet panel anchored to the bottom edge of the screen, overlaying the content above it?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is there a bottom sheet panel anchored to the bottom edge of the screen, overlaying the content above it?", + "tag": "position" + }, + { + "test": "structure_more_sheet", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "More-sheet appears (About app + Settings), restored on back" + }, + { + "test": "structure_filter_tab_swap", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Sort tab -> Display tab swaps sort options for display options" + }, + { + "test": "structure_selection_mode", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "long-press -> '1 selected' + selection actions, restored on back" + }, + { + "test": "structure_selection_mode_vlm", + "passed": true, + "message": "VLM: Q='Does the top bar show a selection count (like '1 selected') with several action icons to its right?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does the top bar show a selection count (like '1 selected') with several action icons to its right?", + "tag": "position" + }, + { + "test": "structure_tab_history", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Library grid -> History surface (Today group), Library covers gone" + }, + { + "test": "structure_tab_browse", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Library grid -> Browse surface, covers gone" + }, + { + "test": "structure_search_empty", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "search 'zzz' -> 0 covers, restored on exit search" + }, + { + "test": "structure_bookinfo_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "cover tap -> Book Info (Start/Move/Delete/Author), depth 1" + }, + { + "test": "structure_bookinfo_shape_vlm", + "passed": true, + "message": "VLM: Q='Is there a large primary action button spanning most of the screen width near the bottom of this book-detail screen?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is there a large primary action button spanning most of the screen width near the bottom of this book-detail screen?", + "tag": "size" + }, + { + "test": "structure_settings_root", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "More->Settings -> 5 category rows, depth 1" + }, + { + "test": "structure_appearance_dark_vlm", + "passed": true, + "message": "VLM: Q='Is the overall background of this screen dark (near-black or very dark grey) rather than white?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is the overall background of this screen dark (near-black or very dark grey) rather than white?", + "tag": "color" + }, + { + "test": "structure_appearance_puredark", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Enabled adds 'Pure dark' block, removed again on System (depth 2)" + }, + { + "test": "structure_reader_open", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "reader renders 'Chapter One' heading + body paragraph, depth 2" + }, + { + "test": "structure_reader_open_vlm", + "passed": true, + "message": "VLM: Q='Does a block of body text (multiple lines of a paragraph) fill most of the screen area?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does a block of body text (multiple lines of a paragraph) fill most of the screen area?", + "tag": "size" + }, + { + "test": "structure_reader_settings_sheet", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "reader -> Reader settings sheet (General/Reader/Colors), depth 3" + }, + { + "test": "structure_chapters_drawer", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "reader -> Chapters drawer (chapter list), depth 3" + }, + { + "test": "structure_library_grid_vlm", + "passed": true, + "message": "VLM: Q='Are there two book cover cards displayed side by side in the same row (a grid layout), rather than stacked vertically?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Are there two book cover cards displayed side by side in the same row (a grid layout), rather than stacked vertically?", + "tag": "shape" + } + ] +} \ No newline at end of file diff --git a/android/acclorite-book-story/tests/android_testgen_kit.py b/android/acclorite-book-story/tests/android_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6 --- /dev/null +++ b/android/acclorite-book-story/tests/android_testgen_kit.py @@ -0,0 +1,1910 @@ +#!/usr/bin/env python3 +"""Android TestGen Kit — the single source of every test helper, so a test's +NAVIGATION 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 package +name differs): always use the module-level PACKAGE (argv[1]). Never write a package +name, an .apk path, a /data/data path, or a pixel coordinate as a literal. + python3 android_testgen_kit.py lint_sources # flags all of those + +SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery): + python3 android_testgen_kit.py audit + python3 android_testgen_kit.py lint + python3 android_testgen_kit.py lint_sources + python3 android_testgen_kit.py audit_depth [results_dir] +""" +from __future__ import annotations + +import ast +import base64 +import functools +import glob +import hashlib +import json +import math +import os +import re +import shlex +import subprocess +import sys +import time +import urllib.error +import 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.0 +SETTLE = { + "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 /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 " list[dict]: + """XML -> list of attribute dicts, each with _bounds and _center.""" + nodes = [] + for m in re.finditer(r"]+?)/?>", 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} \n" + " android_testgen_kit.py audit_depth [results_dir]\n" + " android_testgen_kit.py score [manifest_dir]") diff --git a/android/acclorite-book-story/tests/android_text_eval.json b/android/acclorite-book-story/tests/android_text_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..6ab1b86e6fe2af5a66ccabab9fcf418424f87ee8 --- /dev/null +++ b/android/acclorite-book-story/tests/android_text_eval.json @@ -0,0 +1,230 @@ +{ + "module": "text", + "total": 22, + "passed": 22, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 22, + "passed": 22, + "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": 2, + "liveness": 0, + "interactive": 20, + "depth_ge1": 19, + "depth_ge2": 6, + "value": 3, + "vlm_fine": 0 + }, + "results": [ + { + "test": "text_empty_state_subtitle", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "Read your favorite books and sort them between categories" + }, + { + "test": "text_empty_state_cta", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "Add a book" + }, + { + "test": "text_search_hint", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "search field placeholder reads 'Search…'" + }, + { + "test": "text_filter_tabs", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Filter sheet tabs 'Sort' and 'Display'" + }, + { + "test": "text_filter_sort_options", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "sort options 'Alphabetically', 'Last read', 'Progress', 'Author'" + }, + { + "test": "text_more_sheet_items", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "More sheet items 'About app' and 'Settings'" + }, + { + "test": "text_bookinfo_no_description", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "No description." + }, + { + "test": "text_bookinfo_author", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Author label present with value 'Unknown'" + }, + { + "test": "text_bookinfo_start_button", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "button label 'Start'" + }, + { + "test": "text_settings_general_subtitle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "General row subtitle 'App language'" + }, + { + "test": "text_settings_appearance_subtitle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Appearance row subtitle 'Theme, colors'" + }, + { + "test": "text_settings_reader_subtitle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Reader row subtitle 'Font, text'" + }, + { + "test": "text_settings_library_subtitle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Library row subtitle 'Categories, display, tabs'" + }, + { + "test": "text_about_report_bug", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "About row label 'Report a bug'" + }, + { + "test": "text_about_licenses", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "About row label 'Open source licenses'" + }, + { + "test": "text_about_support_development", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "About row label 'Support development'" + }, + { + "test": "text_reader_chapter_heading", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "reader heading 'Chapter One'" + }, + { + "test": "text_reader_first_paragraph", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "reader body contains 'The quick brown fox jumps over the lazy dog.'" + }, + { + "test": "text_reader_topbar_title", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "reader top bar shows title 'testbook' and chapter 'Chapter One'" + }, + { + "test": "text_history_today_group", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "History date-group header 'Today'" + }, + { + "test": "text_history_book_title", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "History lists book title 'testbook'" + }, + { + "test": "text_browse_folder_path", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "/storage/emulated/0/Download/Books" + } + ] +} \ No newline at end of file diff --git a/android/acclorite-book-story/tests/book_fixture.py b/android/acclorite-book-story/tests/book_fixture.py new file mode 100644 index 0000000000000000000000000000000000000000..f3669612149bd533755b08fbe6595f3f6ca28044 --- /dev/null +++ b/android/acclorite-book-story/tests/book_fixture.py @@ -0,0 +1,241 @@ +"""Shared book-import fixture helper for Book Story reader tests. + +This module is imported (never inlined) by the test modules that need a real +book in the library or the reader open. It owns the full, portable path: + + push fixtures -> grant the Download/Books folder via SAF (once) -> + scan + add the book to the library -> open the reader. + +Every helper is idempotent and self-healing: it first checks whether the app is +already in the desired state, and only performs the setup work when it is not. +Nothing here writes a package name, an absolute app-data path, or a pixel +coordinate — the folder is located by its on-device name, which the kit derives +from the fixtures directory, so the identical flow runs on the recreation. +""" +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 + +# The book fixtures live in fixtures/Books/*.txt on the host, which the kit +# mirrors to /sdcard/Download/Books/*.txt on device (subdirs preserved). +BOOK_SUBDIR = "Books" +BOOK1_FILE = "testbook.txt" +BOOK1_TITLE = "testbook" +BOOK2_FILE = "alpha_wonderland.txt" +BOOK2_TITLE = "alpha_wonderland" + + +def _tab(nodes, label): + """Bottom-nav tab by its visible label (Library/History/Browse).""" + hits = [n for n in find_nodes(nodes, text=label)] + # the bottom-nav labels sit near the bottom of the screen + hits = sorted(hits, key=lambda n: n.get("_bounds", (0, 0, 0, 0))[1]) + for n in hits: + y = n.get("_bounds", (0, 0, 0, 0))[1] + if y > 2000: + return n + return hits[-1] if hits else None + + +def _open_tab(label): + nodes = ui() + t = _tab(nodes, label) + if t: + tap_node(t) + settle("tap") + return True + return False + + +def library_has_book(title, relaunch=True): + """True if `title` is currently shown on the Library screen.""" + if relaunch: + restart_app() + wait_for_foreground() + _open_tab("Library") + nodes = ui() + return find_node(nodes, text=title) is not None + + +def _folder_already_granted(): + """From the Browse tab, a granted folder makes the book file appear.""" + nodes = ui() + return find_node(nodes, text=BOOK1_FILE) is not None or \ + find_node(nodes, text=BOOK2_FILE) is not None + + +def grant_books_folder(): + """Grant the Download/Books folder through the SAF picker, once. + + Assumes the Browse tab is showing. Returns True when the folder is granted + (or was already). The grant survives restart/process-death but NOT a data + wipe, so callers that clear_data must re-grant. + """ + if _folder_already_granted(): + return True + nodes = ui() + setup = find_node(nodes, text="Set up scanning") + if setup: + tap_node(setup) + settle("launch") + else: + # Browse settings reachable via the More menu if the empty-state CTA is gone + more = find_node(nodes, content_desc="More") + if more: + tap_node(more) + settle("tap") + nodes = ui() + sett = find_node_ci(nodes, "Scanning") or find_node_ci(nodes, "Settings") + if sett: + tap_node(sett) + settle("launch") + time.sleep(1) + nodes = ui() + addf = find_node(nodes, text="Add folder") + if not addf: + return _folder_already_granted() + tap_node(addf) + settle("launch") + time.sleep(1.5) + # SAF picker: sdk_gphone -> Download -> Books -> USE THIS FOLDER -> ALLOW + for _ in range(8): + if find_node(ui(), text="Download"): + break + time.sleep(1) + dl = find_node(ui(), text="Download") + if not dl: + return False + tap_node(dl) + settle("launch") + time.sleep(1.5) + bk = find_node(ui(), text=BOOK_SUBDIR) + if not bk: + return False + tap_node(bk) + settle("launch") + time.sleep(1.5) + use = find_node(ui(), text="USE THIS FOLDER") + if not use: + return False + tap_node(use) + settle("launch") + time.sleep(1.5) + allow = find_node_ci(ui(), "ALLOW") + if allow: + tap_node(allow) + settle("launch") + time.sleep(2.5) + # We are now back on the Browse settings screen; pop to the Browse tab. + back() + settle("tap") + time.sleep(1) + return _folder_already_granted() or True + + +def import_book(title=BOOK1_TITLE, book_file=BOOK1_FILE): + """Ensure `title` is in the Library. Idempotent. + + Returns (ok: bool, note: str). `note` is one of already / imported / + setup_failed: so a caller can produce an honest failure message. + """ + push_fixtures() + restart_app() + wait_for_foreground() + _open_tab("Library") + if find_node(ui(), text=title): + return True, "already" + + if not _open_tab("Browse"): + return False, "setup_failed: no Browse tab" + if not _folder_already_granted(): + grant_books_folder() + # grant_books_folder may leave us in settings; return to Browse tab + if not _folder_already_granted(): + _open_tab("Browse") + # Scan may take a moment to surface the file. + bf = None + for _ in range(6): + bf = find_node(ui(), text=book_file) + if bf: + break + time.sleep(1) + if not bf: + return False, "setup_failed: book file not found in Browse after grant" + tap_node(bf) + settle("tap") + add = find_node(ui(), content_desc="Add files") + if not add: + return False, "setup_failed: Add files action missing" + tap_node(add) + settle("launch") + ok_btn = find_node(ui(), text="OK") + if ok_btn: + tap_node(ok_btn) + settle("launch") + time.sleep(3) + _open_tab("Library") + if find_node(ui(), text=title): + return True, "imported" + return False, "setup_failed: book not in library after add" + + +def open_book_info(title=BOOK1_TITLE): + """From the Library, tap the book's cover to open its Book Info screen. + Returns True on success. Assumes the book is already imported.""" + restart_app() + wait_for_foreground() + _open_tab("Library") + nodes = ui() + # The cover is the tappable card; find the title label then tap the cover + # that sits above/left of it. The cover has content-desc "Cover image ...". + cover = find_node(nodes, content_desc="Cover image not found") + if cover is None: + covers = [n for n in nodes if "Cover image" in (n.get("content-desc") or "")] + cover = covers[0] if covers else None + if cover is None: + return False + if not tap_node(cover): + return False + settle("launch") + # Book Info shows a "Start"/"Continue" button and Move/Delete + nodes = ui() + return (find_node(nodes, text="Start") is not None or + find_node(nodes, text="Continue") is not None or + find_node(nodes, text="Move") is not None) + + +def open_reader(title=BOOK1_TITLE): + """Open the reader on `title` and return True once book text is showing. + + Dismisses the one-time immersive-mode system cling if it appears. + """ + if not open_book_info(title): + return False + nodes = ui() + start = find_node(nodes, text="Start") or find_node(nodes, text="Continue") + if not start: + return False + tap_node(start) + settle("launch") + time.sleep(2) + # Dismiss the system "Viewing full screen / Got it" cling if present. + got = find_node(ui(), text="Got it") + if got: + tap_node(got) + settle("tap") + time.sleep(1) + nodes = ui() + return find_node(nodes, text="Chapter One") is not None or len( + [n for n in nodes if len(n.get("text", "")) > 40]) > 0 + + +def reader_show_menu(): + """Inside the reader, tap the center to toggle the top/bottom reader bars. + Returns the node list after the tap.""" + info = get_screen_info() + tap(info["center_x"], info["center_y"]) + settle("tap") + return ui() diff --git a/android/acclorite-book-story/tests/conftest.py b/android/acclorite-book-story/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27 --- /dev/null +++ b/android/acclorite-book-story/tests/conftest.py @@ -0,0 +1 @@ +pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"] diff --git a/android/acclorite-book-story/tests/fixtures/BookStoryTest/test_book.txt b/android/acclorite-book-story/tests/fixtures/BookStoryTest/test_book.txt new file mode 100644 index 0000000000000000000000000000000000000000..2384cd4fc9ee4bcae7fb35f93bc57ae60424a136 --- /dev/null +++ b/android/acclorite-book-story/tests/fixtures/BookStoryTest/test_book.txt @@ -0,0 +1,43 @@ +The Test Chronicle + +by Recon Author + +Chapter 1 + +This is paragraph 1 of chapter 1. The quick brown fox jumps over the lazy dog. This is paragraph 1 of chapter 1. The quick brown fox jumps over the lazy dog. This is paragraph 1 of chapter 1. The quick brown fox jumps over the lazy dog. + +This is paragraph 2 of chapter 1. The quick brown fox jumps over the lazy dog. This is paragraph 2 of chapter 1. The quick brown fox jumps over the lazy dog. This is paragraph 2 of chapter 1. The quick brown fox jumps over the lazy dog. + +This is paragraph 3 of chapter 1. The quick brown fox jumps over the lazy dog. This is paragraph 3 of chapter 1. The quick brown fox jumps over the lazy dog. This is paragraph 3 of chapter 1. The quick brown fox jumps over the lazy dog. + +Chapter 2 + +This is paragraph 1 of chapter 2. The quick brown fox jumps over the lazy dog. This is paragraph 1 of chapter 2. The quick brown fox jumps over the lazy dog. This is paragraph 1 of chapter 2. The quick brown fox jumps over the lazy dog. + +This is paragraph 2 of chapter 2. The quick brown fox jumps over the lazy dog. This is paragraph 2 of chapter 2. The quick brown fox jumps over the lazy dog. This is paragraph 2 of chapter 2. The quick brown fox jumps over the lazy dog. + +This is paragraph 3 of chapter 2. The quick brown fox jumps over the lazy dog. This is paragraph 3 of chapter 2. The quick brown fox jumps over the lazy dog. This is paragraph 3 of chapter 2. The quick brown fox jumps over the lazy dog. + +Chapter 3 + +This is paragraph 1 of chapter 3. The quick brown fox jumps over the lazy dog. This is paragraph 1 of chapter 3. The quick brown fox jumps over the lazy dog. This is paragraph 1 of chapter 3. The quick brown fox jumps over the lazy dog. + +This is paragraph 2 of chapter 3. The quick brown fox jumps over the lazy dog. This is paragraph 2 of chapter 3. The quick brown fox jumps over the lazy dog. This is paragraph 2 of chapter 3. The quick brown fox jumps over the lazy dog. + +This is paragraph 3 of chapter 3. The quick brown fox jumps over the lazy dog. This is paragraph 3 of chapter 3. The quick brown fox jumps over the lazy dog. This is paragraph 3 of chapter 3. The quick brown fox jumps over the lazy dog. + +Chapter 4 + +This is paragraph 1 of chapter 4. The quick brown fox jumps over the lazy dog. This is paragraph 1 of chapter 4. The quick brown fox jumps over the lazy dog. This is paragraph 1 of chapter 4. The quick brown fox jumps over the lazy dog. + +This is paragraph 2 of chapter 4. The quick brown fox jumps over the lazy dog. This is paragraph 2 of chapter 4. The quick brown fox jumps over the lazy dog. This is paragraph 2 of chapter 4. The quick brown fox jumps over the lazy dog. + +This is paragraph 3 of chapter 4. The quick brown fox jumps over the lazy dog. This is paragraph 3 of chapter 4. The quick brown fox jumps over the lazy dog. This is paragraph 3 of chapter 4. The quick brown fox jumps over the lazy dog. + +Chapter 5 + +This is paragraph 1 of chapter 5. The quick brown fox jumps over the lazy dog. This is paragraph 1 of chapter 5. The quick brown fox jumps over the lazy dog. This is paragraph 1 of chapter 5. The quick brown fox jumps over the lazy dog. + +This is paragraph 2 of chapter 5. The quick brown fox jumps over the lazy dog. This is paragraph 2 of chapter 5. The quick brown fox jumps over the lazy dog. This is paragraph 2 of chapter 5. The quick brown fox jumps over the lazy dog. + +This is paragraph 3 of chapter 5. The quick brown fox jumps over the lazy dog. This is paragraph 3 of chapter 5. The quick brown fox jumps over the lazy dog. This is paragraph 3 of chapter 5. The quick brown fox jumps over the lazy dog. diff --git a/android/acclorite-book-story/tests/fixtures/Books/alpha_wonderland.txt b/android/acclorite-book-story/tests/fixtures/Books/alpha_wonderland.txt new file mode 100644 index 0000000000000000000000000000000000000000..5b9476929dde0d7ae5f0165cce6ee849d1ceefed --- /dev/null +++ b/android/acclorite-book-story/tests/fixtures/Books/alpha_wonderland.txt @@ -0,0 +1,7 @@ +Introduction + +Alpha Wonderland is a distinct sample title used so the test suite can search and filter between multiple books in the library without ambiguity. + +Section One + +This book exists purely to provide a second, uniquely named record for multi-book integrity and search tests. Its content differs from the first sample book on every line. diff --git a/android/acclorite-book-story/tests/fixtures/Books/testbook.txt b/android/acclorite-book-story/tests/fixtures/Books/testbook.txt new file mode 100644 index 0000000000000000000000000000000000000000..fadc36af4d174b44b08ef5289cda5c8a2cd0a684 --- /dev/null +++ b/android/acclorite-book-story/tests/fixtures/Books/testbook.txt @@ -0,0 +1,11 @@ +Chapter One + +The quick brown fox jumps over the lazy dog. This is a sample book for testing the Book Story reader application. It contains multiple paragraphs of readable text that the reader will render on screen. + +This second paragraph of the first chapter gives the reader more content to display and lets us verify that scrolling and pagination work as intended inside the reader view. + +Chapter Two + +Reading is a wonderful activity that expands the mind. This second chapter continues the story with more sample content for the reader to display on screen. + +The story concludes here with a final paragraph that marks the end of the sample book used throughout the automated behavioral test suite for this reader application. diff --git a/android/acclorite-book-story/tests/requirements.txt b/android/acclorite-book-story/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c --- /dev/null +++ b/android/acclorite-book-story/tests/requirements.txt @@ -0,0 +1,2 @@ +pytest +pillow diff --git a/android/acclorite-book-story/tests/test_android_computation.py b/android/acclorite-book-story/tests/test_android_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..ff4486bba4ef146fc5f36a9e5b02af02cdcfaa12 --- /dev/null +++ b/android/acclorite-book-story/tests/test_android_computation.py @@ -0,0 +1,750 @@ +#!/usr/bin/env python3 +"""COMPUTATION module — CORE FUNCTION input -> output for Book's Story. + +Lane: the app's derived/computed values. SOLE OWNER of jump_kind="value". Every +test feeds an INPUT (a typed search query, opening a record, reaching a settings +sheet) and asserts a SPECIFIC value the running original produced — never a value +computed here or read from the source. + +Ground truth — every value below was OBSERVED on the running original with scratch +scripts before it was hard-coded (recon's numbers were partly stale; these are the +device's own): + + Library SEARCH (Library tab, Search icon -> single EditText, live filter; the DB + query is LOWER(title) LIKE '%q%' — case-insensitive substring on TITLE only): + * "" -> both {testbook, alpha_wonderland}; count badge "2" + * "alpha" -> {alpha_wonderland}; badge "1" + * "testbook" -> {testbook}; badge "1" + * "book" -> {testbook} ONLY (alpha_wonderland's title has no "book") + * "wonderland" -> {alpha_wonderland}; badge "1" + * "zzz" -> {} (none); badge "0" + * type "alpha" then tap "Exit search" -> both restored (round-trip) + Library title count badge = number of book cards (2). The "Default" category tab + badge tracks the CURRENT filtered count (2 -> 1 -> 0). + Book Info (tap a cover) -> progress reads "0%" for a never-opened book. + Reader (Start) bottom progress reads "0% (20%)" for testbook page 1 (leading + token "0%"; the "(20%)" is this book's chapter fraction). + Reader settings sheet ("Reader settings" icon) tabs General/Reader/Colors: + * Reader tab: Font size "16pt", Letter spacing "0pt", Size "80%", + Corners roundness "8pt". + * Colors tab (Color preset "Preset 1"): Background color R/G/B = 250/248/255, + Font color R/G/B = 68/70/79. + +Depth is REAL: Book Info = 1 (and_reach_book_info), Reader = 2 (and_reach_reader), +the reader settings sheet = 3 (and_enter_reader_sheet). Never clear_data() — the +library persists across restart_app(); each test opens its own entry point. +""" +import os +import sys +import time + +# ADB_PATH / DEVICE_SERIAL / PACKAGE come from the environment the runner exports; +# the kit reads them via os.environ / argv. Never bake a serial/package/adb path in. +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 +import book_fixture as bf # shared, validated import helper + +COVER_DESC = "Cover image not found" +BOOK1 = bf.BOOK1_TITLE # "testbook" +BOOK1_FILE = bf.BOOK1_FILE # "testbook.txt" +BOOK2 = bf.BOOK2_TITLE # "alpha_wonderland" +BOOK2_FILE = bf.BOOK2_FILE # "alpha_wonderland.txt" + +TESTS = [] + + +def _t(fn): + TESTS.append(fn) + return fn + + +# ── entry-point helpers ────────────────────────────────────────────────────── + +def _reach_library(retries: int = 6) -> bool: + """Bring the app to the Library tab with a book visible. Absorbs the launch + race (monkey reports foreground a beat before Compose paints).""" + wait_for_foreground() + for _ in range(retries): + bf._open_tab("Library") + nodes = ui() + if (find_node(nodes, content_desc=COVER_DESC) is not None + or find_node(nodes, text=BOOK1) is not None): + return True + settle("tap") + return False + + +def _ensure_both_books() -> bool: + """Idempotent guard: both persisted books present (fast 'already' path).""" + ok1, _ = bf.import_book(BOOK1, BOOK1_FILE) + ok2, _ = bf.import_book(BOOK2, BOOK2_FILE) + return ok1 and ok2 + + +def _library_titles(): + """The set of KNOWN book titles currently visible on the Library screen.""" + nodes = ui() + return {tt for tt in (BOOK1, BOOK2) if find_node(nodes, text=tt) is not None} + + +def _open_search() -> bool: + """From the Library, tap the Search icon and confirm the query field appeared.""" + s = find_node(ui(), content_desc="Search") + if s is None or not tap_node(s): + return False + settle("tap") + time.sleep(0.8) + return len(find_by_class(ui(), "EditText")) > 0 + + +def _search_field(): + edits = find_by_class(ui(), "EditText") + return edits[0] if edits else None + + +def _category_badge_value(): + """The 'Default' category tab count badge — a digit TextView just right of the + 'Default' label (y in the tab strip, x to its right). Returns the string or ''.""" + nodes = ui() + default = find_node(nodes, text="Default") + if default is None: + return "" + dx1, dy1, dx2, dy2 = default["_bounds"] + best = "" + for n in nodes: + t = n.get("text", "").strip() + if not t.isdigit(): + continue + b = n.get("_bounds") + if not b: + continue + # same row as the Default tab, immediately to its right + if abs(b[1] - dy1) < 60 and b[0] >= dx2 - 20: + best = t + break + return best + + +def _library_title_badge_value(): + """The Library screen title's count badge — a digit TextView on the 'Library' + title row (top bar), to the right of the 'Library' title text.""" + nodes = ui() + # The top-bar 'Library' title sits high (y<300); the tab label sits low (y>2200). + titles = [n for n in find_nodes(nodes, text="Library") + if n.get("_bounds") and n["_bounds"][1] < 400] + if not titles: + return "" + tx1, ty1, tx2, ty2 = titles[0]["_bounds"] + for n in nodes: + t = n.get("text", "").strip() + if not t.isdigit(): + continue + b = n.get("_bounds") + if b and abs(b[1] - ty1) < 80 and b[0] >= tx2 - 20: + return t + return "" + + +# ── depth-backing navigation helpers (name-matched by and_audit_depth) ──────── + +def and_reach_book_info(title=BOOK1) -> bool: + """Tap the book's cover and PROVE the jump into Book Info. Backs depth 1.""" + nodes = ui() + cover = find_node(nodes, content_desc=COVER_DESC) + if cover is None: + covers = [n for n in nodes if "Cover image" in (n.get("content-desc") or "")] + cover = covers[0] if covers else None + if cover is None: + return False + if and_reach_surface(cover, target="Start", source="Continue reading"): + return True + return find_node(ui(), text="Move") is not None + + +def and_reach_reader() -> bool: + """From Book Info tap Start; confirm reader body text rendered. Backs depth 2 + (immersive reader has no reliable pre-cling surface diff, so and_enter).""" + start = find_node(ui(), text="Start") or find_node(ui(), text="Continue") + if start is None or not tap_node(start): + return False + settle("launch") + time.sleep(1.5) + got = find_node(ui(), text="Got it") # one-time immersive cling + if got: + tap_node(got) + settle("tap") + and_enter("reader") + return find_node(ui(), text="Chapter One") is not None + + +def and_enter_reader_sheet() -> bool: + """From inside the reader, reveal the bars and open the Reader settings sheet. + Confirms the sheet's tab row (General/Reader/Colors) appeared. Backs depth 3.""" + info = get_screen_info() + tap(info["center_x"], info["center_y"]) # toggle bars + settle("tap") + time.sleep(1) + rs = find_node(ui(), content_desc="Reader settings") + if rs is None or not tap_node(rs): + return False + settle("launch") + time.sleep(1) + nodes = ui() + ok = (find_node(nodes, text="Colors") is not None + and find_node(nodes, text="Reader") is not None) + if ok: + and_enter("reader_settings_sheet") + return ok + + +def _open_reader_sheet_tab(tab_text: str) -> bool: + """Inside the open Reader settings sheet, switch to a named tab.""" + tab = find_node(ui(), text=tab_text) + if tab is None or not tap_node(tab): + return False + settle("tap") + time.sleep(0.6) + return True + + +def _label_value_below(section_text: str, suffix_ok=("pt", "%")): + """The value label rendered directly BELOW a section header (e.g. '16pt' under + 'Font size'). Returns the first suffix-matching TextView whose top is just + beneath the header and horizontally aligned with it. '' if not found.""" + nodes = ui() + header = find_node(nodes, text=section_text) + if header is None: + return "" + hx1, hy1, hx2, hy2 = header["_bounds"] + cands = [] + for n in nodes: + t = n.get("text", "").strip() + if not t or not any(t.endswith(s) for s in suffix_ok): + continue + b = n.get("_bounds") + if not b: + continue + # below the header, left-aligned with it, within a slider block + if b[1] >= hy1 and (b[1] - hy2) < 220 and abs(b[0] - hx1) < 80: + cands.append((b[1], t)) + cands.sort() + return cands[0][1] if cands else "" + + +def _rgb_values_after(section_text: str, n_values=3): + """The N numeric slider values rendered after a colour section header (the R, + G, B labels under 'Background color' / 'Font color'). Order = top-to-bottom.""" + nodes = ui() + header = find_node(nodes, text=section_text) + if header is None: + return [] + hy = header["_bounds"][1] + vals = [] + for n in nodes: + t = n.get("text", "").strip() + if not (t.isdigit() and 0 <= int(t) <= 255): + continue + b = n.get("_bounds") + if b and b[1] > hy: + vals.append((b[1], t)) + vals.sort() + return [v for _y, v in vals[:n_values]] + + +def _screenshot(name): + p = os.path.join(RESULTS_DIR, "screenshots", f"_computation_{name}.png") + screencap(p) + return p + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1. Library SEARCH — the cleanest input->output (5 filter cases + round-trip) +# ══════════════════════════════════════════════════════════════════════════════ + +def _run_search_case(name, query, expected_set, expect_str): + """Shared body: open Library search, type `query`, assert the visible KNOWN + titles equal `expected_set`. A positive/negative pair is baked in — for a + single-result query the OTHER book must be ABSENT after being present before.""" + if not _ensure_both_books(): + record(name, False, "setup_failed: could not ensure both books present", + depth=0, jump_kind="value", expect=expect_str) + return + restart_app() + if not _reach_library(): + record(name, False, "setup_failed: Library not reachable", + depth=0, jump_kind="value", expect=expect_str) + return + before = _library_titles() + if not _open_search(): + record(name, False, "setup_failed: search field did not open", + depth=0, jump_kind="value", expect=expect_str) + return + field = _search_field() + if field is None or not type_text(field, query): + record(name, False, "setup_failed: could not type into the search field", + depth=0, jump_kind="value", expect=expect_str) + return + time.sleep(1.2) + got = _library_titles() + # both books must have been present before we filtered (guards a mis-setup) + both_before = before == {BOOK1, BOOK2} + ok = both_before and got == expected_set + record(name, ok, + "" if ok else + f"behavior_wrong: query {query!r} left {sorted(got)}, expected " + f"{sorted(expected_set)} (before filter: {sorted(before)})", + depth=0, jump_kind="value", expect=expect_str) + + +@_t +@and_test(expects=("computation_search_alpha",)) +def test_search_alpha(): + _run_search_case("computation_search_alpha", "alpha", {BOOK2}, + "search 'alpha' -> alpha_wonderland only") + + +@_t +@and_test(expects=("computation_search_testbook",)) +def test_search_testbook(): + _run_search_case("computation_search_testbook", "testbook", {BOOK1}, + "search 'testbook' -> testbook only") + + +@_t +@and_test(expects=("computation_search_book",)) +def test_search_book(): + # 'book' is a substring of 'testbook' but NOT of 'alpha_wonderland' -> only testbook + _run_search_case("computation_search_book", "book", {BOOK1}, + "search 'book' -> testbook only (alpha_wonderland excluded)") + + +@_t +@and_test(expects=("computation_search_wonderland",)) +def test_search_wonderland(): + _run_search_case("computation_search_wonderland", "wonderland", {BOOK2}, + "search 'wonderland' -> alpha_wonderland only") + + +@_t +@and_test(expects=("computation_search_no_match",)) +def test_search_no_match(): + _run_search_case("computation_search_no_match", "zzz", set(), + "search 'zzz' -> no books") + + +@_t +@and_test(expects=("computation_search_clear_restores",)) +def test_search_clear_restores(): + """Round-trip: type 'alpha' (one book), tap 'Exit search', both books return. + The OUTPUT set goes {both} -> {one} -> {both}: a positive/negative/positive + over the SAME surface.""" + name = "computation_search_clear_restores" + expect_str = "after 'alpha' then Exit search -> both books restored" + if not _ensure_both_books(): + record(name, False, "setup_failed: could not ensure both books present", + depth=0, jump_kind="value", expect=expect_str) + return + restart_app() + if not _reach_library(): + record(name, False, "setup_failed: Library not reachable", + depth=0, jump_kind="value", expect=expect_str) + return + if not _open_search(): + record(name, False, "setup_failed: search field did not open", + depth=0, jump_kind="value", expect=expect_str) + return + field = _search_field() + if field is None or not type_text(field, "alpha"): + record(name, False, "setup_failed: could not type into the search field", + depth=0, jump_kind="value", expect=expect_str) + return + time.sleep(1.2) + filtered = _library_titles() + ex = find_node(ui(), content_desc="Exit search") + if ex is None or not tap_node(ex): + record(name, False, "behavior_wrong: no 'Exit search' affordance to clear", + depth=0, jump_kind="value", expect=expect_str) + return + settle("tap") + time.sleep(1) + restored = _library_titles() + ok = filtered == {BOOK2} and restored == {BOOK1, BOOK2} + record(name, ok, + "" if ok else + f"behavior_wrong: filtered={sorted(filtered)} then restored=" + f"{sorted(restored)}, expected {{alpha_wonderland}} then both", + depth=0, jump_kind="value", expect=expect_str) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2. Count badges — a DERIVED value (badge == number of matching book cards) +# ══════════════════════════════════════════════════════════════════════════════ + +@_t +@and_test(expects=("computation_library_count_badge",)) +def test_library_count_badge(): + """The Library title badge equals the number of book cards on screen. With the + two persisted books it reads '2' and matches the card count we observe — a + self-consistent computation, not a constant.""" + name = "computation_library_count_badge" + if not _ensure_both_books(): + record(name, False, "setup_failed: could not ensure both books present", + depth=0, jump_kind="value", expect="Library count badge == 2 == #cards") + return + restart_app() + if not _reach_library(): + record(name, False, "setup_failed: Library not reachable", + depth=0, jump_kind="value", expect="Library count badge == 2 == #cards") + return + nodes = ui() + cards = len([n for n in nodes if (n.get("content-desc") or "") == COVER_DESC]) + badge = _library_title_badge_value() or _category_badge_value() + ok = badge.isdigit() and int(badge) == cards == 2 + record(name, ok, + "" if ok else + f"behavior_wrong: badge={badge!r} but observed {cards} book cards " + f"(expected both == '2')", + depth=0, jump_kind="value", expect="Library count badge == 2 (== 2 cards)") + + +@_t +@and_test(expects=("computation_search_count_badge",)) +def test_search_count_badge(): + """Search-result count consistency: after typing 'alpha' the 'Default' category + badge reads '1' and exactly one known title remains — the badge is the derived + count of the filtered set.""" + name = "computation_search_count_badge" + expect_str = "after 'alpha' the count badge reads '1' (one visible book)" + restart_app() + if not _reach_library(): + record(name, False, "setup_failed: Library not reachable", + depth=0, jump_kind="value", expect=expect_str) + return + before_badge = _category_badge_value() + if not _open_search(): + record(name, False, "setup_failed: search field did not open", + depth=0, jump_kind="value", expect=expect_str) + return + field = _search_field() + if field is None or not type_text(field, "alpha"): + record(name, False, "setup_failed: could not type into the search field", + depth=0, jump_kind="value", expect=expect_str) + return + time.sleep(1.2) + badge = _category_badge_value() + visible = _library_titles() + ok = before_badge == "2" and badge == "1" and visible == {BOOK2} + record(name, ok, + "" if ok else + f"behavior_wrong: badge {before_badge!r}->{badge!r}, visible " + f"{sorted(visible)}; expected '2'->'1' with only alpha_wonderland", + depth=0, jump_kind="value", expect=expect_str) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3. Book Info progress value (depth 1) +# ══════════════════════════════════════════════════════════════════════════════ + +@_t +@and_test(expects=("computation_book_info_progress",)) +def test_book_info_progress(): + """A never-opened book reads 0% on its Book Info screen — the app's derived + reading-progress value. Depth 1, backed by and_reach_book_info.""" + name = "computation_book_info_progress" + expect_str = "Book Info progress reads '0%'" + restart_app() + if not _reach_library(): + record(name, False, "setup_failed: Library not reachable", + depth=1, jump_kind="value", expect=expect_str) + return + if not and_reach_book_info(BOOK1): + record(name, False, "setup_failed: could not open Book Info", + depth=1, jump_kind="value", expect=expect_str) + return + nodes = ui() + # the progress value is a TextView ending in '%' on the Book Info header + pct = "" + for n in nodes: + t = n.get("text", "").strip() + if t.endswith("%") and t[:-1].strip().replace(".", "").isdigit(): + pct = t + break + ok = pct.replace(" ", "") == "0%" + record(name, ok, + "" if ok else + f"behavior_wrong: Book Info progress reads {pct!r}, expected '0%'", + depth=1, jump_kind="value", expect=expect_str) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4. Reader progress readout (depth 2) +# ══════════════════════════════════════════════════════════════════════════════ + +@_t +@and_test(expects=("computation_reader_progress",)) +def test_reader_progress(): + """The reader's bottom progress readout is a COMPUTED string: bookProgress% + + ' (chapterProgress%)'. For testbook page 1 it reads '0% (20%)'. We assert the + full observed string, then (fallback) the stable leading '0%' token. Depth 2.""" + name = "computation_reader_progress" + expect_str = "reader progress reads '0% (20%)' (leading '0%')" + restart_app() + if not _reach_library(): + record(name, False, "setup_failed: Library not reachable", + depth=2, jump_kind="value", expect=expect_str) + return + if not and_reach_book_info(BOOK1): + record(name, False, "setup_failed: could not open Book Info", + depth=1, jump_kind="value", expect=expect_str) + return + if not and_reach_reader(): + record(name, False, "setup_failed: reader did not render book text", + depth=2, jump_kind="value", expect=expect_str) + return + # reveal the bars, then read the bottom progress TextView + info = get_screen_info() + tap(info["center_x"], info["center_y"]) + settle("tap") + time.sleep(1) + nodes = ui() + progress = "" + for n in nodes: + t = n.get("text", "").strip() + b = n.get("_bounds") + # the progress readout is a lone '..%..' TextView low on screen + if b and b[1] > info["height"] * 0.8 and "%" in t and "(" in t: + progress = t + break + if not progress: + # fallback: any low TextView containing a leading percentage + for n in nodes: + t = n.get("text", "").strip() + b = n.get("_bounds") + if b and b[1] > info["height"] * 0.8 and t.replace(" ", "").startswith("0%"): + progress = t + break + norm = progress.replace(" ", "") + ok = norm == "0%(20%)" or norm.startswith("0%") + record(name, ok, + "" if ok else + f"behavior_wrong: reader progress reads {progress!r}, expected " + f"'0% (20%)' (or a leading '0%')", + depth=2, jump_kind="value", expect=expect_str) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5. Reader settings sheet — computed value LABELS (depth 3, Reader tab) +# ══════════════════════════════════════════════════════════════════════════════ + +def _reach_reader_settings_tab(tab_text): + """Full path to a named tab of the reader settings sheet. Returns True with the + sheet open on `tab_text`, else False. Crosses Library->BookInfo->Reader->Sheet.""" + if not _reach_library(): + return False + if not and_reach_book_info(BOOK1): + return False + if not and_reach_reader(): + return False + if not and_enter_reader_sheet(): + return False + return _open_reader_sheet_tab(tab_text) + + +def _run_reader_label_case(name, section, expected, expect_str, scrolls=3): + """Open the reader sheet's Reader tab, scroll to `section`, assert its value + label. Depth 3 throughout (backed by the and_reach_/and_enter_ chain).""" + restart_app() + if not _reach_reader_settings_tab("Reader"): + record(name, False, "setup_failed: could not reach the reader settings 'Reader' tab", + depth=3, jump_kind="value", expect=expect_str) + return + # scroll the sheet until the section header is on screen + found = find_node(ui(), text=section) is not None + for _ in range(scrolls): + if found: + break + scroll_down(0.5) + time.sleep(0.4) + found = find_node(ui(), text=section) is not None + if not found: + record(name, False, f"setup_failed: '{section}' not found in the Reader tab", + depth=3, jump_kind="value", expect=expect_str) + return + val = _label_value_below(section) + ok = val.replace(" ", "") == expected + record(name, ok, + "" if ok else + f"behavior_wrong: '{section}' value reads {val!r}, expected {expected!r}", + depth=3, jump_kind="value", expect=expect_str) + + +@_t +@and_test(expects=("computation_font_size_label",)) +def test_font_size_label(): + _run_reader_label_case("computation_font_size_label", "Font size", "16pt", + "reader 'Font size' value label reads '16pt'") + + +@_t +@and_test(expects=("computation_letter_spacing_label",)) +def test_letter_spacing_label(): + _run_reader_label_case("computation_letter_spacing_label", "Letter spacing", "0pt", + "reader 'Letter spacing' value label reads '0pt'") + + +@_t +@and_test(expects=("computation_size_percent_label",)) +def test_size_percent_label(): + _run_reader_label_case("computation_size_percent_label", "Size", "80%", + "reader 'Size' value label reads '80%'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 6. Reader settings Colors tab — RGB numeric values + rendered reader colours +# ══════════════════════════════════════════════════════════════════════════════ + +@_t +@and_test(expects=("computation_bg_color_red",)) +def test_background_color_red(): + """The Colors tab shows the Background colour as three stored channel values + R/G/B = 250/248/255 for 'Preset 1'. We assert the Red channel == '250' — a + value the app computes/stores, read out of the slider label. Depth 3.""" + name = "computation_bg_color_red" + expect_str = "Background color Red channel reads '250'" + restart_app() + if not _reach_reader_settings_tab("Colors"): + record(name, False, "setup_failed: could not reach the reader settings 'Colors' tab", + depth=3, jump_kind="value", expect=expect_str) + return + # scroll to the Background color section if needed + for _ in range(3): + if find_node(ui(), text="Background color") is not None: + break + scroll_down(0.4) + time.sleep(0.4) + vals = _rgb_values_after("Background color", 3) + red = vals[0] if vals else "" + ok = red == "250" + record(name, ok, + "" if ok else + f"behavior_wrong: Background R reads {red!r} (all={vals}), expected '250'", + depth=3, jump_kind="value", expect=expect_str) + + +@_t +@and_test(expects=("computation_font_color_red",)) +def test_font_color_red(): + """The Font colour's first stored channel R == '68' for 'Preset 1'. A distinct + computed value from the background, read out of its slider label. Depth 3.""" + name = "computation_font_color_red" + expect_str = "Font color Red channel reads '68'" + restart_app() + if not _reach_reader_settings_tab("Colors"): + record(name, False, "setup_failed: could not reach the reader settings 'Colors' tab", + depth=3, jump_kind="value", expect=expect_str) + return + # The 'Font color' section sits low; its header must be scrolled into the + # UPPER half so its three R/G/B digit labels are actually on-screen below it + # (when the header is near the bottom, the digits are clipped off and read ''). + half = get_screen_info()["height"] * 0.55 + for _ in range(8): + fc = find_node(ui(), text="Font color") + if fc is not None and fc["_bounds"][1] < half: + break + scroll_down(0.4) + time.sleep(0.4) + vals = _rgb_values_after("Font color", 3) + red = vals[0] if vals else "" + ok = red == "68" + record(name, ok, + "" if ok else + f"behavior_wrong: Font R reads {red!r} (all={vals}), expected '68'", + depth=3, jump_kind="value", expect=expect_str) + + +# ── VLM (exactly 3, all tag='color') — the RGB NUMBER is dump-readable but the +# rendered reader page and text colours are not; each question a blank screen +# fails. ──────────────────────────────────────────────────────────────────── + +@_t +@and_test(expects=("computation_bg_swatch_vlm",)) +def test_background_swatch_vlm(): + """The Background colour (R/G/B=250/248/255) renders as a near-white/very-pale + reader page — the rendered hue, not the number.""" + name = "computation_bg_swatch_vlm" + restart_app() + if not _reach_reader_settings_tab("Colors"): + record(name, False, "setup_failed: could not reach the Colors tab", + depth=3, jump_kind="none", tag="color") + return + for _ in range(3): + if find_node(ui(), text="Background color") is not None: + break + scroll_down(0.4) + time.sleep(0.4) + _screenshot("bg_swatch") + vlm_assert( + "computation_bg_swatch", + "In the visible 'Chapter One' reader area above the colour settings panel, " + "is the page background rendered white or a very pale/near-white shade " + "rather than a dark or saturated colour?", + RESULTS_DIR, expect="YES", depth=3, jump_kind="none", tag="color") + + +@_t +@and_test(expects=("computation_font_swatch_vlm",)) +def test_font_swatch_vlm(): + """The Font colour (R/G/B=68/70/79) renders as dark/near-black reader text, + visibly distinct from the pale page background.""" + name = "computation_font_swatch_vlm" + restart_app() + if not _reach_reader_settings_tab("Colors"): + record(name, False, "setup_failed: could not reach the Colors tab", + depth=3, jump_kind="none", tag="color") + return + for _ in range(4): + if find_node(ui(), text="Font color") is not None: + break + scroll_down(0.5) + time.sleep(0.4) + _screenshot("font_swatch") + vlm_assert( + "computation_font_swatch", + "In the visible 'Chapter One' reader area above the colour settings panel, " + "is the body text rendered dark gray or near-black rather than white or " + "another pale shade?", + RESULTS_DIR, expect="YES", depth=3, jump_kind="none", tag="color") + + +@_t +@and_test(expects=("computation_swatches_differ_vlm",)) +def test_swatches_differ_vlm(): + """The pale page and dark font render with clear readable contrast — a visual + property the RGB values in the accessibility dump alone cannot confirm.""" + name = "computation_swatches_differ_vlm" + restart_app() + if not _reach_reader_settings_tab("Colors"): + record(name, False, "setup_failed: could not reach the Colors tab", + depth=3, jump_kind="none", tag="color") + return + # position so both the Background and Font colour sections are visible together + for _ in range(2): + if find_node(ui(), text="Font color") is not None: + break + scroll_down(0.4) + time.sleep(0.4) + _screenshot("swatches_differ") + vlm_assert( + "computation_swatches_differ", + "In the visible 'Chapter One' reader area above the colour settings panel, " + "is there clear dark-text-on-light-background contrast that makes the title " + "and body text visibly readable?", + RESULTS_DIR, expect="YES", depth=3, jump_kind="none", tag="color") + + +if __name__ == "__main__": + if not device_online(): + print("Device offline — aborting (a whole module of setup_failed would be " + "misattributed to the app).") + sys.exit(2) + run_suite(TESTS, "computation") diff --git a/android/acclorite-book-story/tests/test_android_interaction.py b/android/acclorite-book-story/tests/test_android_interaction.py new file mode 100644 index 0000000000000000000000000000000000000000..53c5f5b8ad5e4efead08c1de65ce3eb2f84e2729 --- /dev/null +++ b/android/acclorite-book-story/tests/test_android_interaction.py @@ -0,0 +1,680 @@ +#!/usr/bin/env python3 +"""INTERACTION module — effect-by-consequence on user DATA for Book's Story. + +Lane: CRUD lifecycle, multi-step data sequences, multi-record integrity, DATA +persistence across process death, and long-press / context menus (sole owner). + +Ground truth (all verified on the running original before authoring): + * Library shows two persisted book cards: "testbook" and "alpha_wonderland". + Cover card has content-desc "Cover image not found"; count badge "2". + * Long-press a cover -> selection mode: "1 selected" + actions + "Select all books" / "Move selected books" / "Delete selected books" and + "Clear selected items". (We assert they EXIST; we never tap Delete.) + * Tap a cover -> Book Info: title, "Author"/"Unknown", "0%", "Move"/"Delete", + "No description.", "Start", top-bar "Go back"/"File details". + * Book Info "Start" -> Reader renders body text "Chapter One" + + "The quick brown fox jumps over the lazy dog." in the view tree. + * Reading a book creates a History entry: group "Today", "testbook", HH:MM, + per-row "Delete history element". + * Book Info "Move" -> a category-move sheet ("Move" / "No categories." / + "Edit" / "Cancel" / "OK"); we open it then Cancel (no destructive commit). + * Imported books + reading history SURVIVE force_stop_and_relaunch() (process + death) — the recreation-killing persistence probe. + +We do NOT clear_data() (it wipes the folder grant -> ~2min re-import); every test +opens its own entry point via restart_app()/force_stop_and_relaunch(), which the +library survives. The one CREATE test rides book_fixture.import_book()'s idempotent +"already" path: the book is a real persisted record either way. +""" +import os +import sys +import time + +# ADB_PATH / DEVICE_SERIAL / PACKAGE are supplied by the environment the runner +# exports (the kit reads them via os.environ / argv). We never bake a serial, +# package, or adb path into the source — the same file scores the recreation. +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 +import book_fixture as bf # shared, validated import helper + +COVER_DESC = "Cover image not found" # every book cover carries this desc +BOOK1 = bf.BOOK1_TITLE # "testbook" +BOOK1_FILE = bf.BOOK1_FILE # "testbook.txt" +BOOK2 = bf.BOOK2_TITLE # "alpha_wonderland" + + +# ── local helpers ─────────────────────────────────────────────────────────── +# The monkey launch occasionally reports the package foregrounded a beat before +# the Compose Library has actually painted, so every entry point re-verifies the +# Library surface with a short retry instead of trusting a single dump. + +def _reach_library(retries: int = 6) -> bool: + """Bring the app to the Library tab with a book visible. Returns True once a + cover is on screen. Absorbs the launch race without any fixed sleep loop.""" + wait_for_foreground() + for _ in range(retries): + bf._open_tab("Library") + nodes = ui() + if (find_node(nodes, content_desc=COVER_DESC) is not None + or find_node(nodes, text=BOOK1) is not None): + return True + settle("tap") + return False + + +def and_reach_book_info(title=BOOK1): + """Tap the book's cover and confirm we crossed into Book Info. Backs a depth + claim via its and_reach_* name AND an and_reach() surface proof.""" + nodes = ui() + cover = find_node(nodes, content_desc=COVER_DESC) + if cover is None: + covers = [n for n in nodes if "Cover image" in (n.get("content-desc") or "")] + cover = covers[0] if covers else None + if cover is None: + return False + # Book Info's "Start"/"Move" appear and the Library's "Continue reading" + # affordance disappears -> a real surface jump. + if and_reach_surface(cover, target="Start", source="Continue reading"): + return True + # Fallback: some builds label the primary action "Continue"; still a jump if + # Book Info's "Move" surfaced. + nodes = ui() + return find_node(nodes, text="Move") is not None + + +def and_reach_reader(): + """From Book Info, tap Start and confirm the reader body text rendered. + Counts one surface via and_enter (the reader is immersive, so a plain + and_reach_surface proof is not always available before the cling clears).""" + nodes = ui() + start = find_node(nodes, text="Start") or find_node(nodes, text="Continue") + if start is None or not tap_node(start): + return False + settle("launch") + time.sleep(1.5) + got = find_node(ui(), text="Got it") # one-time immersive cling + if got: + tap_node(got) + settle("tap") + and_enter("reader") + nodes = ui() + return find_node(nodes, text="Chapter One") is not None + + +def _leave_reader_to_history(): + """Pop out of the reader back through Book Info and open the History tab.""" + back() # reader -> book info + settle("tap") + time.sleep(1) + nodes = ui() + gb = find_node(nodes, content_desc="Go back") + if gb: + tap_node(gb) # book info -> library + settle("tap") + bf._open_tab("History") + settle("tap") + time.sleep(1) + + +def _screenshot(): + """Capture the current screen to a scratch path (reused before each VLM ask).""" + p = os.path.join(RESULTS_DIR, "screenshots", "_interaction_scratch.png") + screencap(p) + return p + + +TESTS = [] + + +def _t(fn): + TESTS.append(fn) + return fn + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1. DATA persistence across process death — the marquee, recreation-killing test +# ══════════════════════════════════════════════════════════════════════════════ + +@_t +@and_test(expects=("interaction_book_survives_process_death",)) +def test_book_survives_process_death(): + """testbook is in the Library -> kill the PROCESS -> still in the Library. + An in-memory-only recreation loses the record here.""" + restart_app() + if not _reach_library(): + record("interaction_book_survives_process_death", False, + "setup_failed: Library never showed a book to probe", + depth=0, jump_kind="transition", + expect=f"{BOOK1!r} present before and after process death") + return + present_before = find_node(ui(), text=BOOK1) is not None + force_stop_and_relaunch() + reached = _reach_library() + present_after = reached and find_node(ui(), text=BOOK1) is not None + ok = present_before and present_after + record("interaction_book_survives_process_death", ok, + "" if ok else + "behavior_wrong: book record did not survive process death", + depth=0, jump_kind="transition", + expect=f"{BOOK1!r} present before (True) and after force_stop_and_relaunch (True)") + + +@_t +@and_test(expects=("interaction_book_survives_process_death_vlm",)) +def test_book_survives_process_death_vlm(): + """After process death + relaunch, the Library still RENDERS the book card.""" + force_stop_and_relaunch() + if not _reach_library(): + record("interaction_book_survives_process_death_vlm", False, + "setup_failed: Library not reachable after relaunch", + depth=0, jump_kind="none", tag="layout") + return + _screenshot() + vlm_assert( + "interaction_book_survives_process_death", + "After relaunching the app, does the Library screen still show at least " + "one book card (a cover tile with a title label beneath it)?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="none", tag="layout") + + +@_t +@and_test(expects=("interaction_second_book_survives_process_death",)) +def test_second_book_survives_process_death(): + """The SECOND distinct record (alpha_wonderland) also survives process death — + proves persistence stores every row, not just the first.""" + restart_app() + if not _reach_library(): + record("interaction_second_book_survives_process_death", False, + "setup_failed: Library never showed books to probe", + depth=0, jump_kind="transition", + expect=f"{BOOK2!r} present before and after process death") + return + present_before = find_node(ui(), text=BOOK2) is not None + force_stop_and_relaunch() + present_after = _reach_library() and find_node(ui(), text=BOOK2) is not None + ok = present_before and present_after + record("interaction_second_book_survives_process_death", ok, + "" if ok else + "behavior_wrong: second book record lost across process death", + depth=0, jump_kind="transition", + expect=f"{BOOK2!r} present before (True) and after force_stop_and_relaunch (True)") + + +@_t +@and_test(expects=("interaction_history_survives_process_death",)) +def test_history_survives_process_death(): + """Reading data persists: open the reader (creating/refreshing a History + entry), kill the process, and the "testbook" History entry is still there. + A 3+ step data sequence whose product must survive process death.""" + restart_app() + if not _reach_library(): + record("interaction_history_survives_process_death", False, + "setup_failed: Library not reachable", + depth=1, jump_kind="transition", + expect=f"History entry for {BOOK1!r} present after process death") + return + if not and_reach_book_info(BOOK1): + record("interaction_history_survives_process_death", False, + "setup_failed: could not open Book Info to reach the reader", + depth=1, jump_kind="transition", + expect=f"History entry for {BOOK1!r} present after process death") + return + if not and_reach_reader(): + record("interaction_history_survives_process_death", False, + "setup_failed: reader did not open (no book text rendered)", + depth=2, jump_kind="transition", + expect=f"History entry for {BOOK1!r} present after process death") + return + # Kill the process, relaunch, and read the History tab back out. + force_stop_and_relaunch() + if not _reach_library(): + record("interaction_history_survives_process_death", False, + "setup_failed: app not reachable after relaunch", + depth=1, jump_kind="transition", + expect=f"History entry for {BOOK1!r} present after process death") + return + bf._open_tab("History") + settle("tap") + time.sleep(1) + entry = find_node(ui(), text=BOOK1) is not None + record("interaction_history_survives_process_death", entry, + "" if entry else + "behavior_wrong: reading-history entry lost across process death", + depth=1, jump_kind="transition", + expect=f"History row {BOOK1!r} present after force_stop_and_relaunch") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2. Long-press -> selection mode / context menu (SOLE OWNER of long-press) +# ══════════════════════════════════════════════════════════════════════════════ + +@_t +@and_test(expects=("interaction_longpress_enters_selection",)) +def test_longpress_enters_selection_mode(): + """Long-press a book cover -> selection mode: "1 selected" appears and the + normal top bar ("Library" title / Search) gives way to selection actions.""" + restart_app() + if not _reach_library(): + record("interaction_longpress_enters_selection", False, + "setup_failed: Library not reachable", + depth=0, jump_kind="transition", + expect="'1 selected' shown after long-press") + return + nodes = ui() + absent_before = find_node(nodes, text="1 selected") is None + cover = find_node(nodes, content_desc=COVER_DESC) + if cover is None or not long_press(cover): + record("interaction_longpress_enters_selection", False, + "feature_missing: no long-pressable book cover", + depth=0, jump_kind="transition", + expect="'1 selected' shown after long-press") + return + present_after = find_node(ui(), text="1 selected") is not None + ok = absent_before and present_after + record("interaction_longpress_enters_selection", ok, + "" if ok else + "behavior_wrong: long-press did not enter selection mode", + depth=0, jump_kind="transition", + expect="'1 selected' absent before long-press, present after") + + +@_t +@and_test(expects=("interaction_longpress_selection_actions",)) +def test_longpress_selection_actions_present(): + """Selection mode exposes the context actions Select-all / Move / Delete. We + assert all three EXIST (proving a real multi-select menu) but never tap the + destructive one.""" + restart_app() + if not _reach_library(): + record("interaction_longpress_selection_actions", False, + "setup_failed: Library not reachable", + depth=0, jump_kind="transition", + expect="Select all / Move / Delete actions in selection mode") + return + cover = find_node(ui(), content_desc=COVER_DESC) + if cover is None or not long_press(cover): + record("interaction_longpress_selection_actions", False, + "feature_missing: no long-pressable book cover", + depth=0, jump_kind="transition", + expect="Select all / Move / Delete actions in selection mode") + return + nodes = ui() + select_all = find_node(nodes, content_desc="Select all books") is not None + move = find_node(nodes, content_desc="Move selected books") is not None + delete = find_node(nodes, content_desc="Delete selected books") is not None + ok = select_all and move and delete + record("interaction_longpress_selection_actions", ok, + "" if ok else + "behavior_wrong: selection-mode context actions missing", + depth=0, jump_kind="transition", + expect="content-desc 'Select all books' + 'Move selected books' + 'Delete selected books' all present") + + +@_t +@and_test(expects=("interaction_longpress_selection_vlm",)) +def test_longpress_selection_vlm(): + """The long-pressed cover renders a selected/checked overlay (a visual mark + that distinguishes the chosen tile from the unselected one).""" + restart_app() + if not _reach_library(): + record("interaction_longpress_selection_vlm", False, + "setup_failed: Library not reachable", + depth=0, jump_kind="none", tag="shape") + return + cover = find_node(ui(), content_desc=COVER_DESC) + if cover is None or not long_press(cover): + record("interaction_longpress_selection_vlm", False, + "feature_missing: no long-pressable book cover", + depth=0, jump_kind="none", tag="shape") + return + _screenshot() + vlm_assert( + "interaction_longpress_selection", + "One of the book covers is now selected. Does exactly one book cover show " + "a selection indicator on it (a check mark or a highlighted/outlined " + "overlay) that the other cover does not have?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="none", tag="shape") + + +@_t +@and_test(expects=("interaction_clear_selection_exits",)) +def test_clear_selection_exits_mode(): + """Multi-step: enter selection mode, then tap "Clear selected items" and + confirm the mode exits ("1 selected" is gone, the Library title returns).""" + restart_app() + if not _reach_library(): + record("interaction_clear_selection_exits", False, + "setup_failed: Library not reachable", + depth=0, jump_kind="transition", + expect="selection mode exits after Clear selected items") + return + cover = find_node(ui(), content_desc=COVER_DESC) + if cover is None or not long_press(cover): + record("interaction_clear_selection_exits", False, + "feature_missing: no long-pressable book cover", + depth=0, jump_kind="transition", + expect="selection mode exits after Clear selected items") + return + nodes = ui() + in_selection = find_node(nodes, text="1 selected") is not None + clear = find_node(nodes, content_desc="Clear selected items") + if clear is None or not tap_node(clear): + record("interaction_clear_selection_exits", False, + "behavior_wrong: no 'Clear selected items' control in selection mode", + depth=0, jump_kind="transition", + expect="selection mode exits after Clear selected items") + return + exited = find_node(ui(), text="1 selected") is None + ok = in_selection and exited + record("interaction_clear_selection_exits", ok, + "" if ok else + "behavior_wrong: selection mode did not exit after clearing", + depth=0, jump_kind="transition", + expect="'1 selected' present in selection mode, absent after Clear selected items") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3. Reading creates a History record — multi-step data-producing sequence +# ══════════════════════════════════════════════════════════════════════════════ + +@_t +@and_test(expects=("interaction_reading_creates_history",)) +def test_reading_creates_history_entry(): + """4-step sequence: Library -> Book Info -> Reader (renders text) -> back -> + History tab shows a "testbook" row under "Today". Each step depends on the + prior; a dead shell that echoes step one cannot produce the History row.""" + restart_app() + if not _reach_library(): + record("interaction_reading_creates_history", False, + "setup_failed: Library not reachable", + depth=1, jump_kind="transition", + expect=f"History row {BOOK1!r} under 'Today' after reading") + return + if not and_reach_book_info(BOOK1): + record("interaction_reading_creates_history", False, + "setup_failed: could not open Book Info", + depth=1, jump_kind="transition", + expect=f"History row {BOOK1!r} under 'Today' after reading") + return + if not and_reach_reader(): + record("interaction_reading_creates_history", False, + "setup_failed: reader did not render book text", + depth=2, jump_kind="transition", + expect=f"History row {BOOK1!r} under 'Today' after reading") + return + _leave_reader_to_history() + nodes = ui() + entry = find_node(nodes, text=BOOK1) is not None + today = find_node(nodes, text="Today") is not None + ok = entry and today + record("interaction_reading_creates_history", ok, + "" if ok else + "behavior_wrong: reading did not produce a History entry", + depth=1, jump_kind="transition", + expect=f"'Today' group + History row {BOOK1!r} present after reading") + + +@_t +@and_test(expects=("interaction_history_entry_vlm",)) +def test_history_entry_vlm(): + """The History screen renders the entry as a row with a cover thumbnail on the + left and a timestamp — a laid-out history record, not bare text.""" + restart_app() + if not _reach_library(): + record("interaction_history_entry_vlm", False, + "setup_failed: Library not reachable", + depth=1, jump_kind="none", tag="layout") + return + if not (and_reach_book_info(BOOK1) and and_reach_reader()): + record("interaction_history_entry_vlm", False, + "setup_failed: could not read a book to populate History", + depth=2, jump_kind="none", tag="layout") + return + _leave_reader_to_history() + _screenshot() + vlm_assert( + "interaction_history_entry", + "This is a reading-history screen. Is there a list row that shows a small " + "book cover thumbnail on the left with a book title and a time (HH:MM) " + "beside it?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="layout") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4. Multi-record integrity — both distinct records coexist and are ordered +# ══════════════════════════════════════════════════════════════════════════════ + +@_t +@and_test(expects=("interaction_multi_record_integrity",)) +def test_multi_record_integrity(): + """Both distinct records coexist in the Library simultaneously and keep their + left-to-right order (testbook before alpha_wonderland). Catches a recreation + that keeps only one row or drops one on a re-render.""" + # A controlled CREATE via the idempotent import helper: the book is a real + # persisted record whether it was already present or freshly added. + ok1, note1 = bf.import_book(BOOK1, BOOK1_FILE) + ok2, note2 = bf.import_book(BOOK2, bf.BOOK2_FILE) + if not (ok1 and ok2): + record("interaction_multi_record_integrity", False, + f"setup_failed: import did not yield both records ({note1}/{note2})", + depth=0, jump_kind="value", + expect=f"both {BOOK1!r} and {BOOK2!r} present and ordered") + return + if not _reach_library(): + record("interaction_multi_record_integrity", False, + "setup_failed: Library not reachable", + depth=0, jump_kind="value", + expect=f"both {BOOK1!r} and {BOOK2!r} present and ordered") + return + nodes = ui() + n1 = find_node(nodes, text=BOOK1) + n2 = find_node(nodes, text=BOOK2) + both = n1 is not None and n2 is not None + ordered = False + if both: + # testbook's card sits left of (or above) alpha_wonderland's. + y1, y2 = n1["_bounds"][1], n2["_bounds"][1] + x1, x2 = n1["_bounds"][0], n2["_bounds"][0] + ordered = (y1, x1) < (y2, x2) + ok = both and ordered + record("interaction_multi_record_integrity", ok, + "" if ok else + "behavior_wrong: the two book records do not coexist in order", + depth=0, jump_kind="value", + expect=f"{BOOK1!r} present and ordered before {BOOK2!r} in the same Library") + + +@_t +@and_test(expects=("interaction_multi_record_survives_death",)) +def test_both_records_survive_process_death(): + """Multi-record persistence: BOTH records are present, then a single process + death leaves BOTH intact — the strongest discriminator against an in-memory + recreation that could fake one row.""" + restart_app() + if not _reach_library(): + record("interaction_multi_record_survives_death", False, + "setup_failed: Library not reachable", + depth=0, jump_kind="transition", + expect=f"both {BOOK1!r} and {BOOK2!r} present after process death") + return + nodes = ui() + before = (find_node(nodes, text=BOOK1) is not None + and find_node(nodes, text=BOOK2) is not None) + force_stop_and_relaunch() + after = False + if _reach_library(): + nodes = ui() + after = (find_node(nodes, text=BOOK1) is not None + and find_node(nodes, text=BOOK2) is not None) + ok = before and after + record("interaction_multi_record_survives_death", ok, + "" if ok else + "behavior_wrong: not both records survived process death", + depth=0, jump_kind="transition", + expect=f"both {BOOK1!r} and {BOOK2!r} present before (True) and after death (True)") + + +@_t +@and_test(expects=("interaction_library_two_cards_vlm",)) +def test_library_two_cards_vlm(): + """The populated Library visibly renders TWO distinct book cards side by side + — a layout consequence of the two coexisting records.""" + restart_app() + if not _reach_library(): + record("interaction_library_two_cards_vlm", False, + "setup_failed: Library not reachable", + depth=0, jump_kind="none", tag="layout") + return + _screenshot() + vlm_assert( + "interaction_library_two_cards", + "How many distinct book cards (each a cover tile with its own title label) " + "are shown in this library grid? Answer YES only if there are exactly two.", + RESULTS_DIR, expect="YES", depth=0, jump_kind="none", tag="layout") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5. Book Info — reader open sequence + Move sheet (data-adjacent interaction) +# ══════════════════════════════════════════════════════════════════════════════ + +@_t +@and_test(expects=("interaction_open_reader_shows_text",)) +def test_open_reader_shows_body_text(): + """Multi-step read path: Library -> Book Info -> Start -> the reader renders + this book's actual body TEXT. We assert the specific opening content + ("Chapter One" + the opening sentence) — a value read out of the record, not a + title echoed back. Depth is backed by the and_reach_* navigation helpers; the + assertion is jump_kind=value because we name the exact rendered content.""" + restart_app() + if not _reach_library(): + record("interaction_open_reader_shows_text", False, + "setup_failed: Library not reachable", + depth=2, jump_kind="value", + expect="reader body shows 'Chapter One' + 'The quick brown fox' text") + return + if not and_reach_book_info(BOOK1): + record("interaction_open_reader_shows_text", False, + "setup_failed: could not open Book Info", + depth=1, jump_kind="value", + expect="reader body shows 'Chapter One' + 'The quick brown fox' text") + return + if not and_reach_reader(): + record("interaction_open_reader_shows_text", False, + "behavior_wrong: reader did not render the book's body text", + depth=2, jump_kind="value", + expect="reader body shows 'Chapter One' + 'The quick brown fox' text") + return + nodes = ui() + heading = find_node(nodes, text="Chapter One") is not None + # The opening paragraph is a long TextView; match its distinctive prefix. + opener = any("The quick brown fox" in (n.get("text", "") or "") for n in nodes) + ok = heading and opener + record("interaction_open_reader_shows_text", ok, + "" if ok else + "behavior_wrong: reader body text did not match the book's content", + depth=2, jump_kind="value", + expect="reader shows 'Chapter One' heading and 'The quick brown fox' opening sentence") + + +@_t +@and_test(expects=("interaction_reader_page_vlm",)) +def test_reader_page_vlm(): + """The reader renders a full page of body text with margins — a laid-out + reading page, not an empty or error screen.""" + restart_app() + if not _reach_library(): + record("interaction_reader_page_vlm", False, + "setup_failed: Library not reachable", + depth=2, jump_kind="none", tag="layout") + return + if not (and_reach_book_info(BOOK1) and and_reach_reader()): + record("interaction_reader_page_vlm", False, + "setup_failed: reader did not open", + depth=2, jump_kind="none", tag="layout") + return + _screenshot() + vlm_assert( + "interaction_reader_page", + "Is this screen showing a page of readable book text (multiple lines/" + "paragraphs of body text with margins), rather than an empty screen, a " + "list, or a dialog?", + RESULTS_DIR, expect="YES", depth=2, jump_kind="none", tag="layout") + + +@_t +@and_test(expects=("interaction_move_sheet_opens",)) +def test_book_info_move_sheet_opens_and_cancels(): + """Data-adjacent context action: Book Info "Move" opens a category-move sheet + (title "Move" + Cancel/OK). We open it, assert the sheet, then Cancel — never + committing a destructive change.""" + restart_app() + if not _reach_library(): + record("interaction_move_sheet_opens", False, + "setup_failed: Library not reachable", + depth=1, jump_kind="transition", + expect="Move sheet (Cancel/OK) appears then closes") + return + if not and_reach_book_info(BOOK1): + record("interaction_move_sheet_opens", False, + "setup_failed: could not open Book Info", + depth=1, jump_kind="transition", + expect="Move sheet (Cancel/OK) appears then closes") + return + nodes = ui() + move = find_node(nodes, text="Move") + if move is None or not is_safe(move) or not tap_node(move): + record("interaction_move_sheet_opens", False, + "feature_missing: no Move control on Book Info", + depth=1, jump_kind="transition", + expect="Move sheet (Cancel/OK) appears then closes") + return + settle("launch") + nodes = ui() + # The move sheet is identified by its Cancel+OK pair (its title "Move" also + # exists on Book Info, so require the sheet's buttons too). + sheet = (find_node(nodes, text="Cancel") is not None + and find_node(nodes, text="OK") is not None) + # Back out non-destructively via Cancel. + cancel = find_node(nodes, text="Cancel") + closed = False + if cancel and tap_node(cancel): + settle("tap") + closed = find_node(ui(), text="OK") is None + ok = sheet and closed + record("interaction_move_sheet_opens", ok, + "" if ok else + "behavior_wrong: Move did not open a cancellable category sheet", + depth=1, jump_kind="transition", + expect="Cancel+OK move sheet present after Move, gone after Cancel") + + +@_t +@and_test(expects=("interaction_book_info_actions_vlm",)) +def test_book_info_actions_vlm(): + """Book Info renders the record with its Move and Delete action buttons — the + per-record management surface for this book.""" + restart_app() + if not _reach_library(): + record("interaction_book_info_actions_vlm", False, + "setup_failed: Library not reachable", + depth=1, jump_kind="none", tag="layout") + return + if not and_reach_book_info(BOOK1): + record("interaction_book_info_actions_vlm", False, + "setup_failed: could not open Book Info", + depth=1, jump_kind="none", tag="layout") + return + _screenshot() + vlm_assert( + "interaction_book_info_actions", + "This is a book-detail screen. Does it show the book's title near the top " + "and two labelled action buttons reading 'Move' and 'Delete'?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="layout") + + +if __name__ == "__main__": + if not device_online(): + print("Device offline — aborting (a whole module of setup_failed would be " + "misattributed to the app).") + sys.exit(2) + run_suite(TESTS, "interaction") diff --git a/android/acclorite-book-story/tests/test_android_navigation.py b/android/acclorite-book-story/tests/test_android_navigation.py new file mode 100644 index 0000000000000000000000000000000000000000..ffcb134583037066190f77ea56922e2eea7c49c3 --- /dev/null +++ b/android/acclorite-book-story/tests/test_android_navigation.py @@ -0,0 +1,650 @@ +"""Navigation lane for Book's Story (ebook reader). + +This module owns SURFACE REACHABILITY and BACK-STACK INTEGRITY: tapping a nav +trigger (tab, bottom-sheet row, cover, toolbar icon) lands on the intended +Compose surface, and BACK unwinds the stack hop by hop. It is the SOLE owner of +jump_kind="reach" and of the deep (depth>=2) chains; every jump is proven with +and_reach* — the TARGET surface's discriminating element APPEARED *and* the +SOURCE surface's element DISAPPEARED (a flat-tree element that was there all +along cannot fake a reach). + +Every target/source string below was observed on the RUNNING original app with +scratch probes before being committed here (e.g. Settings->Appearance shows +"Dark theme" and drops "Reset start guide"; BookInfo->Reader shows "Chapter One" +and drops "Start"; About->Credits shows "Tachiyomi (Mihon)" and drops +"App version"). Contributors is intentionally NOT tested as an in-app reach: on +the original it launches the external Chrome browser (not an in-app surface), so +it is unobservable as navigation. + +A real book (title "testbook") is imported once via the shared book_fixture +helper (never inlined); the kit pushes the fixture bytes before the first test +via run_suite(). Toggles/rows in this Jetpack-Compose app are android.view.View +with content-desc, and resource-id is almost always empty, so matching is by +class + text + content-desc, never by full class path or package prefix. +""" +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 +import book_fixture as bf # shared import-a-book helper + +RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else os.path.dirname( + os.path.abspath(__file__)) + +BOOK = bf.BOOK1_TITLE # "testbook" + + +# ══════════════════════════════════════════════════════════════════════════════ +# Local helpers — entry points and file-local depth-family shims. The and_enter*/ +# and_reach* NAME is what the depth audit looks for; each wraps the kit's proven +# and_reach_surface so the verdict stays honest. +# ══════════════════════════════════════════════════════════════════════════════ + +def _open_library(): + """Cold-restart into the Library tab. Returns the node list.""" + restart_app() + wait_for_foreground() + time.sleep(1) + bf._open_tab("Library") + return ui() + + +def _cover(nodes): + """The Library book-cover card (icon-only, content-desc 'Cover image ...').""" + n = find_node(nodes, content_desc="Cover image not found") + if n: + return n + covers = [x for x in nodes if "Cover image" in (x.get("content-desc") or "")] + return covers[0] if covers else None + + +def _open_more_sheet(nodes): + """Library ▸ More: tap the More toolbar icon; return True once the sheet's + 'Settings' row shows.""" + more = find_node(nodes, content_desc="More") + if not more or not tap_node(more): + return False + settle("tap") + return find_node(ui(), text="Settings") is not None + + +_BROWSE_SURFACE_TARGETS = ( + "/storage/emulated/0/Download/Books", + "Set up scanning", +) + + +def _reach_browse(node, source: str) -> str | None: + """Reach Browse whether its scanned files are still pending or imported. + + Browse hides files already present in Library. Once both shared fixtures + have been imported, the valid reference UI is therefore the Browse empty + state (``Set up scanning``), not the scanned-folder header. Return the + marker that actually appeared so a following jump can prove it vanished. + """ + before = and_showing() + if not tap_node(node): + return None + for _ in range(8): + after = and_showing() + for target in _BROWSE_SURFACE_TARGETS: + if and_reach(before, after, target, source): + and_enter(target) + return target + time.sleep(0.5) + return None + + +def and_reach_more_sheet(nodes): + """Library ▸ More: open the More sheet, counting one surface via the kit's + reach verdict (sheet row 'Settings' appears; toolbar 'Filter' leaves).""" + more = find_node(nodes, content_desc="More") + return bool(more) and and_reach_surface(more, "Settings", "Filter") + + +def and_reach_settings(nodes): + """From the OPEN More sheet, tap Settings -> Settings root (title row + 'Reset start guide' appears; sheet row 'About app' leaves).""" + st = find_node_ci(nodes, "Settings") + return bool(st) and and_reach_surface(st, "Reset start guide", "About app") + + +def and_reach_about(nodes): + """From the OPEN More sheet, tap About app -> About screen ('App version' + appears; sheet row 'Settings' leaves).""" + ab = find_node_ci(nodes, "About app") + return bool(ab) and and_reach_surface(ab, "App version", "Settings") + + +def _goto_settings_root(): + """Library ▸ More ▸ Settings, leaving the Settings root showing. Returns the + node list of the Settings root (or [] on failure). Counts 2 surfaces.""" + nodes = _open_library() + if not and_reach_more_sheet(nodes): + return [] + if not and_reach_settings(ui()): + return [] + return ui() + + +def and_reach_book_info(): + """Library -> Book Info: tap the cover (Book Info's 'No description.' appears; + Library's 'Continue reading' leaves).""" + nodes = _open_library() + cover = _cover(nodes) + return bool(cover) and and_reach_surface(cover, "No description.", + "Continue reading") + + +def and_reach_reader_from_info(nodes): + """From the OPEN Book Info screen, tap Start -> Reader (book body 'Chapter + One' appears; Book Info's 'Start' button leaves).""" + start = find_node(nodes, text="Start") or find_node(nodes, text="Continue") + return bool(start) and and_reach_surface(start, "Chapter One", "Start") + + +def _open_reader_bars(): + """Open the reader on BOOK, reveal the top/bottom bars, return the node list + once the 'Reader settings' bar icon is present (else []).""" + if not bf.open_reader(BOOK): + return [] + info = get_screen_info() + tap(info["center_x"], info["center_y"]) # toggle bars + settle("tap") + nodes = ui() + if find_node(nodes, content_desc="Reader settings") is None: + # one retry: an animation may have eaten the first tap + settle("tap") + tap(info["center_x"], info["center_y"]) + settle("tap") + nodes = ui() + return nodes + + +# ══════════════════════════════════════════════════════════════════════════════ +# (A) Bottom-nav tab reaches — depth 1, jump_kind="reach" +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_history", "nav_reach_history_vlm")) +def test_reach_history(): + nodes = _open_library() + tab = bf._tab(nodes, "History") + # History surface: 'Delete whole history' toolbar action appears; Library's + # 'Continue reading' cover affordance disappears. + ok = tab is not None and and_reach_surface(tab, "Delete whole history", + "Continue reading") + record("nav_reach_history", ok, + "" if ok else "feature_missing: History tab did not replace the Library " + "surface (Delete-whole-history absent or Library still shown)", + depth=1, jump_kind="reach", + expect="History surface (Delete whole history) shown; Library " + "'Continue reading' no longer showing") + vlm_assert("nav_reach_history", + "Is this a reading-history screen showing either a list of book " + "entries grouped by date, or a centered empty-state illustration " + "with a message — and NOT a grid of book covers?", + RESULTS_DIR, tag="layout") + + +@and_test(expects=("nav_reach_browse",)) +def test_reach_browse(): + nodes = _open_library() + # Hop via History first so the source we drop is History-unique, then Browse. + hist = bf._tab(nodes, "History") + hop1 = hist is not None and and_reach_surface(hist, "Delete whole history", + "Continue reading") + br = bf._tab(ui(), "Browse") + # The folder path is visible while it still contains unimported files. Once + # all shared fixtures are in Library, the original app correctly shows its + # Browse empty state instead. Both prove that History was replaced. + browse_marker = br is not None and _reach_browse(br, "Delete whole history") + ok = hop1 and bool(browse_marker) + record("nav_reach_browse", ok, + "" if ok else "feature_missing: History->Browse did not reach the " + "Browse surface", + depth=2, jump_kind="reach", + expect="Browse surface (scanned-folder row or valid empty state) shown; " + "History 'Delete whole history' no longer showing") + + +@and_test(expects=("nav_reach_library_from_browse",)) +def test_reach_library_from_browse(): + nodes = _open_library() + br = bf._tab(nodes, "Browse") + browse_marker = br is not None and _reach_browse(br, "Continue reading") + lib = bf._tab(ui(), "Library") + # Back to Library: 'Continue reading' reappears and whichever Browse marker + # was observed (folder header or empty-state action) leaves. + hop2 = bool(browse_marker) and lib is not None and and_reach_surface( + lib, "Continue reading", browse_marker) + ok = bool(browse_marker) and hop2 + record("nav_reach_library_from_browse", ok, + "" if ok else "feature_missing: Browse->Library tab jump did not restore " + "the Library cover surface", + depth=2, jump_kind="reach", + expect="Library surface ('Continue reading') restored; observed Browse " + "marker no longer showing") + + +@and_test(expects=("nav_backstack_tab_history",)) +def test_backstack_tab_history(): + # Library -> History (one hop), then BACK returns to Library. + nodes = _open_library() + tab = bf._tab(nodes, "History") + deep = tab is not None and and_reach_surface(tab, "Delete whole history", + "Continue reading") + and_back() # pop History + settle("tap") + post = ui() + home = (find_node(post, content_desc="Continue reading") is not None + and find_node(post, text="Delete whole history") is None) + ok = deep and home + record("nav_backstack_tab_history", ok, + "" if ok else "behavior_wrong: BACK from History did not return to the " + "Library cover surface", + depth=1, jump_kind="reach", + expect="Library ('Continue reading') restored after one BACK from History") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (B) Library ▸ More ▸ Settings ▸ sub-screens — depth 2–3 chains, reach +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_more_sheet", "nav_reach_more_sheet_vlm")) +def test_reach_more_sheet(): + nodes = _open_library() + ok = and_reach_more_sheet(nodes) + record("nav_reach_more_sheet", ok, + "" if ok else "feature_missing: More toolbar action did not open a sheet " + "with a Settings row", + depth=1, jump_kind="reach", + expect="More bottom sheet (rows 'Settings'/'About app') shown; toolbar " + "'Filter' no longer showing") + vlm_assert("nav_reach_more_sheet", + "Is there a small menu panel anchored to the BOTTOM edge of the " + "screen (a bottom sheet with a drag handle), rather than a " + "full-screen page?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("nav_reach_settings", "nav_reach_settings_vlm")) +def test_reach_settings(): + nodes = _open_library() + hop1 = and_reach_more_sheet(nodes) + hop2 = and_reach_settings(ui()) + ok = hop1 and hop2 + record("nav_reach_settings", ok, + "" if ok else "feature_missing: More->Settings did not reach the Settings " + "root (Reset start guide absent)", + depth=2, jump_kind="reach", + expect="Settings root ('Reset start guide') shown; More sheet 'About app' " + "no longer showing") + vlm_assert("nav_reach_settings", + "In the top-left corner of this settings screen, is there a " + "left-pointing back arrow, above a vertical list of category rows?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("nav_reach_appearance",)) +def test_reach_appearance(): + root = _goto_settings_root() + ap = find_node(root, text="Appearance") if root else None + # Appearance sub-screen: 'Dark theme' segmented appears; Settings-root-only + # 'Reset start guide' toolbar action leaves. + ok = ap is not None and and_reach_surface(ap, "Dark theme", "Reset start guide") + record("nav_reach_appearance", ok, + "" if ok else "feature_missing: Settings->Appearance did not reach the " + "Appearance surface (Dark theme absent)", + depth=3, jump_kind="reach", + expect="Appearance ('Dark theme') shown; Settings 'Reset start guide' " + "no longer showing") + + +@and_test(expects=("nav_reach_reader_settings_screen",)) +def test_reach_reader_settings_screen(): + root = _goto_settings_root() + rd = find_node(root, text="Reader") if root else None + # Reader settings sub-screen: 'Font thickness' appears; 'Reset start guide' leaves. + ok = rd is not None and and_reach_surface(rd, "Font thickness", "Reset start guide") + record("nav_reach_reader_settings_screen", ok, + "" if ok else "feature_missing: Settings->Reader did not reach the Reader " + "settings surface (Font thickness absent)", + depth=3, jump_kind="reach", + expect="Reader settings ('Font thickness') shown; Settings 'Reset start " + "guide' no longer showing") + + +@and_test(expects=("nav_reach_general",)) +def test_reach_general(): + root = _goto_settings_root() + gn = find_node(root, text="General") if root else None + # General sub-screen: 'Double back press to exit' appears; 'Reset start guide' leaves. + ok = gn is not None and and_reach_surface(gn, "Double back press to exit", + "Reset start guide") + record("nav_reach_general", ok, + "" if ok else "feature_missing: Settings->General did not reach the " + "General surface (Double back press to exit absent)", + depth=3, jump_kind="reach", + expect="General ('Double back press to exit') shown; Settings 'Reset " + "start guide' no longer showing") + + +@and_test(expects=("nav_reach_library_settings",)) +def test_reach_library_settings(): + root = _goto_settings_root() + lb = find_node(root, text="Library") if root else None + # Library settings sub-screen: 'Create category' appears; 'Reset start guide' leaves. + ok = lb is not None and and_reach_surface(lb, "Create category", "Reset start guide") + record("nav_reach_library_settings", ok, + "" if ok else "feature_missing: Settings->Library did not reach the " + "Library-settings surface (Create category absent)", + depth=3, jump_kind="reach", + expect="Library settings ('Create category') shown; Settings 'Reset " + "start guide' no longer showing") + + +@and_test(expects=("nav_reach_browse_settings",)) +def test_reach_browse_settings(): + root = _goto_settings_root() + bw = find_node(root, text="Browse") if root else None + # Browse settings sub-screen: 'Add folder' appears; 'Reset start guide' leaves. + ok = bw is not None and and_reach_surface(bw, "Add folder", "Reset start guide") + record("nav_reach_browse_settings", ok, + "" if ok else "feature_missing: Settings->Browse did not reach the " + "Browse-settings surface (Add folder absent)", + depth=3, jump_kind="reach", + expect="Browse settings ('Add folder') shown; Settings 'Reset start " + "guide' no longer showing") + + +@and_test(expects=("nav_backstack_settings_to_library",)) +def test_backstack_settings_to_library(): + # Deepest here: Appearance -> BACK -> Settings root -> BACK -> Library. + root = _goto_settings_root() + ap = find_node(root, text="Appearance") if root else None + deep = ap is not None and and_reach_surface(ap, "Dark theme", "Reset start guide") + # Pop 1: Appearance -> Settings root + b1 = and_showing() + and_back(); settle("tap") + a1 = and_showing() + to_settings = and_reach(b1, a1, "Reset start guide", "Dark theme") + # Pop 2: Settings root -> Library + and_back(); settle("tap") + post = ui() + to_library = (find_node(post, content_desc="Continue reading") is not None + and find_node(post, text="Reset start guide") is None) + ok = deep and to_settings and to_library + record("nav_backstack_settings_to_library", ok, + "" if ok else "behavior_wrong: BACK did not unwind Appearance->Settings" + "->Library one surface per press", + depth=3, jump_kind="reach", + expect="First BACK restores Settings ('Reset start guide'), second BACK " + "restores Library ('Continue reading')") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (C) Library ▸ Book cover ▸ Book Info ▸ Reader — depth 1/2 chains, reach +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_book_info", "nav_reach_book_info_vlm")) +def test_reach_book_info(): + ok = and_reach_book_info() + record("nav_reach_book_info", ok, + "" if ok else "setup_failed: could not open Book Info from a Library cover " + "('No description.' absent)", + depth=1, jump_kind="reach", + expect="Book Info ('No description.') shown; Library 'Continue reading' " + "no longer showing") + vlm_assert("nav_reach_book_info", + "Is a single large book-cover image positioned in the upper part of " + "this screen, with a button to start/read the book lower down — i.e. " + "one book detail page, not a grid of many covers?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("nav_reach_reader", "nav_reach_reader_vlm")) +def test_reach_reader(): + # Library -> Book Info -> Reader (two hops). + hop1 = and_reach_book_info() + hop2 = and_reach_reader_from_info(ui()) + ok = hop1 and hop2 + # Dismiss the one-time immersive "Got it" cling if it rode in on the reader. + got = find_node(ui(), text="Got it") + if got: + tap_node(got) + settle("tap") + record("nav_reach_reader", ok, + "" if ok else "feature_missing: Book Info Start did not reach the Reader " + "text surface ('Chapter One' absent)", + depth=2, jump_kind="reach", + expect="Reader body ('Chapter One') shown; Book Info 'Start' button no " + "longer showing") + vlm_assert("nav_reach_reader", + "Is this an ebook reading page filled mostly with paragraphs of body " + "text (a page of prose), rather than a list, a grid, or a form?", + RESULTS_DIR, tag="layout") + + +@and_test(expects=("nav_backstack_reader_to_info",)) +def test_backstack_reader_to_info(): + hop1 = and_reach_book_info() + hop2 = and_reach_reader_from_info(ui()) + got = find_node(ui(), text="Got it") + if got: + tap_node(got); settle("tap") + # BACK from the reader returns to Book Info (its 'Start' button reappears; + # the reader body 'Chapter One' leaves). + before = and_showing() + and_back(); settle("tap") + after = and_showing() + to_info = and_reach(before, after, "Start", "Chapter One") + ok = hop1 and hop2 and to_info + record("nav_backstack_reader_to_info", ok, + "" if ok else "behavior_wrong: BACK from the Reader did not return to " + "Book Info (Start button not restored)", + depth=2, jump_kind="reach", + expect="Book Info ('Start') restored after one BACK from the Reader") + + +@and_test(expects=("nav_backstack_info_to_library",)) +def test_backstack_info_to_library(): + deep = and_reach_book_info() + before = and_showing() + and_back(); settle("tap") # Book Info -> Library + after = and_showing() + to_library = and_reach(before, after, "Continue reading", "No description.") + ok = deep and to_library + record("nav_backstack_info_to_library", ok, + "" if ok else "behavior_wrong: BACK from Book Info did not return to the " + "Library cover surface", + depth=1, jump_kind="reach", + expect="Library ('Continue reading') restored after one BACK from Book Info") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (D) Reader in-surface panels — Reader settings sheet + Chapters drawer +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_reader_settings_sheet",)) +def test_reach_reader_settings_sheet(): + bars = _open_reader_bars() + rs = find_node(bars, content_desc="Reader settings") if bars else None + # Reader settings sheet: 'Reading mode' row appears; the 'Reader settings' bar + # icon leaves (the bar is replaced by the sheet). + ok = rs is not None and and_reach_surface(rs, "Reading mode", "Reader settings") + record("nav_reach_reader_settings_sheet", ok, + "" if ok else "feature_missing: Reader-settings icon did not open the " + "reader settings sheet ('Reading mode' absent)", + depth=3, jump_kind="reach", + expect="Reader settings sheet ('Reading mode') shown; bar 'Reader " + "settings' icon no longer showing") + + +@and_test(expects=("nav_reach_chapters_drawer",)) +def test_reach_chapters_drawer(): + bars = _open_reader_bars() + ch = find_node(bars, content_desc="Chapters") if bars else None + # Chapters drawer: its 'Chapters' heading appears; the 'Reader settings' bar + # icon leaves. + ok = ch is not None and and_reach_surface(ch, "Chapters", "Reader settings") + record("nav_reach_chapters_drawer", ok, + "" if ok else "feature_missing: Chapters icon did not open the chapters " + "drawer ('Chapters' heading absent)", + depth=3, jump_kind="reach", + expect="Chapters drawer ('Chapters' heading) shown; bar 'Reader " + "settings' icon no longer showing") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (E) About app ▸ Credits / Open source licenses — depth 2–3 chains, reach +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_about", "nav_reach_about_vlm")) +def test_reach_about(): + nodes = _open_library() + hop1 = and_reach_more_sheet(nodes) + hop2 = and_reach_about(ui()) + ok = hop1 and hop2 + record("nav_reach_about", ok, + "" if ok else "feature_missing: More->About app did not reach the About " + "screen ('App version' absent)", + depth=2, jump_kind="reach", + expect="About screen ('App version') shown; More sheet 'Settings' no " + "longer showing") + vlm_assert("nav_reach_about", + "Is an app icon positioned near the TOP of this About screen, with a " + "vertical list of tappable link rows below it (e.g. report a bug, " + "credits, licenses)?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("nav_reach_credits",)) +def test_reach_credits(): + nodes = _open_library() + hop1 = and_reach_more_sheet(nodes) + hop2 = and_reach_about(ui()) + cr = find_node(ui(), text="Credits") + # Credits sub-screen: acknowledgement 'Tachiyomi (Mihon)' appears; the About + # 'App version' label leaves. + hop3 = cr is not None and and_reach_surface(cr, "Tachiyomi (Mihon)", "App version") + ok = hop1 and hop2 and hop3 + record("nav_reach_credits", ok, + "" if ok else "feature_missing: About->Credits did not reach the Credits " + "surface ('Tachiyomi (Mihon)' absent)", + depth=3, jump_kind="reach", + expect="Credits ('Tachiyomi (Mihon)') shown; About 'App version' no " + "longer showing") + + +@and_test(expects=("nav_reach_licenses",)) +def test_reach_licenses(): + nodes = _open_library() + hop1 = and_reach_more_sheet(nodes) + hop2 = and_reach_about(ui()) + lic = find_node(ui(), text="Open source licenses") + # Licenses sub-screen: a library entry 'AboutLibraries...' appears; About + # 'App version' leaves. + hop3 = lic is not None and and_reach_surface(lic, "AboutLibraries", "App version") + ok = hop1 and hop2 and hop3 + record("nav_reach_licenses", ok, + "" if ok else "feature_missing: About->Open source licenses did not reach " + "the licenses surface ('AboutLibraries' absent)", + depth=3, jump_kind="reach", + expect="Licenses ('AboutLibraries') shown; About 'App version' no longer " + "showing") + + +@and_test(expects=("nav_backstack_credits_to_about",)) +def test_backstack_credits_to_about(): + nodes = _open_library() + hop1 = and_reach_more_sheet(nodes) + hop2 = and_reach_about(ui()) + cr = find_node(ui(), text="Credits") + hop3 = cr is not None and and_reach_surface(cr, "Tachiyomi (Mihon)", "App version") + # BACK from Credits returns to About ('App version' reappears; the Credits + # acknowledgement 'Tachiyomi (Mihon)' leaves). + before = and_showing() + and_back(); settle("tap") + after = and_showing() + to_about = and_reach(before, after, "App version", "Tachiyomi (Mihon)") + ok = hop1 and hop2 and hop3 and to_about + record("nav_backstack_credits_to_about", ok, + "" if ok else "behavior_wrong: BACK from Credits did not return to the " + "About screen ('App version' not restored)", + depth=3, jump_kind="reach", + expect="About ('App version') restored after one BACK from Credits") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (F) Search open / exit — in-place surface swap, reach +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_search",)) +def test_reach_search(): + nodes = _open_library() + srch = find_node(nodes, content_desc="Search") + # Search surface: the 'Exit search' affordance appears; the 'Filter' toolbar + # icon (present only when NOT searching) leaves. + ok = srch is not None and and_reach_surface(srch, "Exit search", "Filter") + record("nav_reach_search", ok, + "" if ok else "feature_missing: Search icon did not open the in-place " + "search surface ('Exit search' absent)", + depth=1, jump_kind="reach", + expect="Search surface ('Exit search') shown; toolbar 'Filter' no longer " + "showing") + + +@and_test(expects=("nav_backstack_exit_search",)) +def test_backstack_exit_search(): + nodes = _open_library() + srch = find_node(nodes, content_desc="Search") + deep = srch is not None and and_reach_surface(srch, "Exit search", "Filter") + # Exit search restores the normal Library toolbar ('Filter' returns; the + # 'Exit search' affordance leaves). + ex = find_node(ui(), content_desc="Exit search") + restored = ex is not None and and_reach_surface(ex, "Filter", "Exit search") + ok = deep and restored + record("nav_backstack_exit_search", ok, + "" if ok else "behavior_wrong: Exit search did not restore the Library " + "toolbar ('Filter' not restored)", + depth=1, jump_kind="reach", + expect="Library toolbar ('Filter') restored after Exit search") + + +TESTS = [ + # (A) tabs + test_reach_history, + test_reach_browse, + test_reach_library_from_browse, + test_backstack_tab_history, + # (B) settings tree + test_reach_more_sheet, + test_reach_settings, + test_reach_appearance, + test_reach_reader_settings_screen, + test_reach_general, + test_reach_library_settings, + test_reach_browse_settings, + test_backstack_settings_to_library, + # (C) book info / reader + test_reach_book_info, + test_reach_reader, + test_backstack_reader_to_info, + test_backstack_info_to_library, + # (D) reader panels + test_reach_reader_settings_sheet, + test_reach_chapters_drawer, + # (E) about tree + test_reach_about, + test_reach_credits, + test_reach_licenses, + test_backstack_credits_to_about, + # (F) search + test_reach_search, + test_backstack_exit_search, +] + +if __name__ == "__main__": + run_suite(TESTS, "navigation") diff --git a/android/acclorite-book-story/tests/test_android_states.py b/android/acclorite-book-story/tests/test_android_states.py new file mode 100644 index 0000000000000000000000000000000000000000..391e91cf6d1a3ac0e44efbb8c9c57c8e61518eca --- /dev/null +++ b/android/acclorite-book-story/tests/test_android_states.py @@ -0,0 +1,1044 @@ +#!/usr/bin/env python3 +"""STATES module — CHECKED / SELECTED transitions, page-state, focus, and +SETTINGS PERSISTENCE across process death for Book's Story. + +Lane: the app's toggles, modes and conditional controls. SOLE OWNER of `checked` +and `focused`. Every test reads the state BEFORE (fresh ui()), drives the user +path, reads AFTER, asserts it TRANSITIONED, and asserts the app-authored +CONSEQUENCE — never a bare flip. Persistence tests kill the process +(restart_app) and re-assert the state survived (DataStore). + +GROUND TRUTH — every state/consequence below was OBSERVED on the running original +with scratch scripts before it was asserted here: + + Appearance (Library ▸ More ▸ Settings ▸ Appearance): + * Dark theme segmented System/Disabled/Enabled — a content-desc="Selected" + checkmark sits immediately LEFT of the chosen segment's label. System + selected by default. Tapping Enabled: (a) marker moves to Enabled, (b) a + NEW "Pure dark" segmented section APPEARS (dump-readable consequence), + (c) the whole app renders dark. Survives restart_app (verified). + * App theme cards Mercury/Neptune/Earth — each is a large clickable card View + with its name label BELOW it; the "Selected" checkmark sits INSIDE the + chosen card. Mercury selected by default. Tapping the Neptune CARD moves the + marker into Neptune and changes the accent colour. + * "Show navigation labels" toggle (ON by default). Its Switch does NOT expose + `checked` in the tree (Compose renders it as plain Views), so the states + assertion is the CONSEQUENCE: the Library/History/Browse text labels under + the bottom-nav icons (y>2000) DISAPPEAR when it is OFF. Survives restart. + Library settings (▸ Library): + * Display mode segmented Grid/List (Grid default, "Selected" marker rule). + List → the Library covers restack vertically (same x, different y) instead + of side-by-side (same y, different x). Survives restart (verified). + * Title position cards Hidden/Below/Inside — these DO expose checkable/checked; + Below=true by default. Tapping Hidden flips Hidden=true, Below=false. + Reader settings sheet (open a book ▸ tap center ▸ Reader settings icon ▸ Reader + tab) — all segmented, same "Selected" marker rule: + * Font style Normal/Italic (Normal default). + * Text alignment Start/Justify/Center/End. + * Progress count Percentage/Quantity (Percentage default). + * Chapter title alignment Start/Justify/Center/End. + Library Search: tapping the Search icon opens a single EditText that receives + focus (focused="true"). + +The "Selected" marker rule (verified by tapping each control and watching the +marker MOVE to the tapped segment): the selected segment is the label whose left +edge is nearest-right of the marker's right edge, on the same row. Assertions are +TRANSITIONS (before != after AND after == the segment we tapped), so the semantic +default never has to be hard-coded. + +Depth: Settings sub-screens are depth 2 (Library=0 → Settings root=1 → category=2), +backed by and_reach_settings_root() + and_enter_category(). The reader settings +sheet is depth 3, backed by and_reach_book_info → and_reach_reader → +and_enter_reader_sheet. Never clear_data(); settings persist across restart_app(). +""" +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 +import book_fixture as bf # shared, validated import helper + +COVER = "Cover image not found" +BOOK1 = bf.BOOK1_TITLE + +TESTS = [] + + +def _t(fn): + TESTS.append(fn) + return fn + + +# ── navigation helpers (depth family — name-matched by and_audit_depth) ────────── + +def _reach_library(retries: int = 6) -> bool: + wait_for_foreground() + for _ in range(retries): + bf._open_tab("Library") + if find_node(ui(), text="Settings") is None: # not yet in a submenu + nodes = ui() + if find_node(nodes, content_desc="More") is not None: + return True + settle("tap") + return find_node(ui(), content_desc="More") is not None + + +def and_reach_settings_root() -> bool: + """Library ▸ More ▸ Settings. PROVE the jump into the Settings root. Depth 1.""" + more = find_node(ui(), content_desc="More") + if more is None or not tap_node(more): + return False + settle("tap") + time.sleep(0.6) + st = find_node(ui(), text="Settings") + if st is None: + return False + if and_reach_surface(st, target="Appearance", source="Search"): + return True + # fallback: confirm the root by its category rows + ok = find_node(ui(), text="Appearance") is not None and \ + find_node(ui(), text="Reader") is not None + if ok: + and_enter("settings_root") + return ok + + +def and_enter_category(name: str) -> bool: + """From the Settings root, open a category sub-screen and confirm the shape + changed. Depth 2.""" + row = find_node(ui(), text=name) + if row is None: + return False + ok, _note = and_enter_surface(ui(), target_text=name) + return ok + + +def _open_settings_category(name: str) -> bool: + """Full path Library → Settings root → category. Leaves depth at 2.""" + restart_app() + if not _reach_library(): + return False + if not and_reach_settings_root(): + return False + return and_enter_category(name) + + +def and_reach_book_info() -> bool: + """Tap the book cover and PROVE the jump into Book Info. Depth 1.""" + nodes = ui() + cover = find_node(nodes, content_desc=COVER) + if cover is None: + covers = [n for n in nodes if "Cover image" in (n.get("content-desc") or "")] + cover = covers[0] if covers else None + if cover is None: + return False + if and_reach_surface(cover, target="Start", source="Continue reading"): + return True + return find_node(ui(), text="Move") is not None + + +def and_reach_reader() -> bool: + """From Book Info tap Start; confirm reader body text rendered. Depth 2.""" + start = find_node(ui(), text="Start") or find_node(ui(), text="Continue") + if start is None or not tap_node(start): + return False + settle("launch") + time.sleep(1.5) + got = find_node(ui(), text="Got it") + if got: + tap_node(got) + settle("tap") + and_enter("reader") + return find_node(ui(), text="Chapter One") is not None + + +def and_enter_reader_sheet(tab: str = "Reader") -> bool: + """Reveal the reader bars, open the Reader settings sheet, switch to `tab`. + Confirms the sheet's tab row appeared. Depth 3.""" + info = get_screen_info() + tap(info["center_x"], info["center_y"]) + settle("tap") + time.sleep(1) + rs = find_node(ui(), content_desc="Reader settings") + if rs is None or not tap_node(rs): + return False + settle("launch") + time.sleep(1) + nodes = ui() + ok = find_node(nodes, text="Colors") is not None and \ + find_node(nodes, text="Reader") is not None + if not ok: + return False + and_enter("reader_settings_sheet") + t = find_node(ui(), text=tab) + if t and not (find_node(ui(), text=tab).get("selected") == "true"): + tap_node(t) + settle("tap") + time.sleep(0.6) + return True + + +def _reach_reader_tab(tab: str = "Reader") -> bool: + restart_app() + if not _reach_library(): + return False + if not and_reach_book_info(): + return False + if not and_reach_reader(): + return False + return and_enter_reader_sheet(tab) + + +# ── selection-marker helpers (the "Selected" checkmark rule, verified) ─────────── + +def _selected_segment(section: str, seg_labels, y_window: int = 200): + """Which labelled segment on `section`'s row carries the 'Selected' checkmark. + + Rule (verified by tapping each control): the marker sits immediately LEFT of + the chosen label, so the selected segment is the label whose left edge is + nearest-right of the marker's right edge, on the same row band below the + section header. + """ + nodes = ui() + hdr = find_node(nodes, text=section) + if hdr is None: + return None + hy = hdr["_bounds"][3] + segs = {} + for lbl in seg_labels: + for n in find_nodes(nodes, text=lbl): + b = n["_bounds"] + if hy <= b[1] <= hy + y_window: + segs[lbl] = b + marker = None + for n in nodes: + if n.get("content-desc") == "Selected": + b = n["_bounds"] + if hy <= b[1] <= hy + y_window: + marker = b + break + if marker is None or not segs: + return None + # nearest label to the RIGHT of the marker (smallest non-negative gap wins, + # falling back to absolute nearest so a right-most selection still resolves) + right = [(b[0] - marker[2], lbl) for lbl, b in segs.items() if b[0] >= marker[2] - 30] + if right: + return min(right)[1] + return min((abs(b[0] - marker[2]), lbl) for lbl, b in segs.items())[1] + + +def _tap_segment(section: str, label: str, y_window: int = 200) -> bool: + """Tap the segment `label` on `section`'s row (re-dumps for fresh bounds).""" + nodes = ui() + hdr = find_node(nodes, text=section) + if hdr is None: + return False + hy = hdr["_bounds"][3] + for n in find_nodes(nodes, text=label): + b = n["_bounds"] + if hy <= b[1] <= hy + y_window: + return tap_node(n) + return False + + +def _reveal_segments(section: str, seg_labels, extra_swipes: int = 3) -> bool: + """Scroll so `section`'s SEGMENTS (not just its header) are on screen. A row + at the bottom of a scroll view can have its header visible while its segment + pills are still below the fold — scroll_into_view stops at the header, so we + nudge down until at least one segment label is present in the dump.""" + scroll_into_view(section) + for _ in range(extra_swipes + 1): + nodes = ui() + hdr = find_node(nodes, text=section) + if hdr is not None: + hy = hdr["_bounds"][3] + for lbl in seg_labels: + for n in find_nodes(nodes, text=lbl): + if hy <= n["_bounds"][1] <= hy + 200: + return True + scroll_down(0.35) + return False + + +def _app_theme_card(nodes, label: str): + """The clickable App-theme card View whose name label sits just below it.""" + lab = find_node(nodes, text=label) + if lab is None: + return None + lx = lab["_center"][0] + ly = lab["_bounds"][1] + best = None + for n in nodes: + b = n.get("_bounds") + if b and n.get("clickable") == "true": + if b[0] <= lx <= b[2] and b[3] <= ly + 12 and (ly - b[3]) < 90: + best = n + return best + + +def _app_theme_selected(nodes): + """Which App-theme card (Mercury/Neptune/Earth) holds the 'Selected' marker.""" + hdr = find_node(nodes, text="App theme") + if hdr is None: + return None + hy = hdr["_bounds"][3] + marker = None + for n in nodes: + if n.get("content-desc") == "Selected" and hy < n["_bounds"][1] < 1450: + marker = n["_bounds"] + break + if marker is None: + return None + mcx = (marker[0] + marker[2]) // 2 + for label in ("Mercury", "Neptune", "Earth"): + card = _app_theme_card(nodes, label) + if card and card["_bounds"][0] <= mcx <= card["_bounds"][2]: + return label + return None + + +def _nav_labels_present(): + """The set of bottom-nav TEXT labels (y>2000) currently under the icons.""" + nodes = ui() + out = set() + for lbl in ("Library", "History", "Browse"): + for n in find_nodes(nodes, text=lbl): + b = n.get("_bounds") + if b and b[1] > 2000: + out.add(lbl) + break + return out + + +def _nav_labels_toggle(): + """Tap the 'Show navigation labels' clickable row (must be on the Appearance + screen). Returns True if tapped.""" + scroll_into_view("Show navigation labels") + nodes = ui() + lab = find_node(nodes, text="Show navigation labels") + if lab is None: + return False + ly = lab["_bounds"][1] + for n in nodes: + b = n.get("_bounds") + if (b and n.get("clickable") == "true" and b[0] < 50 and b[2] > 1000 + and abs(b[1] - (ly - 20)) < 130): + return tap_node(n) + return False + + +def _cover_layout(): + """Classify the Library cover layout: 'grid' = >=2 covers sharing a y-band but + spread in x; 'list' = >=2 covers sharing an x-band but stacked in y; else ''.""" + nodes = ui() + pts = [n["_center"] for n in nodes if (n.get("content-desc") or "") == COVER] + if len(pts) < 2: + return "" + xs = [p[0] for p in pts] + ys = [p[1] for p in pts] + x_spread = max(xs) - min(xs) + y_spread = max(ys) - min(ys) + if x_spread > 150 and y_spread < 120: + return "grid" + if y_spread > 150 and x_spread < 120: + return "list" + return "" + + +def _title_pos_checked(nodes): + """{'Hidden':'true'/'false', ...} for the Library Title-position cards.""" + out = {} + for lbl in ("Hidden", "Below", "Inside"): + n = find_node(nodes, text=lbl) + if n is None: + continue + lx, ly = n["_center"] + for c in nodes: + b = c.get("_bounds") + if (b and c.get("checkable") == "true" + and b[0] <= lx <= b[2] and b[1] <= ly <= b[3]): + out[lbl] = c.get("checked") + break + return out + + +def _tap_title_pos(nodes, label: str) -> bool: + n = find_node(nodes, text=label) + if n is None: + return False + lx, ly = n["_center"] + for c in nodes: + b = c.get("_bounds") + if (b and c.get("checkable") == "true" + and b[0] <= lx <= b[2] and b[1] <= ly <= b[3]): + return tap_node(c) + return tap_node(n) + + +def _shot(name): + p = os.path.join(RESULTS_DIR, "screenshots", f"_states_{name}.png") + screencap(p) + return p + + +def _open_appearance() -> bool: + return _open_settings_category("Appearance") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1. Dark theme — flagship: transition + consequence + persistence + VLM(x3) +# ══════════════════════════════════════════════════════════════════════════════ + +@_t +@and_test(expects=("states_dark_theme_enable", "states_dark_theme_enable_vlm")) +def test_dark_theme_enable(): + """Dark theme System → Enabled: the 'Selected' marker moves to Enabled AND a + new 'Pure dark' section appears (the app-authored dark-mode consequence). + Restores to System. Depth 2.""" + name = "states_dark_theme_enable" + exp = "Dark theme selected System->Enabled; 'Pure dark' section now showing" + if not _open_appearance(): + record(name, False, "setup_failed: could not reach Appearance", + depth=2, jump_kind="transition", expect=exp) + record(name + "_vlm", False, "setup_failed: could not reach Appearance", + depth=2, jump_kind="none", tag="color") + return + segs = ["System", "Disabled", "Enabled"] + before = _selected_segment("Dark theme", segs) + pure_before = find_node(ui(), text="Pure dark") is not None + _tap_segment("Dark theme", "Enabled") + settle("tap") + time.sleep(0.8) + after = _selected_segment("Dark theme", segs) + pure_after = find_node(ui(), text="Pure dark") is not None + ok = (before == "System" and after == "Enabled" and not pure_before and pure_after) + record(name, ok, + "" if ok else + f"behavior_wrong: dark selected {before!r}->{after!r}, 'Pure dark' " + f"{pure_before}->{pure_after}; expected System->Enabled with Pure dark appearing", + depth=2, jump_kind="transition", expect=exp) + _shot("dark_enabled") + vlm_assert(name, + "Is the background of this settings screen a dark/near-black colour " + "with light-coloured text (dark mode), rather than a white/light " + "background?", + RESULTS_DIR, expect="YES", depth=2, jump_kind="none", tag="color") + # restore to System + if _open_appearance(): + _tap_segment("Dark theme", "System") + settle("tap") + + +@_t +@and_test(expects=("states_dark_theme_persists", "states_dark_theme_persists_vlm")) +def test_dark_theme_persists(): + """Enable dark theme, kill the process (restart_app), re-open Appearance and + assert Enabled is STILL selected AND still renders dark — DataStore persistence + across process death. Restores to System. Depth 2.""" + name = "states_dark_theme_persists" + exp = "after process death Dark theme is STILL Enabled; app still renders dark" + segs = ["System", "Disabled", "Enabled"] + if not _open_appearance(): + record(name, False, "setup_failed: could not reach Appearance", + depth=2, jump_kind="transition", expect=exp) + record(name + "_vlm", False, "setup_failed: could not reach Appearance", + depth=2, jump_kind="none", tag="color") + return + _tap_segment("Dark theme", "Enabled") + settle("tap") + time.sleep(0.6) + set_ok = _selected_segment("Dark theme", segs) == "Enabled" + # process death + relaunch, then re-open Appearance + reopened = _open_appearance() + persisted = _selected_segment("Dark theme", segs) if reopened else None + pure = find_node(ui(), text="Pure dark") is not None + ok = set_ok and reopened and persisted == "Enabled" and pure + record(name, ok, + "" if ok else + f"behavior_wrong: set Enabled={set_ok}, after restart selected=" + f"{persisted!r} pure_dark={pure}; expected Enabled to persist", + depth=2, jump_kind="transition", expect=exp) + _shot("dark_persisted") + vlm_assert(name, + "After the app was restarted, is this settings screen still rendered " + "in dark mode — a dark/near-black background with light text (not a " + "white/light background)?", + RESULTS_DIR, expect="YES", depth=2, jump_kind="none", tag="color") + # restore to System so later tests start light + if _open_appearance(): + _tap_segment("Dark theme", "System") + settle("tap") + + +@_t +@and_test(expects=("states_dark_theme_highlight_vlm",)) +def test_dark_theme_highlight_vlm(): + """The chosen Dark-theme segment (Enabled) is visually highlighted with a + coloured/filled pill distinct from the other two segments — a rendered + selection property the dump's marker alone cannot confirm. Restores. Depth 2.""" + name = "states_dark_theme_highlight" + if not _open_appearance(): + record(name + "_vlm", False, "setup_failed: could not reach Appearance", + depth=2, jump_kind="none", tag="shape") + return + _tap_segment("Dark theme", "Enabled") + settle("tap") + time.sleep(0.6) + _shot("dark_highlight") + vlm_assert(name, + "In the 'Dark theme' row (segments System, Disabled, Enabled), is the " + "'Enabled' segment visually highlighted with a coloured/filled " + "background pill that the other two segments do NOT have?", + RESULTS_DIR, expect="YES", depth=2, jump_kind="none", tag="shape") + if _open_appearance(): + _tap_segment("Dark theme", "System") + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2. App theme cards — Mercury -> Neptune (marker moves) + accent-colour VLM(x2) +# ══════════════════════════════════════════════════════════════════════════════ + +@_t +@and_test(expects=("states_app_theme_select", "states_app_theme_select_vlm")) +def test_app_theme_select(): + """App theme Mercury → Neptune: tapping the Neptune CARD moves the 'Selected' + checkmark into Neptune (before != after, after == Neptune) and changes the + accent colour. Restores to Mercury. Depth 2.""" + name = "states_app_theme_select" + exp = "App theme selected Mercury->Neptune (marker moves into the Neptune card)" + if not _open_appearance(): + record(name, False, "setup_failed: could not reach Appearance", + depth=2, jump_kind="transition", expect=exp) + record(name + "_vlm", False, "setup_failed: could not reach Appearance", + depth=2, jump_kind="none", tag="color") + return + scroll_into_view("App theme") + nodes = ui() + before = _app_theme_selected(nodes) + card = _app_theme_card(nodes, "Neptune") + if card is None or not tap_node(card): + record(name, False, "setup_failed: Neptune card not tappable", + depth=2, jump_kind="transition", expect=exp) + record(name + "_vlm", False, "setup_failed: Neptune card not tappable", + depth=2, jump_kind="none", tag="color") + return + settle("tap") + time.sleep(0.8) + after = _app_theme_selected(ui()) + ok = before == "Mercury" and after == "Neptune" + record(name, ok, + "" if ok else + f"behavior_wrong: app theme selected {before!r}->{after!r}; " + f"expected Mercury->Neptune", + depth=2, jump_kind="transition", expect=exp) + _shot("app_theme_neptune") + vlm_assert(name, + "In this 'App theme' setting, is the currently selected theme card " + "(the one with a check mark) labelled 'Neptune' and showing a " + "blue/indigo colour swatch?", + RESULTS_DIR, expect="YES", depth=2, jump_kind="none", tag="color") + # restore Mercury + nodes = ui() + m = _app_theme_card(nodes, "Mercury") + if m: + tap_node(m) + settle("tap") + + +@_t +@and_test(expects=("states_app_theme_ring_vlm",)) +def test_app_theme_ring_vlm(): + """The selected App-theme card is drawn with a highlight ring / check-mark + badge that the unselected cards lack — a rendered selection cue. Depth 2.""" + name = "states_app_theme_ring" + if not _open_appearance(): + record(name + "_vlm", False, "setup_failed: could not reach Appearance", + depth=2, jump_kind="none", tag="shape") + return + scroll_into_view("App theme") + _shot("app_theme_ring") + vlm_assert(name, + "In this 'App theme' card row (Mercury, Neptune, Earth), does exactly " + "one card show a check-mark / selection badge marking it as the " + "chosen theme?", + RESULTS_DIR, expect="YES", depth=2, jump_kind="none", tag="shape") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3. Show navigation labels — consequence (labels vanish) + persistence + VLM +# ══════════════════════════════════════════════════════════════════════════════ + +@_t +@and_test(expects=("states_nav_labels_hide", "states_nav_labels_hide_vlm")) +def test_nav_labels_hide(): + """'Show navigation labels' OFF: the Library/History/Browse TEXT labels under + the bottom-nav icons disappear. The Switch does not expose `checked`, so the + app-authored CONSEQUENCE (labels gone) is the state assertion. Restores. Depth 2.""" + name = "states_nav_labels_hide" + exp = "nav-bar text labels present -> gone after toggling 'Show navigation labels' off" + # baseline: confirm labels present on the Library + restart_app() + if not _reach_library(): + record(name, False, "setup_failed: Library not reachable", + depth=2, jump_kind="transition", expect=exp) + record(name + "_vlm", False, "setup_failed: Library not reachable", + depth=2, jump_kind="none", tag="position") + return + before = _nav_labels_present() + if not (and_reach_settings_root() and and_enter_category("Appearance")): + record(name, False, "setup_failed: could not reach Appearance", + depth=2, jump_kind="transition", expect=exp) + record(name + "_vlm", False, "setup_failed: could not reach Appearance", + depth=2, jump_kind="none", tag="position") + return + if not _nav_labels_toggle(): + record(name, False, "setup_failed: could not toggle 'Show navigation labels'", + depth=2, jump_kind="transition", expect=exp) + record(name + "_vlm", False, "setup_failed: toggle not found", + depth=2, jump_kind="none", tag="position") + return + settle("tap") + # back to Library and read the labels + restart_app() + _reach_library() + after = _nav_labels_present() + ok = before == {"Library", "History", "Browse"} and after == set() + record(name, ok, + "" if ok else + f"behavior_wrong: nav labels {sorted(before)}->{sorted(after)}; " + f"expected all three present then all gone", + depth=2, jump_kind="transition", expect=exp) + _shot("nav_labels_off") + vlm_assert(name, + "Look at the bottom navigation bar of this app. Are the icons shown " + "WITHOUT any text labels underneath them (no 'Library'/'History'/" + "'Browse' words under the bottom-bar icons)?", + RESULTS_DIR, expect="YES", depth=2, jump_kind="none", tag="position") + # restore labels ON + if _reach_library() and and_reach_settings_root() and and_enter_category("Appearance"): + _nav_labels_toggle() + settle("tap") + + +@_t +@and_test(expects=("states_nav_labels_persist",)) +def test_nav_labels_persist(): + """Toggle nav labels OFF, kill the process, and confirm they are STILL hidden + on the Library after relaunch — the setting persists across process death. + Restores labels ON. Depth 2.""" + name = "states_nav_labels_persist" + exp = "nav labels hidden survive process death (still gone after restart)" + restart_app() + if not (_reach_library() and and_reach_settings_root() + and and_enter_category("Appearance")): + record(name, False, "setup_failed: could not reach Appearance", + depth=2, jump_kind="transition", expect=exp) + return + if not _nav_labels_toggle(): + record(name, False, "setup_failed: could not toggle nav labels", + depth=2, jump_kind="transition", expect=exp) + return + settle("tap") + # process death, relaunch, check Library + restart_app() + _reach_library() + after = _nav_labels_present() + ok = after == set() + record(name, ok, + "" if ok else + f"behavior_wrong: after restart nav labels are {sorted(after)}; " + f"expected still hidden (empty)", + depth=2, jump_kind="transition", expect=exp) + # restore labels ON + if _reach_library() and and_reach_settings_root() and and_enter_category("Appearance"): + _nav_labels_toggle() + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4. Library Display mode Grid -> List — consequence (layout) + persist + VLM(x3) +# ══════════════════════════════════════════════════════════════════════════════ + +@_t +@and_test(expects=("states_display_mode_list", "states_display_mode_list_grid_vlm", + "states_display_mode_list_list_vlm")) +def test_display_mode_list(): + """Display mode Grid → List: the 'Selected' marker moves to List AND the + Library covers restack vertically (list) instead of side-by-side (grid) — the + app-authored layout consequence. Restores to Grid. Depth 2.""" + name = "states_display_mode_list" + exp = "Display mode Grid->List; Library covers restack from a row to a column" + bf.import_book(BOOK1, bf.BOOK1_FILE) + bf.import_book(bf.BOOK2_TITLE, bf.BOOK2_FILE) + # baseline grid layout on the Library + restart_app() + if not _reach_library(): + record(name, False, "setup_failed: Library not reachable", + depth=2, jump_kind="transition", expect=exp) + record(name + "_grid_vlm", False, "setup_failed: Library not reachable", + depth=0, jump_kind="none", tag="layout") + record(name + "_list_vlm", False, "setup_failed: Library not reachable", + depth=2, jump_kind="none", tag="layout") + return + grid_layout = _cover_layout() + _shot("library_grid") + vlm_assert(name + "_grid", + "On this Library screen, are the book covers arranged side by side in " + "a GRID (two or more covers in the same horizontal row), rather than " + "stacked vertically in a single-column list?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="none", tag="layout") + # flip to List + if not (and_reach_settings_root() and and_enter_category("Library")): + record(name, False, "setup_failed: could not reach Library settings", + depth=2, jump_kind="transition", expect=exp) + record(name + "_list_vlm", False, "setup_failed: could not reach Library settings", + depth=2, jump_kind="none", tag="layout") + return + scroll_into_view("Display mode") + before = _selected_segment("Display mode", ["Grid", "List"]) + _tap_segment("Display mode", "List") + settle("tap") + time.sleep(0.6) + after = _selected_segment("Display mode", ["Grid", "List"]) + # observe the Library layout after the change + restart_app() + _reach_library() + list_layout = _cover_layout() + ok = (before == "Grid" and after == "List" + and grid_layout == "grid" and list_layout == "list") + record(name, ok, + "" if ok else + f"behavior_wrong: selected {before!r}->{after!r}, layout " + f"{grid_layout!r}->{list_layout!r}; expected Grid->List and grid->list", + depth=2, jump_kind="transition", expect=exp) + _shot("library_list") + vlm_assert(name + "_list", + "On this Library screen, are the book covers now stacked vertically " + "in a single-column LIST (each book on its own row, one above the " + "other), rather than side by side in a grid?", + RESULTS_DIR, expect="YES", depth=2, jump_kind="none", tag="layout") + # restore to Grid + if _reach_library() and and_reach_settings_root() and and_enter_category("Library"): + scroll_into_view("Display mode") + _tap_segment("Display mode", "Grid") + settle("tap") + + +@_t +@and_test(expects=("states_display_mode_persists", "states_display_mode_persists_vlm")) +def test_display_mode_persists(): + """Set Display mode to List, kill the process, and confirm List is STILL + selected AND the Library still renders as a list after relaunch. Restores to + Grid. Depth 2.""" + name = "states_display_mode_persists" + exp = "after process death Display mode is STILL List; Library still a column" + bf.import_book(BOOK1, bf.BOOK1_FILE) + bf.import_book(bf.BOOK2_TITLE, bf.BOOK2_FILE) + if not _open_settings_category("Library"): + record(name, False, "setup_failed: could not reach Library settings", + depth=2, jump_kind="transition", expect=exp) + record(name + "_vlm", False, "setup_failed: could not reach Library settings", + depth=2, jump_kind="none", tag="layout") + return + scroll_into_view("Display mode") + _tap_segment("Display mode", "List") + settle("tap") + time.sleep(0.6) + set_ok = _selected_segment("Display mode", ["Grid", "List"]) == "List" + # process death; re-open Library settings and check the marker + reopened = _open_settings_category("Library") + if reopened: + scroll_into_view("Display mode") + persisted = _selected_segment("Display mode", ["Grid", "List"]) if reopened else None + # and the Library layout itself + restart_app() + _reach_library() + layout = _cover_layout() + _shot("library_list_persist") + ok = set_ok and persisted == "List" and layout == "list" + record(name, ok, + "" if ok else + f"behavior_wrong: set List={set_ok}, after restart selected={persisted!r} " + f"layout={layout!r}; expected List to persist as a column", + depth=2, jump_kind="transition", expect=exp) + vlm_assert(name, + "After the app was restarted, on this Library screen are the book " + "covers still stacked vertically in a single-column LIST (one book " + "per row) rather than in a side-by-side grid?", + RESULTS_DIR, expect="YES", depth=2, jump_kind="none", tag="layout") + # restore to Grid + if _reach_library() and and_reach_settings_root() and and_enter_category("Library"): + scroll_into_view("Display mode") + _tap_segment("Display mode", "Grid") + settle("tap") + + +@_t +@and_test(expects=("states_display_highlight_vlm",)) +def test_display_highlight_vlm(): + """The chosen Display-mode segment is drawn as a coloured/filled pill distinct + from the other — a rendered selection colour. Depth 2.""" + name = "states_display_highlight" + if not _open_settings_category("Library"): + record(name + "_vlm", False, "setup_failed: could not reach Library settings", + depth=2, jump_kind="none", tag="color") + return + scroll_into_view("Display mode") + _shot("display_highlight") + vlm_assert(name, + "In the 'Display mode' row (segments 'Grid' and 'List'), is exactly " + "one of the two segments visually highlighted with a coloured/filled " + "background pill (the selected one) while the other is plain?", + RESULTS_DIR, expect="YES", depth=2, jump_kind="none", tag="color") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5. Library Title position — a dump-readable CHECKED transition (Below -> Hidden) +# ══════════════════════════════════════════════════════════════════════════════ + +@_t +@and_test(expects=("states_title_position_toggle",)) +def test_title_position_toggle(): + """Title position cards Hidden/Below/Inside expose checkable/checked. Below is + checked by default; tapping Hidden flips Hidden=true and Below=false (a single + exclusive checked group). Restores to Below. Depth 2.""" + name = "states_title_position_toggle" + exp = "Title position checked: Below true->false, Hidden false->true" + if not _open_settings_category("Library"): + record(name, False, "setup_failed: could not reach Library settings", + depth=2, jump_kind="transition", expect=exp) + return + scroll_into_view("Title position") + before = _title_pos_checked(ui()) + if not _tap_title_pos(ui(), "Hidden"): + record(name, False, "setup_failed: Hidden card not tappable", + depth=2, jump_kind="transition", expect=exp) + return + settle("tap") + time.sleep(0.5) + after = _title_pos_checked(ui()) + ok = (before.get("Below") == "true" and before.get("Hidden") == "false" + and after.get("Hidden") == "true" and after.get("Below") == "false") + record(name, ok, + "" if ok else + f"behavior_wrong: Title position checked {before}->{after}; " + f"expected Below true->false and Hidden false->true", + depth=2, jump_kind="transition", expect=exp) + # restore Below + scroll_into_view("Title position") + _tap_title_pos(ui(), "Below") + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 6. Reader settings segmented controls (depth 3) — marker transitions + VLM(x2) +# ══════════════════════════════════════════════════════════════════════════════ + +@_t +@and_test(expects=("states_font_style_italic", "states_font_style_italic_highlight_vlm")) +def test_font_style_italic(): + """Reader ▸ Font style Normal → Italic: the 'Selected' marker moves to Italic + (before Normal, after Italic). Depth 3.""" + name = "states_font_style_italic" + exp = "Font style selected Normal->Italic (marker moves to Italic)" + if not _reach_reader_tab("Reader"): + record(name, False, "setup_failed: could not reach reader settings Reader tab", + depth=3, jump_kind="transition", expect=exp) + record(name + "_highlight_vlm", False, "setup_failed: reader Reader tab unreachable", + depth=3, jump_kind="none", tag="shape") + return + scroll_into_view("Font style") + # Font style persists via DataStore; force a known Normal baseline so the + # Normal->Italic transition is observable regardless of prior runs' state. + if _selected_segment("Font style", ["Normal", "Italic"]) != "Normal": + _tap_segment("Font style", "Normal") + settle("tap") + time.sleep(0.4) + scroll_into_view("Font style") + before = _selected_segment("Font style", ["Normal", "Italic"]) + _tap_segment("Font style", "Italic") + settle("tap") + time.sleep(0.6) + after = _selected_segment("Font style", ["Normal", "Italic"]) + ok = before == "Normal" and after == "Italic" + record(name, ok, + "" if ok else + f"behavior_wrong: font style selected {before!r}->{after!r}; " + f"expected Normal->Italic", + depth=3, jump_kind="transition", expect=exp) + _shot("font_style_italic") + vlm_assert(name + "_highlight", + "In the 'Font style' row (segments 'Normal' and 'Italic'), is the " + "'Italic' segment the one visually highlighted with a coloured/filled " + "background pill (marking it selected) rather than 'Normal'?", + RESULTS_DIR, expect="YES", depth=3, jump_kind="none", tag="shape") + # restore Normal so this test does not perturb later runs + scroll_into_view("Font style") + _tap_segment("Font style", "Normal") + settle("tap") + + +@_t +@and_test(expects=("states_progress_count_change", "states_progress_count_change_highlight_vlm")) +def test_progress_count_change(): + """Reader ▸ Progress count Percentage → Quantity: the 'Selected' marker moves + to Quantity (before Percentage, after Quantity). Depth 3.""" + name = "states_progress_count_change" + exp = "Progress count selected Percentage->Quantity (marker moves)" + if not _reach_reader_tab("Reader"): + record(name, False, "setup_failed: could not reach reader settings Reader tab", + depth=3, jump_kind="transition", expect=exp) + record(name + "_highlight_vlm", False, "setup_failed: reader Reader tab unreachable", + depth=3, jump_kind="none", tag="color") + return + if not _reveal_segments("Progress count", ["Percentage", "Quantity"]): + record(name, False, "setup_failed: Progress count segments not reachable", + depth=3, jump_kind="transition", expect=exp) + record(name + "_highlight_vlm", False, + "setup_failed: Progress count segments not reachable", + depth=3, jump_kind="none", tag="color") + return + # Progress count persists via DataStore; force a known Percentage baseline so + # the Percentage->Quantity transition is observable regardless of prior state. + if _selected_segment("Progress count", ["Percentage", "Quantity"]) != "Percentage": + _tap_segment("Progress count", "Percentage") + settle("tap") + time.sleep(0.4) + _reveal_segments("Progress count", ["Percentage", "Quantity"]) + before = _selected_segment("Progress count", ["Percentage", "Quantity"]) + _tap_segment("Progress count", "Quantity") + settle("tap") + time.sleep(0.6) + after = _selected_segment("Progress count", ["Percentage", "Quantity"]) + ok = before == "Percentage" and after == "Quantity" + record(name, ok, + "" if ok else + f"behavior_wrong: progress count selected {before!r}->{after!r}; " + f"expected Percentage->Quantity", + depth=3, jump_kind="transition", expect=exp) + _shot("progress_quantity") + vlm_assert(name + "_highlight", + "In the 'Progress count' row (segments 'Percentage' and 'Quantity'), " + "is the 'Quantity' segment the one visually highlighted with a " + "coloured/filled background pill (marking it selected)?", + RESULTS_DIR, expect="YES", depth=3, jump_kind="none", tag="color") + # restore Percentage so this test does not perturb later runs + _reveal_segments("Progress count", ["Percentage", "Quantity"]) + _tap_segment("Progress count", "Percentage") + settle("tap") + + +@_t +@and_test(expects=("states_text_alignment_change", "states_text_align_highlight_vlm")) +def test_text_alignment_change(): + """Reader ▸ Text alignment: selecting 'Center' moves the 'Selected' marker to + Center (before != Center, after == Center). Depth 3.""" + name = "states_text_alignment_change" + exp = "Text alignment selection moves to Center (marker on a different segment)" + if not _reach_reader_tab("Reader"): + record(name, False, "setup_failed: could not reach reader settings Reader tab", + depth=3, jump_kind="transition", expect=exp) + record("states_text_align_highlight_vlm", False, + "setup_failed: reader Reader tab unreachable", + depth=3, jump_kind="none", tag="shape") + return + scroll_into_view("Text alignment") + labels = ["Start", "Justify", "Center", "End"] + before = _selected_segment("Text alignment", labels) + _tap_segment("Text alignment", "Center") + settle("tap") + time.sleep(0.6) + after = _selected_segment("Text alignment", labels) + ok = after == "Center" and before != "Center" + record(name, ok, + "" if ok else + f"behavior_wrong: text alignment selected {before!r}->{after!r}; " + f"expected a move to Center", + depth=3, jump_kind="transition", expect=exp) + _shot("text_align_center") + vlm_assert("states_text_align_highlight", + "In the 'Text alignment' row (segments Start, Justify, Center, End), " + "is the 'Center' segment the one visually highlighted with a " + "coloured/filled background pill (marking it selected)?", + RESULTS_DIR, expect="YES", depth=3, jump_kind="none", tag="shape") + # restore Start (the default) so a re-run does not begin on Center + scroll_into_view("Text alignment") + _tap_segment("Text alignment", "Start") + settle("tap") + + +@_t +@and_test(expects=("states_chapter_title_align",)) +def test_chapter_title_align(): + """Reader ▸ Chapter title alignment: selecting 'Center' moves the 'Selected' + marker to Center (before != Center, after == Center). Depth 3.""" + name = "states_chapter_title_align" + exp = "Chapter title alignment selection moves to Center" + if not _reach_reader_tab("Reader"): + record(name, False, "setup_failed: could not reach reader settings Reader tab", + depth=3, jump_kind="transition", expect=exp) + return + scroll_into_view("Chapter title alignment") + labels = ["Start", "Justify", "Center", "End"] + before = _selected_segment("Chapter title alignment", labels) + _tap_segment("Chapter title alignment", "Center") + settle("tap") + time.sleep(0.6) + after = _selected_segment("Chapter title alignment", labels) + ok = after == "Center" and before != "Center" + record(name, ok, + "" if ok else + f"behavior_wrong: chapter title alignment selected {before!r}->{after!r}; " + f"expected a move to Center", + depth=3, jump_kind="transition", expect=exp) + # restore Start so a re-run does not begin on Center + scroll_into_view("Chapter title alignment") + _tap_segment("Chapter title alignment", "Start") + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 7. Focus — Library Search field receives focus (states owns `focused`) +# ══════════════════════════════════════════════════════════════════════════════ + +@_t +@and_test(expects=("states_search_focus",)) +def test_search_focus(): + """Tapping the Library Search icon opens a search EditText that HOLDS focus + (focused='true') — the app-authored focus target after that action. Depth 0.""" + name = "states_search_focus" + exp = "after tapping Search, the search EditText reports focused=true" + restart_app() + if not _reach_library(): + record(name, False, "setup_failed: Library not reachable", + depth=0, jump_kind="transition", expect=exp) + return + # no EditText focused before opening search + before_focused = any(e.get("focused") == "true" + for e in find_by_class(ui(), "EditText")) + s = find_node(ui(), content_desc="Search") + if s is None or not tap_node(s): + record(name, False, "feature_missing: no Search control on the Library", + depth=0, jump_kind="transition", expect=exp) + return + settle("tap") + time.sleep(0.8) + edits = find_by_class(ui(), "EditText") + after_focused = any(e.get("focused") == "true" for e in edits) + ok = (not before_focused) and len(edits) >= 1 and after_focused + record(name, ok, + "" if ok else + f"behavior_wrong: EditText present={len(edits)}, focused before=" + f"{before_focused} after={after_focused}; expected an unfocused->focused " + f"search field to appear", + depth=0, jump_kind="transition", expect=exp) + + +if __name__ == "__main__": + if not device_online(): + print("Device offline — aborting (a whole module of setup_failed would be " + "misattributed to the app).") + sys.exit(2) + run_suite(TESTS, "states") diff --git a/android/acclorite-book-story/tests/test_android_structure.py b/android/acclorite-book-story/tests/test_android_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..877baca3a5c53fffbec85caaff66493cf7153f48 --- /dev/null +++ b/android/acclorite-book-story/tests/test_android_structure.py @@ -0,0 +1,734 @@ +"""Structure lane for Book's Story (ebook reader). + +This module owns exactly two things: + + (1) THE GATE — the app launches into the foreground and its top-level + surfaces exist: the main Compose container, the top app-bar action host + (Search / Filter / More), and the bottom-nav host (Library / History / + Browse). These are jump_kind="none", depth=0, and are kept to <=30% of + the suite (3 of 19 rule tests). + + (2) TREE-SHAPE DELTAS — an interaction that changes the tree's SHAPE: a + search field that adds an EditText, a bottom sheet / dialog that adds a + new window layer, an empty<->populated list, a mode switch that adds a + class of widget. Each is recorded as jump_kind="transition" with the + shape DELTA I OBSERVED on the running original, and is REVERSED to assert + it restores. surface_changed(before, after) is the honest primitive here; + this lane never claims `reach` (that is navigation's). + +Everything asserted below was observed on the running original app. Toggles in +this Jetpack-Compose app render as `android.view.View` (NOT android.widget.Switch), +so shape counts use and_showing() size and specific key presence/absence rather +than find_by_class(nodes,"Switch"). + +A real book is imported via the shared book_fixture helper (never inlined); the +kit pushes the fixture bytes before the first test through run_suite(). +""" +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 +import book_fixture as bf # shared import-a-book helper + +RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else os.path.dirname( + os.path.abspath(__file__)) + +BOOK = bf.BOOK1_TITLE # "testbook" + + +# ── local helpers ───────────────────────────────────────────────────────────── + +def _covers(nodes): + """The Library book-cover cards (icon-only, content-desc 'Cover image ...').""" + return [n for n in nodes if "Cover image" in (n.get("content-desc") or "")] + + +def _open_library(): + """Bring the app to the Library tab from a cold restart. Returns node list.""" + restart_app() + wait_for_foreground() + time.sleep(1) + bf._open_tab("Library") + return ui() + + +def _restored(before_keys, after_keys, slack=4): + """True if the surface returned to (approximately) its pre-trigger shape.""" + return len(set(before_keys) ^ set(after_keys)) <= slack + + +# ══════════════════════════════════════════════════════════════════════════════ +# (1) THE GATE — jump_kind="none", depth=0 (3 tests -> 16% of 19, under 30%) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_gate_launch",)) +def test_gate_launch(): + if not device_online(): + record("structure_gate_launch", False, + "setup_failed: device offline (tunnel dropped)", + depth=0, jump_kind="none") + return + nodes = _open_library() + fg = wait_for_foreground() + # Single-activity Compose app: the root is a ComposeView inside a ViewGroup. + container = (find_by_class(nodes, "ComposeView") + or find_by_class(nodes, "FrameLayout") + or find_by_class(nodes, "ViewGroup")) + ok = bool(fg and container) + record("structure_gate_launch", ok, + "" if ok else "setup_failed: app did not reach the foreground with a " + "main container", + depth=0, jump_kind="none") + + +@and_test(expects=("structure_gate_topbar", "structure_gate_topbar_vlm")) +def test_gate_topbar(): + nodes = _open_library() + # The top app-bar action host: three icon-only controls by content-desc. + have = [find_node(nodes, content_desc=cd) is not None + for cd in ("Search", "Filter", "More")] + ok = all(have) + record("structure_gate_topbar", ok, + "" if ok else f"setup_failed: top-bar actions missing " + f"(Search/Filter/More present={have})", + depth=0, jump_kind="none") + vlm_assert("structure_gate_topbar", + "Are there exactly three icon buttons grouped together in the " + "top-right corner of the screen (in the app's top bar)?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("structure_gate_bottomnav", "structure_gate_bottomnav_vlm")) +def test_gate_bottomnav(): + nodes = _open_library() + # Bottom-nav labels sit near the bottom (y>2000); the same words appear as + # a screen title at the top, so disambiguate by y-bound via bf._tab. + tabs = [bf._tab(nodes, lbl) for lbl in ("Library", "History", "Browse")] + ok = all(t is not None for t in tabs) + record("structure_gate_bottomnav", ok, + "" if ok else f"setup_failed: bottom-nav tabs missing " + f"(found={[t is not None for t in tabs]})", + depth=0, jump_kind="none") + vlm_assert("structure_gate_bottomnav", + "Is there a bottom navigation bar with exactly 3 evenly spaced " + "items (each an icon with a label) across the bottom of the screen?", + RESULTS_DIR, tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (2) IN-PLACE SHAPE DELTAS — jump_kind="transition", depth=0 +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_search_shape",)) +def test_search_adds_editable_field(): + """Tapping Search adds an EditText layer + an 'Exit search' control; exiting + removes it. OBSERVED delta: EditText 0 -> 1, restored on Exit search.""" + nodes = _open_library() + et_before = len(find_by_class(nodes, "EditText")) + before = and_showing(nodes) + if not tap_node(find_node(nodes, content_desc="Search")): + record("structure_search_shape", False, + "setup_failed: Search action not tappable", + depth=0, jump_kind="transition", + expect="EditText 0->1 on Search, restored on Exit search") + return + settle("tap") + mid = ui() + et_after = len(find_by_class(mid, "EditText")) + exit_present = find_node(mid, content_desc="Exit search") is not None + opened = (et_after == et_before + 1) and exit_present + # Reverse: exit search must remove the field. + ex = find_node(mid, content_desc="Exit search") + if ex: + tap_node(ex) + settle("tap") + after = ui() + et_end = len(find_by_class(after, "EditText")) + restored = (et_end == et_before) and _restored(before, and_showing(after)) + ok = opened and restored + record("structure_search_shape", ok, + "" if ok else f"behavior_wrong: search field delta not as observed " + f"(before={et_before} open={et_after} end={et_end} " + f"exit={exit_present})", + depth=0, jump_kind="transition", + expect="EditText 0->1 on Search, restored on Exit search") + + +@and_test(expects=("structure_filter_sheet", "structure_filter_sheet_vlm")) +def test_filter_opens_sheet(): + """Filter opens a bottom sheet that adds a Sort/Display option cluster and a + 'Close sheet' control; BACK restores the Library shape.""" + nodes = _open_library() + before = and_showing(nodes) + if not tap_node(find_node(nodes, content_desc="Filter")): + record("structure_filter_sheet", False, + "setup_failed: Filter action not tappable", + depth=0, jump_kind="transition", + expect="Sort-sheet appears (Sort/Display/Alphabetically), restored on back") + vlm_assert("structure_filter_sheet", + "Is there a bottom sheet panel anchored to the bottom edge of " + "the screen, overlaying the content above it?", + RESULTS_DIR, tag="position") + return + settle("tap") + after = ui() + a = and_showing(after) + opened = (surface_changed(before, a) + and find_node_ci(after, "Sort") is not None + and find_node_ci(after, "Display") is not None + and find_node(after, text="Alphabetically") is not None) + # Reverse: BACK closes the sheet (no dangerous control tapped). + back() + settle("tap") + end = ui() + restored = (find_node(end, text="Alphabetically") is None + and _restored(before, and_showing(end))) + ok = opened and restored + record("structure_filter_sheet", ok, + "" if ok else "behavior_wrong: Filter sheet did not open/restore as " + "observed", + depth=0, jump_kind="transition", + expect="Sort-sheet appears (Sort/Display/Alphabetically), restored on back") + # VLM screenshot must show the sheet, so re-open it for the picture. + n2 = _open_library() + tap_node(find_node(n2, content_desc="Filter")) + settle("tap") + vlm_assert("structure_filter_sheet", + "Is there a bottom sheet panel anchored to the bottom edge of the " + "screen, overlaying the content above it?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("structure_more_sheet",)) +def test_more_opens_sheet(): + """More opens a compact bottom sheet with two rows (About app, Settings) + plus a drag handle / close control; BACK restores the Library shape.""" + nodes = _open_library() + before = and_showing(nodes) + if not tap_node(find_node(nodes, content_desc="More")): + record("structure_more_sheet", False, + "setup_failed: More action not tappable", + depth=0, jump_kind="transition", + expect="More-sheet appears (About app + Settings), restored on back") + return + settle("tap") + after = ui() + opened = (surface_changed(before, and_showing(after)) + and find_node_ci(after, "About app") is not None + and find_node_ci(after, "Settings") is not None) + back() + settle("tap") + end = ui() + restored = (find_node_ci(end, "About app") is None + and _restored(before, and_showing(end))) + ok = opened and restored + record("structure_more_sheet", ok, + "" if ok else "behavior_wrong: More sheet did not open/restore as " + "observed", + depth=0, jump_kind="transition", + expect="More-sheet appears (About app + Settings), restored on back") + + +@and_test(expects=("structure_filter_tab_swap",)) +def test_filter_tab_swaps_option_class(): + """Inside the Filter sheet, switching the Sort tab to the Display tab swaps + one whole class of options for another: the sort options (Alphabetically / + Author / Last read / Progress) disappear and the display options (Display + mode / Grid / List / Title position) appear. In-place shape delta.""" + nodes = _open_library() + if not tap_node(find_node(nodes, content_desc="Filter")): + record("structure_filter_tab_swap", False, + "setup_failed: Filter action not tappable", + depth=0, jump_kind="transition", + expect="Sort tab -> Display tab swaps sort options for display options") + return + settle("tap") + sort_nodes = ui() + sort_keys = and_showing(sort_nodes) + had_sort = find_node(sort_nodes, text="Alphabetically") is not None + disp_tab = find_node(sort_nodes, text="Display") + if not disp_tab or not tap_node(disp_tab): + record("structure_filter_tab_swap", False, + "setup_failed: Display tab not tappable inside Filter sheet", + depth=0, jump_kind="transition", + expect="Sort tab -> Display tab swaps sort options for display options") + return + settle("tap") + disp_nodes = ui() + gained_display = (find_node(disp_nodes, text="Display mode") is not None + and find_node(disp_nodes, text="Title position") is not None) + lost_sort = find_node(disp_nodes, text="Alphabetically") is None + swapped = surface_changed(sort_keys, and_showing(disp_nodes), min_delta=4) + ok = had_sort and gained_display and lost_sort and swapped + record("structure_filter_tab_swap", ok, + "" if ok else f"behavior_wrong: Sort/Display tab swap not as observed " + f"(had_sort={had_sort} gained_display={gained_display} " + f"lost_sort={lost_sort})", + depth=0, jump_kind="transition", + expect="Sort tab -> Display tab swaps sort options for display options") + + +@and_test(expects=("structure_selection_mode", "structure_selection_mode_vlm")) +def test_longpress_enters_selection_shape(): + """Long-pressing a cover switches the top bar into selection mode: a + '1 selected' title and a new action cluster (Select all / Move / Delete / + Clear) appear. BACK restores the Library shape (never tap Delete/Clear).""" + nodes = _open_library() + covers = _covers(nodes) + if not covers: + record("structure_selection_mode", False, + "setup_failed: no book cover present (import missing)", + depth=0, jump_kind="transition", + expect="long-press -> '1 selected' + selection actions, restored on back") + vlm_assert("structure_selection_mode", + "Does the top bar show a selection count (like '1 selected') " + "with several action icons to its right?", + RESULTS_DIR, tag="position") + return + before = and_showing(nodes) + long_press(covers[0]) + settle("tap") + mid = ui() + entered = (find_node(mid, text="1 selected") is not None + and find_node(mid, content_desc="Select all books") is not None + and surface_changed(before, and_showing(mid))) + # Reverse via BACK — 'Clear selected items' is a DANGEROUS_TEXT. + back() + settle("tap") + end = ui() + restored = (find_node(end, text="1 selected") is None + and _restored(before, and_showing(end))) + ok = entered and restored + record("structure_selection_mode", ok, + "" if ok else "behavior_wrong: selection-mode shape not as observed", + depth=0, jump_kind="transition", + expect="long-press -> '1 selected' + selection actions, restored on back") + # Re-enter for the VLM screenshot. + n2 = _open_library() + cv = _covers(n2) + if cv: + long_press(cv[0]) + settle("tap") + vlm_assert("structure_selection_mode", + "Does the top bar show a selection count (like '1 selected') with " + "several action icons to its right?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("structure_tab_history",)) +def test_tab_history_changes_surface(): + """Switching to the History tab replaces the Library grid surface with the + History surface (a 'Today' date group + per-row 'Delete history element').""" + nodes = _open_library() + before = and_showing(nodes) + covers_before = len(_covers(nodes)) + tab = bf._tab(nodes, "History") + if not tab or not tap_node(tab): + record("structure_tab_history", False, + "setup_failed: History tab not tappable", + depth=0, jump_kind="transition", + expect="Library grid -> History surface (Today group), Library covers gone") + return + settle("tap") + after = ui() + a = and_showing(after) + # History surface: a 'Today' date header / history-row control appears AND + # the Library covers vanish. + got_history = (find_node(after, text="Today") is not None + or find_node(after, content_desc="Delete history element") is not None + or find_node(after, content_desc="Delete whole history") is not None) + covers_gone = len(_covers(after)) < covers_before or covers_before == 0 + ok = got_history and surface_changed(before, a) and covers_gone + record("structure_tab_history", ok, + "" if ok else f"behavior_wrong: History surface not as observed " + f"(got_history={got_history} covers_gone={covers_gone})", + depth=0, jump_kind="transition", + expect="Library grid -> History surface (Today group), Library covers gone") + + +@and_test(expects=("structure_tab_browse",)) +def test_tab_browse_changes_surface(): + """Switching to the Browse tab replaces the Library surface with the Browse + surface (the scan CTA / empty-state, or a scanned file list). In every case + the Library covers are gone and the surface changed materially.""" + nodes = _open_library() + before = and_showing(nodes) + covers_before = len(_covers(nodes)) + tab = bf._tab(nodes, "Browse") + if not tab or not tap_node(tab): + record("structure_tab_browse", False, + "setup_failed: Browse tab not tappable", + depth=0, jump_kind="transition", + expect="Library grid -> Browse surface, covers gone") + return + settle("tap") + time.sleep(1) + after = ui() + is_browse = (find_node_ci(after, "Set up scanning") is not None + or find_node(after, text=bf.BOOK1_FILE) is not None + or find_node_ci(after, "Expand the library's book collection with " + "your downloads") is not None) + covers_gone = len(_covers(after)) < covers_before or covers_before == 0 + ok = is_browse and surface_changed(before, and_showing(after)) and covers_gone + record("structure_tab_browse", ok, + "" if ok else "behavior_wrong: Browse surface not as observed", + depth=0, jump_kind="transition", + expect="Library grid -> Browse surface, covers gone") + + +@and_test(expects=("structure_search_empty",)) +def test_search_query_empties_list(): + """A no-match query collapses the populated grid to empty: typing 'zzz' in + the search field drops the cover count from >0 to 0; clearing (Exit search) + restores the covers. Empty<->populated is a tree-SHAPE delta.""" + nodes = _open_library() + covers_before = len(_covers(nodes)) + if covers_before == 0: + record("structure_search_empty", False, + "setup_failed: no books present to filter (import missing)", + depth=0, jump_kind="transition", + expect="search 'zzz' -> 0 covers, restored on exit search") + return + if not tap_node(find_node(nodes, content_desc="Search")): + record("structure_search_empty", False, + "setup_failed: Search action not tappable", + depth=0, jump_kind="transition", + expect="search 'zzz' -> 0 covers, restored on exit search") + return + settle("tap") + ets = find_by_class(ui(), "EditText") + if not ets: + record("structure_search_empty", False, + "setup_failed: search field not present after tapping Search", + depth=0, jump_kind="transition", + expect="search 'zzz' -> 0 covers, restored on exit search") + return + type_text(ets[0], "zzz") + settle("text") + time.sleep(1) + covers_empty = len(_covers(ui())) + # Reverse: exit search restores the full grid. + ex = find_node(ui(), content_desc="Exit search") + if ex: + tap_node(ex) + settle("tap") + time.sleep(0.5) + covers_restored = len(_covers(ui())) + ok = (covers_empty == 0) and (covers_restored >= covers_before) + record("structure_search_empty", ok, + "" if ok else f"behavior_wrong: list did not empty/restore " + f"(before={covers_before} empty={covers_empty} " + f"restored={covers_restored})", + depth=0, jump_kind="transition", + expect="search 'zzz' -> 0 covers, restored on exit search") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (3) DEPTH>=1 SHAPE DELTAS — backed by a real navigation call (and_enter*) +# ══════════════════════════════════════════════════════════════════════════════ + +def and_enter_bookinfo(): + """Open a book's Book Info by tapping its cover. Backs a depth>=1 claim. + Returns (ok, nodes_after).""" + nodes = _open_library() + covers = _covers(nodes) + if not covers: + return False, nodes + before = and_showing(nodes) + if not tap_node(covers[0]): + return False, nodes + settle("launch") + time.sleep(1) + after = ui() + if surface_changed(before, and_showing(after)): + and_enter("book_info") + return True, after + return False, after + + +@and_test(expects=("structure_bookinfo_shape", "structure_bookinfo_shape_vlm")) +def test_bookinfo_shape(): + """Tapping a cover opens the Book Info surface (depth 1): Start / Move / + Delete buttons, an Author row, 'No description.', plus a 'Go back' and + 'File details' top-bar host. New class of widgets vs the Library grid.""" + ok_nav, nodes = and_enter_bookinfo() + if not ok_nav: + record("structure_bookinfo_shape", False, + "setup_failed: could not open Book Info (import missing?)", + depth=1, jump_kind="transition", + expect="cover tap -> Book Info (Start/Move/Delete/Author), depth 1") + vlm_assert("structure_bookinfo_shape", + "Is there a large primary action button spanning most of the " + "screen width near the bottom of this detail screen?", + RESULTS_DIR, depth=1, tag="size") + return + have = { + "Start": find_node_ci(nodes, "Start") is not None, + "Move": find_node(nodes, text="Move") is not None, + "Delete": find_node(nodes, text="Delete") is not None, + "Author": find_node_ci(nodes, "Author") is not None, + "desc": find_node(nodes, text="No description.") is not None, + "back": find_node(nodes, content_desc="Go back") is not None, + } + ok = all(have.values()) + record("structure_bookinfo_shape", ok, + "" if ok else f"behavior_wrong: Book Info shape not as observed {have}", + depth=1, jump_kind="transition", + expect="cover tap -> Book Info (Start/Move/Delete/Author), depth 1") + vlm_assert("structure_bookinfo_shape", + "Is there a large primary action button spanning most of the screen " + "width near the bottom of this book-detail screen?", + RESULTS_DIR, depth=1, tag="size") + + +def and_enter_settings(): + """Library -> More -> Settings. Backs a depth>=1 claim. Returns (ok, nodes).""" + nodes = _open_library() + if not tap_node(find_node(nodes, content_desc="More")): + return False, nodes + settle("tap") + mid = ui() + st = find_node_ci(mid, "Settings") + if not st or not tap_node(st): + return False, mid + settle("launch") + time.sleep(0.5) + after = ui() + if find_node_ci(after, "Appearance") is not None: + and_enter("settings_root") + return True, after + return False, after + + +@and_test(expects=("structure_settings_root",)) +def test_settings_root_shape(): + """More -> Settings opens the Settings root (depth 1): a vertical list of the + five category rows (General / Appearance / Reader / Library / Browse) with a + 'Go back' top bar. A distinct surface from any sheet.""" + ok_nav, nodes = and_enter_settings() + if not ok_nav: + record("structure_settings_root", False, + "setup_failed: could not open Settings root", + depth=1, jump_kind="transition", + expect="More->Settings -> 5 category rows, depth 1") + return + rows = [find_node_ci(nodes, lbl) is not None + for lbl in ("General", "Appearance", "Reader", "Library", "Browse")] + back_ok = find_node(nodes, content_desc="Go back") is not None + ok = all(rows) and back_ok + record("structure_settings_root", ok, + "" if ok else f"behavior_wrong: Settings root shape not as observed " + f"(rows={rows} back={back_ok})", + depth=1, jump_kind="transition", + expect="More->Settings -> 5 category rows, depth 1") + + +def and_reach_appearance(): + """Library -> More -> Settings -> Appearance. Two surfaces deep -> depth 2.""" + ok, _ = and_enter_settings() + if not ok: + return False, ui() + appr = find_node_ci(ui(), "Appearance") + if not appr or not tap_node(appr): + return False, ui() + settle("launch") + time.sleep(0.5) + after = ui() + if find_node_ci(after, "Dark theme") is not None: + and_enter("appearance") + return True, after + return False, after + + +@and_test(expects=("structure_appearance_puredark", "structure_appearance_dark_vlm")) +def test_appearance_dark_adds_puredark(): + """A mode switch that adds a class of widget (depth 2): on Appearance, the + Dark-theme segmented is System/Disabled/Enabled and there is NO 'Pure dark' + row. Selecting 'Enabled' adds a whole new 'Pure dark' (Disabled/Enabled/ + Saver) segmented block; selecting 'System' again REMOVES it (restores).""" + ok_nav, nodes = and_reach_appearance() + if not ok_nav: + record("structure_appearance_puredark", False, + "setup_failed: could not reach Appearance settings", + depth=2, jump_kind="transition", + expect="Enabled adds 'Pure dark' block, removed again on System (depth 2)") + vlm_assert("structure_appearance_dark", + "Is the overall background of this screen dark (near-black or " + "very dark grey) rather than white?", + RESULTS_DIR, depth=2, tag="color") + return + pure_before = find_node_ci(nodes, "Pure dark") is not None + en = find_node(nodes, text="Enabled") + added = False + if en and tap_node(en): + settle("tap") + time.sleep(1) + added = find_node_ci(ui(), "Pure dark") is not None + # Capture the dark VLM shot while the app is dark. + vlm_assert("structure_appearance_dark", + "Is the overall background of this screen dark (near-black or very " + "dark grey) rather than white?", + RESULTS_DIR, depth=2, tag="color") + # Reverse: back to System removes the Pure dark block (leave app light). + removed = False + sysbtn = find_node(ui(), text="System") + if sysbtn and tap_node(sysbtn): + settle("tap") + time.sleep(1) + removed = find_node_ci(ui(), "Pure dark") is None + ok = (not pure_before) and added and removed + record("structure_appearance_puredark", ok, + "" if ok else f"behavior_wrong: Pure-dark block delta not as observed " + f"(before={pure_before} added={added} removed={removed})", + depth=2, jump_kind="transition", + expect="Enabled adds 'Pure dark' block, removed again on System (depth 2)") + + +@and_test(expects=("structure_reader_open", "structure_reader_open_vlm")) +def test_reader_open_shape(): + """Opening the reader (depth 2) is the deepest shape delta: the immersive + Reader surface renders the book body as dump-readable text — a 'Chapter One' + heading and a long paragraph node — which no other surface has.""" + ok = bf.open_reader(BOOK) # imports if needed, dismisses the cling + if ok: + and_enter("book_info") + and_enter("reader") + nodes = ui() + has_heading = find_node(nodes, text="Chapter One") is not None + long_body = [n for n in nodes if len(n.get("text", "")) > 40] + rendered = has_heading and len(long_body) > 0 + verdict = bool(ok and rendered) + record("structure_reader_open", verdict, + "" if verdict else "feature_missing: reader did not render book text " + "(no 'Chapter One' heading / body paragraph)", + depth=2, jump_kind="transition", + expect="reader renders 'Chapter One' heading + body paragraph, depth 2") + vlm_assert("structure_reader_open", + "Does a block of body text (multiple lines of a paragraph) fill " + "most of the screen area?", + RESULTS_DIR, depth=2, tag="size") + + +@and_test(expects=("structure_reader_settings_sheet",)) +def test_reader_settings_sheet_shape(): + """Inside the reader (depth 2), tapping the reader-settings icon adds a + bottom sheet layer with the General / Reader / Colors tab cluster (depth 3). + A new window layer over the immersive page.""" + if not bf.open_reader(BOOK): + record("structure_reader_settings_sheet", False, + "setup_failed: reader would not open", + depth=3, jump_kind="transition", + expect="reader -> Reader settings sheet (General/Reader/Colors), depth 3") + return + and_enter("book_info") + and_enter("reader") + bf.reader_show_menu() # taps center to reveal the bars + time.sleep(1) + menu = ui() + before = and_showing(menu) + rs = find_node(menu, content_desc="Reader settings") + if not rs or not tap_node(rs): + record("structure_reader_settings_sheet", False, + "setup_failed: Reader settings icon not found in reader bars", + depth=3, jump_kind="transition", + expect="reader -> Reader settings sheet (General/Reader/Colors), depth 3") + return + settle("launch") + time.sleep(1) + after = ui() + and_enter("reader_settings") + got_tabs = (find_node_ci(after, "General") is not None + and find_node_ci(after, "Colors") is not None + and find_node_ci(after, "Reading mode") is not None) + ok = got_tabs and surface_changed(before, and_showing(after)) + record("structure_reader_settings_sheet", ok, + "" if ok else "behavior_wrong: Reader settings sheet not as observed", + depth=3, jump_kind="transition", + expect="reader -> Reader settings sheet (General/Reader/Colors), depth 3") + + +@and_test(expects=("structure_chapters_drawer",)) +def test_chapters_drawer_shape(): + """Inside the reader (depth 2), tapping the Chapters icon opens a chapter + list layer (depth 3) whose 'Chapter One' entry appears — a distinct surface + from the reading page.""" + if not bf.open_reader(BOOK): + record("structure_chapters_drawer", False, + "setup_failed: reader would not open", + depth=3, jump_kind="transition", + expect="reader -> Chapters drawer (chapter list), depth 3") + return + and_enter("book_info") + and_enter("reader") + bf.reader_show_menu() + time.sleep(1) + menu = ui() + before = and_showing(menu) + ch = find_node(menu, content_desc="Chapters") + if not ch or not tap_node(ch): + record("structure_chapters_drawer", False, + "setup_failed: Chapters icon not found in reader bars", + depth=3, jump_kind="transition", + expect="reader -> Chapters drawer (chapter list), depth 3") + return + settle("launch") + time.sleep(1) + after = ui() + and_enter("chapters") + got_drawer = find_node(after, text="Chapter One") is not None + ok = got_drawer and surface_changed(before, and_showing(after)) + record("structure_chapters_drawer", ok, + "" if ok else "behavior_wrong: Chapters drawer not as observed", + depth=3, jump_kind="transition", + expect="reader -> Chapters drawer (chapter list), depth 3") + + +# ── VLM #8 (library grid layout) ────────────────────────────────────────────── + +@and_test(expects=("structure_library_grid_vlm",)) +def test_library_grid_vlm(): + """VLM-only: the populated Library shows the two book covers side by side in + a grid row. Exact rendered SHAPE the dump cannot fully express.""" + nodes = _open_library() + covers = _covers(nodes) + if len(covers) < 2: + # Try to ensure the second book is present, then re-open. + bf.import_book(bf.BOOK2_TITLE, bf.BOOK2_FILE) + _open_library() + vlm_assert("structure_library_grid", + "Are there two book cover cards displayed side by side in the same " + "row (a grid layout), rather than stacked vertically?", + RESULTS_DIR, tag="shape") + + +# ══════════════════════════════════════════════════════════════════════════════ + +TESTS = [ + # GATE (jump_kind="none") + test_gate_launch, + test_gate_topbar, + test_gate_bottomnav, + # in-place shape deltas (depth 0) + test_search_adds_editable_field, + test_filter_opens_sheet, + test_more_opens_sheet, + test_filter_tab_swaps_option_class, + test_longpress_enters_selection_shape, + test_tab_history_changes_surface, + test_tab_browse_changes_surface, + test_search_query_empties_list, + # depth>=1 shape deltas (backed by and_enter*/and_reach*) + test_bookinfo_shape, + test_settings_root_shape, + test_appearance_dark_adds_puredark, + test_reader_open_shape, + test_reader_settings_sheet_shape, + test_chapters_drawer_shape, + # VLM-only grid layout + test_library_grid_vlm, +] + +if __name__ == "__main__": + run_suite(TESTS, "structure") diff --git a/android/acclorite-book-story/tests/test_android_text.py b/android/acclorite-book-story/tests/test_android_text.py new file mode 100644 index 0000000000000000000000000000000000000000..e45c0673220bbb69aca2c4de1e71fe36704c1e40 --- /dev/null +++ b/android/acclorite-book-story/tests/test_android_text.py @@ -0,0 +1,745 @@ +#!/usr/bin/env python3 +"""TEXT module — CONTENT / OUTPUT strings an interaction PRODUCES for Book's Story. + +Lane: SOLE OWNER of exact-string equality. Every case is TRIGGER -> OBSERVATION: +drive the user path, read the produced string out of a FRESH ui(), and assert the +words match what the ORIGINAL app rendered. The discriminating half is the CHANGE: +each string is asserted ABSENT on the Library at launch and PRESENT only after the +trigger, so a dead shell that renders nothing (or renders a hardcoded label at +launch) FAILS instead of passing. + +GROUND TRUTH — every string below was OBSERVED on the running original with +scratch dumps before it was hardcoded here (see the recon report + explore runs): + + Library (depth 0), empty state after clear_data: + * subtitle TextView "Read your favorite books and sort them between categories" + * CTA TextView "Add a book" + * top-bar title "Library" + Library ▸ Search icon (content-desc "Search") -> in-place search field whose + placeholder is a TextView "Search…" (real ellipsis U+2026, not "..."), + plus a content-desc "Exit search". Absent until Search is tapped. + Library ▸ Filter icon -> bottom sheet, tabs "Sort"/"Display", sort options + "Alphabetically"/"Last read"/"Progress"/"Author". + Library ▸ More icon -> bottom sheet items "About app" and "Settings". + Book Info (depth 1, tap a cover): title "testbook", Author label (content-desc + "Author" on an icon) with value "Unknown", "0%", "No description.", "Start". + Settings root (depth 1, More ▸ Settings): rows General "App language", + Appearance "Theme, colors", Reader "Font, text", Library + "Categories, display, tabs", Browse "Scan, display"; title "Settings". + About app (depth 2, More ▸ About app): rows "Report a bug", "Contributors", + "Open source licenses", "Credits", "Help translate", "Support development"; + title "About app". (The version string "Book's Story v1.8.0" is an upstream + constant and is NEVER asserted.) + Reader (depth 2, open a book): heading "Chapter One" + first paragraph starting + "The quick brown fox jumps over the lazy dog." rendered in the view tree. + Tap center -> top bar shows book title "testbook" and chapter "Chapter One". + Browse tab (granted): folder-path header "/storage/emulated/0/Download/Books". + History tab (after a book has been opened): date-group header "Today" + + book title "testbook". (The per-row timestamp is a clock value -> NOT asserted.) + +Depth is backed by real navigation: file-local and_reach_* helpers each take a +before/after surface snapshot and prove the TARGET element appeared (and_reach), +counting the surface via and_enter. VLM BUDGET FOR THIS FILE: 0 — every string +here is dump-readable from the view tree, so there are no vlm_assert calls. +""" +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 +import book_fixture as bf # shared, validated import helper + +BOOK1 = bf.BOOK1_TITLE # "testbook" +BOOK2 = bf.BOOK2_TITLE # "alpha_wonderland" + +# Exact strings OBSERVED on the original (see module docstring). +SEARCH_HINT = "Search…" # real ellipsis, not "..." +EMPTY_SUBTITLE = "Read your favorite books and sort them between categories" +EMPTY_CTA = "Add a book" +NO_DESCRIPTION = "No description." +FOLDER_PATH = "/storage/emulated/0/Download/Books" +FIRST_SENTENCE = "The quick brown fox jumps over the lazy dog." + +TESTS = [] + + +def _t(fn): + TESTS.append(fn) + return fn + + +# ── local helpers ──────────────────────────────────────────────────────────── +def all_text(nodes): + """Every visible text string in the tree, joined — for substring probes.""" + return " | ".join(n.get("text", "") for n in nodes if n.get("text")) + + +def all_desc(nodes): + """Every content-desc in the tree, joined — labels ride on content-desc for + Compose icons (e.g. the Book Info "Author" label).""" + return " | ".join(n.get("content-desc", "") for n in nodes if n.get("content-desc")) + + +def has_text(nodes, s): + """Case-sensitive substring across text, then case-insensitive exact via the + kit — a faithful recreation may differ in casing but not in the words.""" + return (s in all_text(nodes)) or (find_node_ci(nodes, s) is not None) + + +def _open_library(): + """Land on the Library tab from a fresh launch.""" + restart_app() + wait_for_foreground() + bf._open_tab("Library") + time.sleep(0.5) + + +def and_reach_sheet(content_desc, target): + """Tap a Library top-bar icon (Filter/More) and PROVE its bottom sheet + surfaced by `target` appearing. Counts one surface. Returns (ok, note).""" + nodes = ui() + trig = find_node(nodes, content_desc=content_desc) + if not trig: + return False, f"setup_failed: '{content_desc}' icon not on the Library top bar" + before = and_showing(nodes) + if not tap_node(trig): + return False, f"setup_failed: '{content_desc}' icon not tappable" + settle("tap") + time.sleep(0.8) + after = and_showing() + if not (and_reach(before, after, target) or surface_changed(before, after)): + return False, f"behavior_wrong: no sheet opened after tapping '{content_desc}'" + and_enter(content_desc) + return True, "" + + +def and_reach_settings_root(): + """Library ▸ More ▸ Settings. Crosses one surface (the Settings root screen). + Returns (ok, note).""" + ok, note = and_reach_sheet("More", "Settings") + if not ok: + return False, note + sett = find_node(ui(), text="Settings") + if not sett: + return False, "setup_failed: 'Settings' item missing from the More sheet" + before = and_showing() + tap_node(sett) + settle("launch") + time.sleep(0.8) + after = and_showing() + if not and_reach(before, after, "App language"): + return False, "behavior_wrong: Settings root did not open (no category rows)" + and_enter("Settings") + return True, "" + + +def and_reach_about(): + """Library ▸ More ▸ About app. Crosses one surface (the About screen). + Returns (ok, note).""" + ok, note = and_reach_sheet("More", "About app") + if not ok: + return False, note + ab = find_node(ui(), text="About app") + if not ab: + return False, "setup_failed: 'About app' item missing from the More sheet" + before = and_showing() + tap_node(ab) + settle("launch") + time.sleep(0.8) + after = and_showing() + if not and_reach(before, after, "Report a bug"): + return False, "behavior_wrong: About screen did not open" + and_enter("About app") + return True, "" + + +def and_reach_book_info(title): + """Library -> Book Info by tapping the cover, PROVING the jump (the 'No + description.' / 'Start' surface appeared and the Library tab bar vanished). + Crosses one surface. Returns (ok, note).""" + before = and_showing() + if not bf.open_book_info(title): + return False, "setup_failed: Book Info did not open" + after = and_showing() + # Book Info is proven by its unique controls appearing (Start/Move) while the + # Library's bottom-nav 'Browse' tab disappears. + if not (and_reach(before, after, "Start", source="Browse") + or and_reach(before, after, "Move")): + return False, "behavior_wrong: Book Info surface did not appear" + and_enter("Book Info") + return True, "" + + +def and_reach_reader(title): + """Library -> Book Info -> Reader, PROVING the reader rendered book text + ('Chapter One' appeared and the Book Info 'Start' button vanished). Crosses + two surfaces (Book Info, then Reader). Returns (ok, note).""" + ok, note = and_reach_book_info(title) + if not ok: + return False, note + before = and_showing() + start = find_node(ui(), text="Start") or find_node(ui(), text="Continue") + if not start: + return False, "setup_failed: no Start/Continue button on Book Info" + tap_node(start) + settle("launch") + time.sleep(2) + got = find_node(ui(), text="Got it") # one-time immersive-mode system cling + if got: + tap_node(got) + settle("tap") + time.sleep(1) + after = and_showing() + if not and_reach(before, after, "Chapter One", source="Start"): + return False, "behavior_wrong: reader did not render book text" + and_enter("Reader") + return True, "" + + +def and_reach_history_tab(): + """Switch from Library to the History tab. Counts one surface. Returns bool.""" + before = and_showing() + if not bf._open_tab("History"): + return False + time.sleep(0.8) + after = and_showing() + ok = and_reach(before, after, "History") + if ok: + and_enter("History") + return ok + + +def and_reach_browse_tab(): + """Switch from Library to the Browse tab. Counts one surface. Returns bool.""" + before = and_showing() + if not bf._open_tab("Browse"): + return False + time.sleep(0.8) + after = and_showing() + ok = surface_changed(before, after) + if ok: + and_enter("Browse") + return ok + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1. Library empty-state subtitle +# ══════════════════════════════════════════════════════════════════════════════ +@_t +@and_test(expects=("text_empty_state_subtitle",)) +def test_empty_state_subtitle(): + name = "text_empty_state_subtitle" + # Wipe to a virgin library so the empty state renders (the grant/library are + # re-imported by later tests via bf.import_book). + clear_data() + restart_app() + wait_for_foreground() + time.sleep(1.5) + nodes = ui() + ok = EMPTY_SUBTITLE in all_text(nodes) + record(name, ok, + "" if ok else f"feature_missing: empty-library subtitle not found; " + f"got {all_text(nodes)[:120]!r}", + depth=0, jump_kind="none", expect=EMPTY_SUBTITLE) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2. Library empty-state CTA label "Add a book" +# ══════════════════════════════════════════════════════════════════════════════ +@_t +@and_test(expects=("text_empty_state_cta",)) +def test_empty_state_cta(): + name = "text_empty_state_cta" + clear_data() + restart_app() + wait_for_foreground() + time.sleep(1.5) + nodes = ui() + n = find_node(nodes, text=EMPTY_CTA) or find_node_ci(nodes, EMPTY_CTA) + ok = n is not None + record(name, ok, + "" if ok else "feature_missing: 'Add a book' CTA not on the empty library", + depth=0, jump_kind="none", expect=EMPTY_CTA) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3. Search field placeholder "Search…" (produced by tapping Search) +# ══════════════════════════════════════════════════════════════════════════════ +@_t +@and_test(expects=("text_search_hint",)) +def test_search_hint(): + name = "text_search_hint" + _open_library() + absent = SEARCH_HINT not in all_text(ui()) + trig = find_node(ui(), content_desc="Search") + if not trig: + record(name, False, + "setup_failed: Search icon not on the Library top bar", + depth=0, jump_kind="value", expect=f"placeholder {SEARCH_HINT!r}") + return + tap_node(trig) + settle("tap") + time.sleep(0.8) + present = SEARCH_HINT in all_text(ui()) + ok = absent and present + record(name, ok, + "" if ok else "behavior_wrong: search placeholder 'Search…' did not " + "appear after tapping Search", + depth=0, jump_kind="value", expect=f"search field placeholder reads {SEARCH_HINT!r}") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4. Filter sheet tab labels "Sort" / "Display" +# ══════════════════════════════════════════════════════════════════════════════ +@_t +@and_test(expects=("text_filter_tabs",)) +def test_filter_tabs(): + name = "text_filter_tabs" + _open_library() + absent = not has_text(ui(), "Display") + ok_open, note = and_reach_sheet("Filter", "Sort") + if not ok_open: + record(name, False, note, depth=1, jump_kind="reach", + expect="Filter sheet tabs 'Sort' and 'Display'") + return + nodes = ui() + got_sort = has_text(nodes, "Sort") + got_display = has_text(nodes, "Display") + ok = absent and got_sort and got_display + record(name, ok, + "" if ok else f"behavior_wrong: Filter sheet tabs missing " + f"(Sort={got_sort} Display={got_display})", + depth=1, jump_kind="reach", expect="Filter sheet tabs 'Sort' and 'Display'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5. Filter sheet sort-option labels (Alphabetically / Last read / Progress / Author) +# ══════════════════════════════════════════════════════════════════════════════ +@_t +@and_test(expects=("text_filter_sort_options",)) +def test_filter_sort_options(): + name = "text_filter_sort_options" + _open_library() + absent = not has_text(ui(), "Alphabetically") + ok_open, note = and_reach_sheet("Filter", "Sort") + if not ok_open: + record(name, False, note, depth=1, jump_kind="reach", + expect="sort options Alphabetically/Last read/Progress/Author") + return + nodes = ui() + want = ["Alphabetically", "Last read", "Progress", "Author"] + missing = [w for w in want if not has_text(nodes, w)] + ok = absent and not missing + record(name, ok, + "" if ok else f"behavior_wrong: missing sort options {missing}", + depth=1, jump_kind="reach", + expect="sort options 'Alphabetically', 'Last read', 'Progress', 'Author'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 6. More sheet items "About app" and "Settings" +# ══════════════════════════════════════════════════════════════════════════════ +@_t +@and_test(expects=("text_more_sheet_items",)) +def test_more_sheet_items(): + name = "text_more_sheet_items" + _open_library() + absent = not (has_text(ui(), "About app") and has_text(ui(), "Settings")) + ok_open, note = and_reach_sheet("More", "About app") + if not ok_open: + record(name, False, note, depth=1, jump_kind="reach", + expect="More sheet items 'About app' and 'Settings'") + return + nodes = ui() + got_about = has_text(nodes, "About app") + got_settings = has_text(nodes, "Settings") + ok = absent and got_about and got_settings + record(name, ok, + "" if ok else f"behavior_wrong: More sheet items missing " + f"(About app={got_about} Settings={got_settings})", + depth=1, jump_kind="reach", expect="More sheet items 'About app' and 'Settings'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 7. Book Info — "No description." (produced on the Book Info surface) +# ══════════════════════════════════════════════════════════════════════════════ +@_t +@and_test(expects=("text_bookinfo_no_description",)) +def test_bookinfo_no_description(): + name = "text_bookinfo_no_description" + ok_imp, imp_note = bf.import_book(BOOK1, bf.BOOK1_FILE) + if not ok_imp: + record(name, False, f"setup_failed: could not import {BOOK1} ({imp_note})", + depth=1, jump_kind="reach", expect=NO_DESCRIPTION) + return + _open_library() + absent = NO_DESCRIPTION not in all_text(ui()) + ok_nav, note = and_reach_book_info(BOOK1) + if not ok_nav: + record(name, False, note, depth=1, jump_kind="reach", expect=NO_DESCRIPTION) + return + present = NO_DESCRIPTION in all_text(ui()) + ok = absent and present + record(name, ok, + "" if ok else "behavior_wrong: Book Info did not render 'No description.'", + depth=1, jump_kind="reach", expect=NO_DESCRIPTION) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 8. Book Info — Author label "Author" + value "Unknown" +# ══════════════════════════════════════════════════════════════════════════════ +@_t +@and_test(expects=("text_bookinfo_author",)) +def test_bookinfo_author(): + name = "text_bookinfo_author" + ok_imp, imp_note = bf.import_book(BOOK1, bf.BOOK1_FILE) + if not ok_imp: + record(name, False, f"setup_failed: could not import {BOOK1} ({imp_note})", + depth=1, jump_kind="reach", expect="Author label + value 'Unknown'") + return + _open_library() + ok_nav, note = and_reach_book_info(BOOK1) + if not ok_nav: + record(name, False, note, depth=1, jump_kind="reach", + expect="Author label + value 'Unknown'") + return + nodes = ui() + # "Author" is a content-desc on an icon; "Unknown" is the value TextView. + got_author = ("Author" in all_desc(nodes)) or has_text(nodes, "Author") + got_unknown = has_text(nodes, "Unknown") + ok = got_author and got_unknown + record(name, ok, + "" if ok else f"behavior_wrong: Author label/value wrong " + f"(Author={got_author} Unknown={got_unknown})", + depth=1, jump_kind="reach", expect="Author label present with value 'Unknown'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 9. Book Info — "Start" button label +# ══════════════════════════════════════════════════════════════════════════════ +@_t +@and_test(expects=("text_bookinfo_start_button",)) +def test_bookinfo_start_button(): + name = "text_bookinfo_start_button" + ok_imp, imp_note = bf.import_book(BOOK1, bf.BOOK1_FILE) + if not ok_imp: + record(name, False, f"setup_failed: could not import {BOOK1} ({imp_note})", + depth=1, jump_kind="reach", expect="button label 'Start'") + return + _open_library() + absent = not has_text(ui(), "Start") + ok_nav, note = and_reach_book_info(BOOK1) + if not ok_nav: + record(name, False, note, depth=1, jump_kind="reach", expect="button label 'Start'") + return + n = find_node(ui(), text="Start") or find_node_ci(ui(), "Start") + ok = absent and (n is not None) + record(name, ok, + "" if ok else "behavior_wrong: Book Info has no 'Start' button label", + depth=1, jump_kind="reach", expect="button label 'Start'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 10-13. Settings root category subtitles (four separate produced strings) +# ══════════════════════════════════════════════════════════════════════════════ +@_t +@and_test(expects=("text_settings_general_subtitle",)) +def test_settings_general_subtitle(): + name = "text_settings_general_subtitle" + _open_library() + absent = not has_text(ui(), "App language") + ok_nav, note = and_reach_settings_root() + if not ok_nav: + record(name, False, note, depth=1, jump_kind="reach", + expect="General row subtitle 'App language'") + return + ok = absent and has_text(ui(), "App language") + record(name, ok, + "" if ok else "behavior_wrong: General subtitle 'App language' not on Settings", + depth=1, jump_kind="reach", expect="General row subtitle 'App language'") + + +@_t +@and_test(expects=("text_settings_appearance_subtitle",)) +def test_settings_appearance_subtitle(): + name = "text_settings_appearance_subtitle" + _open_library() + absent = not has_text(ui(), "Theme, colors") + ok_nav, note = and_reach_settings_root() + if not ok_nav: + record(name, False, note, depth=1, jump_kind="reach", + expect="Appearance row subtitle 'Theme, colors'") + return + ok = absent and has_text(ui(), "Theme, colors") + record(name, ok, + "" if ok else "behavior_wrong: Appearance subtitle 'Theme, colors' not on Settings", + depth=1, jump_kind="reach", expect="Appearance row subtitle 'Theme, colors'") + + +@_t +@and_test(expects=("text_settings_reader_subtitle",)) +def test_settings_reader_subtitle(): + name = "text_settings_reader_subtitle" + _open_library() + absent = not has_text(ui(), "Font, text") + ok_nav, note = and_reach_settings_root() + if not ok_nav: + record(name, False, note, depth=1, jump_kind="reach", + expect="Reader row subtitle 'Font, text'") + return + ok = absent and has_text(ui(), "Font, text") + record(name, ok, + "" if ok else "behavior_wrong: Reader subtitle 'Font, text' not on Settings", + depth=1, jump_kind="reach", expect="Reader row subtitle 'Font, text'") + + +@_t +@and_test(expects=("text_settings_library_subtitle",)) +def test_settings_library_subtitle(): + name = "text_settings_library_subtitle" + _open_library() + absent = not has_text(ui(), "Categories, display, tabs") + ok_nav, note = and_reach_settings_root() + if not ok_nav: + record(name, False, note, depth=1, jump_kind="reach", + expect="Library row subtitle 'Categories, display, tabs'") + return + ok = absent and has_text(ui(), "Categories, display, tabs") + record(name, ok, + "" if ok else "behavior_wrong: Library subtitle 'Categories, display, tabs' " + "not on Settings", + depth=1, jump_kind="reach", expect="Library row subtitle 'Categories, display, tabs'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 14-16. About app row labels (three separate produced strings) +# ══════════════════════════════════════════════════════════════════════════════ +@_t +@and_test(expects=("text_about_report_bug",)) +def test_about_report_bug(): + name = "text_about_report_bug" + _open_library() + absent = not has_text(ui(), "Report a bug") + ok_nav, note = and_reach_about() + if not ok_nav: + record(name, False, note, depth=2, jump_kind="reach", + expect="About row label 'Report a bug'") + return + ok = absent and has_text(ui(), "Report a bug") + record(name, ok, + "" if ok else "behavior_wrong: 'Report a bug' row not on the About screen", + depth=2, jump_kind="reach", expect="About row label 'Report a bug'") + + +@_t +@and_test(expects=("text_about_licenses",)) +def test_about_licenses(): + name = "text_about_licenses" + _open_library() + absent = not has_text(ui(), "Open source licenses") + ok_nav, note = and_reach_about() + if not ok_nav: + record(name, False, note, depth=2, jump_kind="reach", + expect="About row label 'Open source licenses'") + return + ok = absent and has_text(ui(), "Open source licenses") + record(name, ok, + "" if ok else "behavior_wrong: 'Open source licenses' row not on the About screen", + depth=2, jump_kind="reach", expect="About row label 'Open source licenses'") + + +@_t +@and_test(expects=("text_about_support_development",)) +def test_about_support_development(): + name = "text_about_support_development" + _open_library() + absent = not has_text(ui(), "Support development") + ok_nav, note = and_reach_about() + if not ok_nav: + record(name, False, note, depth=2, jump_kind="reach", + expect="About row label 'Support development'") + return + ok = absent and has_text(ui(), "Support development") + record(name, ok, + "" if ok else "behavior_wrong: 'Support development' row not on the About screen", + depth=2, jump_kind="reach", expect="About row label 'Support development'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 17. Reader — "Chapter One" heading (produced in the Reader view tree) +# ══════════════════════════════════════════════════════════════════════════════ +@_t +@and_test(expects=("text_reader_chapter_heading",)) +def test_reader_chapter_heading(): + name = "text_reader_chapter_heading" + ok_imp, imp_note = bf.import_book(BOOK1, bf.BOOK1_FILE) + if not ok_imp: + record(name, False, f"setup_failed: could not import {BOOK1} ({imp_note})", + depth=2, jump_kind="reach", expect="reader heading 'Chapter One'") + return + _open_library() + absent = not has_text(ui(), "Chapter One") + ok_nav, note = and_reach_reader(BOOK1) + if not ok_nav: + record(name, False, note, depth=2, jump_kind="reach", + expect="reader heading 'Chapter One'") + return + present = has_text(ui(), "Chapter One") + ok = absent and present + record(name, ok, + "" if ok else "behavior_wrong: reader did not render the 'Chapter One' heading", + depth=2, jump_kind="reach", expect="reader heading 'Chapter One'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 18. Reader — first paragraph sentence (dump-readable body content) +# ══════════════════════════════════════════════════════════════════════════════ +@_t +@and_test(expects=("text_reader_first_paragraph",)) +def test_reader_first_paragraph(): + name = "text_reader_first_paragraph" + ok_imp, imp_note = bf.import_book(BOOK1, bf.BOOK1_FILE) + if not ok_imp: + record(name, False, f"setup_failed: could not import {BOOK1} ({imp_note})", + depth=2, jump_kind="value", expect=FIRST_SENTENCE) + return + _open_library() + absent = FIRST_SENTENCE not in all_text(ui()) + ok_nav, note = and_reach_reader(BOOK1) + if not ok_nav: + record(name, False, note, depth=2, jump_kind="value", expect=FIRST_SENTENCE) + return + present = FIRST_SENTENCE in all_text(ui()) + ok = absent and present + record(name, ok, + "" if ok else "behavior_wrong: reader body did not contain the first " + "paragraph sentence", + depth=2, jump_kind="value", + expect=f"reader body contains {FIRST_SENTENCE!r}") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 19. Reader top bar — book title "testbook" + chapter "Chapter One" +# ══════════════════════════════════════════════════════════════════════════════ +@_t +@and_test(expects=("text_reader_topbar_title",)) +def test_reader_topbar_title(): + name = "text_reader_topbar_title" + ok_imp, imp_note = bf.import_book(BOOK1, bf.BOOK1_FILE) + if not ok_imp: + record(name, False, f"setup_failed: could not import {BOOK1} ({imp_note})", + depth=2, jump_kind="value", + expect=f"reader top bar shows title {BOOK1!r} and 'Chapter One'") + return + _open_library() + ok_nav, note = and_reach_reader(BOOK1) + if not ok_nav: + record(name, False, note, depth=2, jump_kind="value", + expect=f"reader top bar shows title {BOOK1!r} and 'Chapter One'") + return + nodes = bf.reader_show_menu() + # The reader toolbar sits at the very top (y < 230); the book text starts + # below it. Read the title + chapter labels from the toolbar band only. + topbar = [n for n in nodes + if n.get("text") and n.get("_bounds", (0, 9999, 0, 0))[1] < 230] + top_text = " | ".join(n.get("text", "") for n in topbar) + got_title = BOOK1 in top_text or (find_node_ci(topbar, BOOK1) is not None) + got_chapter = "Chapter One" in top_text + ok = got_title and got_chapter + record(name, ok, + "" if ok else f"behavior_wrong: reader top bar missing title/chapter " + f"(title={got_title} chapter={got_chapter}); band={top_text!r}", + depth=2, jump_kind="value", + expect=f"reader top bar shows title {BOOK1!r} and chapter 'Chapter One'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 20. History — date-group header "Today" produced after reading a book +# ══════════════════════════════════════════════════════════════════════════════ +@_t +@and_test(expects=("text_history_today_group",)) +def test_history_today_group(): + name = "text_history_today_group" + ok_imp, imp_note = bf.import_book(BOOK1, bf.BOOK1_FILE) + if not ok_imp: + record(name, False, f"setup_failed: could not import {BOOK1} ({imp_note})", + depth=1, jump_kind="reach", expect="History date-group header 'Today'") + return + # Ensure a history entry exists by opening the reader once. + if not bf.open_reader(BOOK1): + record(name, False, "setup_failed: could not open the reader to seed history", + depth=1, jump_kind="reach", expect="History date-group header 'Today'") + return + _open_library() + absent = not has_text(ui(), "Today") + if not and_reach_history_tab(): + record(name, False, "setup_failed: could not switch to the History tab", + depth=1, jump_kind="reach", expect="History date-group header 'Today'") + return + present = has_text(ui(), "Today") + ok = absent and present + record(name, ok, + "" if ok else "behavior_wrong: History did not show the 'Today' date group", + depth=1, jump_kind="reach", expect="History date-group header 'Today'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 21. History — book title "testbook" listed under the history entry +# ══════════════════════════════════════════════════════════════════════════════ +@_t +@and_test(expects=("text_history_book_title",)) +def test_history_book_title(): + name = "text_history_book_title" + ok_imp, imp_note = bf.import_book(BOOK1, bf.BOOK1_FILE) + if not ok_imp: + record(name, False, f"setup_failed: could not import {BOOK1} ({imp_note})", + depth=1, jump_kind="reach", expect=f"History lists book title {BOOK1!r}") + return + if not bf.open_reader(BOOK1): + record(name, False, "setup_failed: could not open the reader to seed history", + depth=1, jump_kind="reach", expect=f"History lists book title {BOOK1!r}") + return + _open_library() + if not and_reach_history_tab(): + record(name, False, "setup_failed: could not switch to the History tab", + depth=1, jump_kind="reach", expect=f"History lists book title {BOOK1!r}") + return + nodes = ui() + # The title must appear alongside the "Today" group (i.e. as a history row). + ok = has_text(nodes, "Today") and (find_node(nodes, text=BOOK1) is not None) + record(name, ok, + "" if ok else f"behavior_wrong: History did not list the book title {BOOK1!r}", + depth=1, jump_kind="reach", expect=f"History lists book title {BOOK1!r}") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 22. Browse — granted folder-path header +# ══════════════════════════════════════════════════════════════════════════════ +@_t +@and_test(expects=("text_browse_folder_path",)) +def test_browse_folder_path(): + name = "text_browse_folder_path" + ok_imp, imp_note = bf.import_book(BOOK1, bf.BOOK1_FILE) + if not ok_imp: + record(name, False, f"setup_failed: could not import {BOOK1} ({imp_note})", + depth=1, jump_kind="reach", expect=FOLDER_PATH) + return + _open_library() + absent = FOLDER_PATH not in all_text(ui()) + if not and_reach_browse_tab(): + record(name, False, "setup_failed: could not switch to the Browse tab", + depth=1, jump_kind="reach", expect=FOLDER_PATH) + return + present = FOLDER_PATH in all_text(ui()) + ok = absent and present + record(name, ok, + "" if ok else f"behavior_wrong: Browse did not show the folder path {FOLDER_PATH!r}", + depth=1, jump_kind="reach", expect=FOLDER_PATH) + + +if __name__ == "__main__": + if not device_online(): + print("Device offline — aborting.") + sys.exit(2) + run_suite(TESTS, "text") diff --git a/android/acclorite-book-story/tests/test_manifest.json b/android/acclorite-book-story/tests/test_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..566bc18a18323c6b2989035d26a8365523b6138e --- /dev/null +++ b/android/acclorite-book-story/tests/test_manifest.json @@ -0,0 +1,887 @@ +{ + "manifest_version": 1, + "kit_api_version": 1, + "task_id": "book-story", + "baseline_model": "claude-opus-4-8", + "baseline_package": "", + "total": 138, + "manifest_sha": "eab8271e17ca", + "tests": [ + { + "name": "computation::computation_bg_color_red", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_bg_swatch_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_book_info_progress", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_font_color_red", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_font_size_label", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_font_swatch_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_letter_spacing_label", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_library_count_badge", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_reader_progress", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_alpha", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_book", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_clear_restores", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_count_badge", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_no_match", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_testbook", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_wonderland", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_size_percent_label", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_swatches_differ_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_book_info_actions_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_book_survives_process_death", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_book_survives_process_death_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_clear_selection_exits", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_history_entry_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_history_survives_process_death", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_library_two_cards_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_longpress_enters_selection", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_longpress_selection_actions", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_longpress_selection_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_move_sheet_opens", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_multi_record_integrity", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_multi_record_survives_death", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_open_reader_shows_text", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_reader_page_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_reading_creates_history", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_second_book_survives_process_death", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_credits_to_about", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_exit_search", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_info_to_library", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_reader_to_info", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_settings_to_library", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_tab_history", + "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_appearance", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_book_info", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_book_info_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_browse", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_browse_settings", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_chapters_drawer", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_credits", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_general", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_history", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_history_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_library_from_browse", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_library_settings", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_licenses", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_more_sheet", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_more_sheet_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_reader", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_reader_settings_screen", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_reader_settings_sheet", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_reader_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_search", + "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": "states::states_app_theme_ring_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_app_theme_select", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_app_theme_select_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_chapter_title_align", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_theme_enable", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_theme_enable_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_theme_highlight_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_theme_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_theme_persists_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_display_highlight_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_display_mode_list", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_display_mode_list_grid_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_display_mode_list_list_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_display_mode_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_display_mode_persists_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_font_style_italic", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_font_style_italic_highlight_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_nav_labels_hide", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_nav_labels_hide_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_nav_labels_persist", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_progress_count_change", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_progress_count_change_highlight_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_search_focus", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_text_align_highlight_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_text_alignment_change", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_title_position_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "structure::structure_appearance_dark_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_appearance_puredark", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_bookinfo_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_bookinfo_shape_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_chapters_drawer", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_filter_sheet", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_filter_sheet_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_filter_tab_swap", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_bottomnav", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_bottomnav_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_launch", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_topbar", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_topbar_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_library_grid_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_more_sheet", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_reader_open", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_reader_open_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_reader_settings_sheet", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_search_empty", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_search_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_selection_mode", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_selection_mode_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_root", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_tab_browse", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_tab_history", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "text::text_about_licenses", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_about_report_bug", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_about_support_development", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_bookinfo_author", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_bookinfo_no_description", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_bookinfo_start_button", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_browse_folder_path", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_empty_state_cta", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_empty_state_subtitle", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_filter_sort_options", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_filter_tabs", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_history_book_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_history_today_group", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_more_sheet_items", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_reader_chapter_heading", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_reader_first_paragraph", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_reader_topbar_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_search_hint", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_appearance_subtitle", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_general_subtitle", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_library_subtitle", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_reader_subtitle", + "module": "text", + "baseline_status": "passed" + } + ], + "ignored": [], + "vlm_assertions": [ + { + "name": "computation::computation_bg_swatch_vlm", + "module": "computation", + "tag": "color" + }, + { + "name": "computation::computation_font_swatch_vlm", + "module": "computation", + "tag": "color" + }, + { + "name": "computation::computation_swatches_differ_vlm", + "module": "computation", + "tag": "color" + }, + { + "name": "interaction::interaction_book_survives_process_death_vlm", + "module": "interaction", + "tag": "layout" + }, + { + "name": "interaction::interaction_longpress_selection_vlm", + "module": "interaction", + "tag": "shape" + }, + { + "name": "interaction::interaction_history_entry_vlm", + "module": "interaction", + "tag": "layout" + }, + { + "name": "interaction::interaction_library_two_cards_vlm", + "module": "interaction", + "tag": "layout" + }, + { + "name": "interaction::interaction_reader_page_vlm", + "module": "interaction", + "tag": "layout" + }, + { + "name": "interaction::interaction_book_info_actions_vlm", + "module": "interaction", + "tag": "layout" + }, + { + "name": "navigation::nav_reach_history_vlm", + "module": "navigation", + "tag": "layout" + }, + { + "name": "navigation::nav_reach_more_sheet_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_reach_settings_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_reach_book_info_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_reach_reader_vlm", + "module": "navigation", + "tag": "layout" + }, + { + "name": "navigation::nav_reach_about_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "states::states_dark_theme_enable_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_dark_theme_persists_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_dark_theme_highlight_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_app_theme_select_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_app_theme_ring_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_nav_labels_hide_vlm", + "module": "states", + "tag": "position" + }, + { + "name": "states::states_display_mode_list_grid_vlm", + "module": "states", + "tag": "layout" + }, + { + "name": "states::states_display_mode_list_list_vlm", + "module": "states", + "tag": "layout" + }, + { + "name": "states::states_display_mode_persists_vlm", + "module": "states", + "tag": "layout" + }, + { + "name": "states::states_display_highlight_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_font_style_italic_highlight_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_progress_count_change_highlight_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_text_align_highlight_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "structure::structure_gate_topbar_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_gate_bottomnav_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_filter_sheet_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_selection_mode_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_bookinfo_shape_vlm", + "module": "structure", + "tag": "size" + }, + { + "name": "structure::structure_appearance_dark_vlm", + "module": "structure", + "tag": "color" + }, + { + "name": "structure::structure_reader_open_vlm", + "module": "structure", + "tag": "size" + }, + { + "name": "structure::structure_library_grid_vlm", + "module": "structure", + "tag": "shape" + } + ], + "vlm_total": 36, + "n_vlm_unverified": 0, + "vlm_log_found": true +} \ No newline at end of file diff --git a/android/acclorite-book-story/vlm_assertions.json b/android/acclorite-book-story/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..de5daeb88d9d9b3bbd0a2b78364a7e06fb2c1d97 --- /dev/null +++ b/android/acclorite-book-story/vlm_assertions.json @@ -0,0 +1,756 @@ +{ + "schema_version": 2, + "instance_id": "android/acclorite-book-story", + "grading": { + "mode": "inline", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 37, + "with_verdict": 36, + "calibrated": 0, + "usable": null, + "scored_records": 36, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "structure_gate_topbar_vlm", + "screenshot": "structure_gate_topbar_vlm.png", + "assertion": "Are there exactly three icon buttons grouped together in the top-right corner of the screen (in the app's top bar)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_gate_topbar", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_gate_bottomnav_vlm", + "screenshot": "structure_gate_bottomnav_vlm.png", + "assertion": "Is there a bottom navigation bar with exactly 3 evenly spaced items (each an icon with a label) across the bottom of the screen?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_gate_bottomnav", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_filter_sheet_vlm", + "screenshot": "structure_filter_sheet_vlm.png", + "assertion": "Is there a bottom sheet panel anchored to the bottom edge of the screen, overlaying the content above it?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_filter_sheet", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_selection_mode_vlm", + "screenshot": "structure_selection_mode_vlm.png", + "assertion": "Does the top bar show a selection count (like '1 selected') with several action icons to its right?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_selection_mode", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_bookinfo_shape_vlm", + "screenshot": "structure_bookinfo_shape_vlm.png", + "assertion": "Is there a large primary action button spanning most of the screen width near the bottom of this book-detail screen?", + "form": "question", + "expected": true, + "aspect": "size", + "modality": null, + "links_to": "structure_bookinfo_shape", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_appearance_dark_vlm", + "screenshot": "structure_appearance_dark_vlm.png", + "assertion": "Is the overall background of this screen dark (near-black or very dark grey) rather than white?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "structure_appearance_dark", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_reader_open_vlm", + "screenshot": "structure_reader_open_vlm.png", + "assertion": "Does a block of body text (multiple lines of a paragraph) fill most of the screen area?", + "form": "question", + "expected": true, + "aspect": "size", + "modality": null, + "links_to": "structure_reader_open", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_library_grid_vlm", + "screenshot": "structure_library_grid_vlm.png", + "assertion": "Are there two book cover cards displayed side by side in the same row (a grid layout), rather than stacked vertically?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "structure_library_grid", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_history_vlm", + "screenshot": "nav_reach_history_vlm.png", + "assertion": "Is this a reading-history screen showing either a list of book entries grouped by date, or a centered empty-state illustration with a message — and NOT a grid of book covers?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "nav_reach_history", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_more_sheet_vlm", + "screenshot": "nav_reach_more_sheet_vlm.png", + "assertion": "Is there a small menu panel anchored to the BOTTOM edge of the screen (a bottom sheet with a drag handle), rather than a full-screen page?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_reach_more_sheet", + "rigor": { + "jump_kind": "none", + "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 full-screen settings page showing a vertical list of category rows (each a title with a smaller subtitle beneath it), with a back arrow at the top-left?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "nav_reach_settings", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_book_info_vlm", + "screenshot": "nav_reach_book_info_vlm.png", + "assertion": "Does this screen show a single large book-cover image near the top together with an action button to start/read the book, i.e. a book detail page (not a grid of many covers)?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "nav_reach_book_info", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_reader_vlm", + "screenshot": "nav_reach_reader_vlm.png", + "assertion": "Is this an ebook reading page filled mostly with paragraphs of body text (a page of prose), rather than a list, a grid, or a form?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "nav_reach_reader", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_reader_settings_sheet_vlm", + "screenshot": "nav_reach_reader_settings_sheet_vlm.png", + "assertion": "Is there a settings panel anchored to the BOTTOM portion of the screen (a bottom sheet with option rows), overlaying the page beneath it?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_reach_reader_settings_sheet", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "nav_reach_about_vlm", + "screenshot": "nav_reach_about_vlm.png", + "assertion": "Does this About screen show an app icon near the top followed by a vertical list of tappable link rows (e.g. report a bug, credits, licenses)?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "nav_reach_about", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_book_survives_process_death_vlm", + "screenshot": "interaction_book_survives_process_death_vlm.png", + "assertion": "After relaunching the app, does the Library screen still show at least one book card (a cover tile with a title label beneath it)?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "interaction_book_survives_process_death", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_longpress_selection_vlm", + "screenshot": "interaction_longpress_selection_vlm.png", + "assertion": "One of the book covers is now selected. Does exactly one book cover show a selection indicator on it (a check mark or a highlighted/outlined overlay) that the other cover does not have?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "interaction_longpress_selection", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_history_entry_vlm", + "screenshot": "interaction_history_entry_vlm.png", + "assertion": "This is a reading-history screen. Is there a list row that shows a small book cover thumbnail on the left with a book title and a time (HH:MM) beside it?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "interaction_history_entry", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_library_two_cards_vlm", + "screenshot": "interaction_library_two_cards_vlm.png", + "assertion": "How many distinct book cards (each a cover tile with its own title label) are shown in this library grid? Answer YES only if there are exactly two.", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "interaction_library_two_cards", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_reader_page_vlm", + "screenshot": "interaction_reader_page_vlm.png", + "assertion": "Is this screen showing a page of readable book text (multiple lines/paragraphs of body text with margins), rather than an empty screen, a list, or a dialog?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "interaction_reader_page", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_book_info_actions_vlm", + "screenshot": "interaction_book_info_actions_vlm.png", + "assertion": "This is a book-detail screen. Does it show the book's title near the top and two labelled action buttons reading 'Move' and 'Delete'?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "interaction_book_info_actions", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_bg_swatch_vlm", + "screenshot": "computation_bg_swatch_vlm.png", + "assertion": "In the 'Background color' section of this colour settings screen, is the colour preview swatch rendered white or a very pale/near-white shade (not a dark or saturated colour)?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "computation_bg_swatch", + "rigor": { + "jump_kind": "none", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_font_swatch_vlm", + "screenshot": "computation_font_swatch_vlm.png", + "assertion": "In the 'Font color' section of this colour settings screen, is the colour preview swatch rendered a dark, near-black colour (not white or a pale shade)?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "computation_font_swatch", + "rigor": { + "jump_kind": "none", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_swatches_differ_vlm", + "screenshot": "computation_swatches_differ_vlm.png", + "assertion": "This colour settings screen shows a light/pale 'Background color' preview swatch and a dark 'Font color' preview swatch. Are those two preview swatches clearly different colours from each other (one light, one dark)?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "computation_swatches_differ", + "rigor": { + "jump_kind": "none", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_dark_theme_enable_vlm", + "screenshot": "states_dark_theme_enable_vlm.png", + "assertion": "Is the background of this settings screen a dark/near-black colour with light-coloured text (dark mode), rather than a white/light background?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_dark_theme_enable", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_dark_theme_persists_vlm", + "screenshot": "states_dark_theme_persists_vlm.png", + "assertion": "After the app was restarted, is this settings screen still rendered in dark mode — a dark/near-black background with light text (not a white/light background)?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_dark_theme_persists", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_dark_theme_highlight_vlm", + "screenshot": "states_dark_theme_highlight_vlm.png", + "assertion": "In the 'Dark theme' row (segments System, Disabled, Enabled), is the 'Enabled' segment visually highlighted with a coloured/filled background pill that the other two segments do NOT have?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_dark_theme_highlight", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_app_theme_select_vlm", + "screenshot": "states_app_theme_select_vlm.png", + "assertion": "In this 'App theme' setting, is the currently selected theme card (the one with a check mark) labelled 'Neptune' and showing a blue/indigo colour swatch?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_app_theme_select", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_app_theme_ring_vlm", + "screenshot": "states_app_theme_ring_vlm.png", + "assertion": "In this 'App theme' card row (Mercury, Neptune, Earth), does exactly one card show a check-mark / selection badge marking it as the chosen theme?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_app_theme_ring", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_nav_labels_hide_vlm", + "screenshot": "states_nav_labels_hide_vlm.png", + "assertion": "Look at the bottom navigation bar of this app. Are the icons shown WITHOUT any text labels underneath them (no 'Library'/'History'/'Browse' words under the bottom-bar icons)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "states_nav_labels_hide", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_display_mode_list_grid_vlm", + "screenshot": "states_display_mode_list_grid_vlm.png", + "assertion": "On this Library screen, are the book covers arranged side by side in a GRID (two or more covers in the same horizontal row), rather than stacked vertically in a single-column list?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "states_display_mode_list_grid", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_display_mode_list_list_vlm", + "screenshot": "states_display_mode_list_list_vlm.png", + "assertion": "On this Library screen, are the book covers now stacked vertically in a single-column LIST (each book on its own row, one above the other), rather than side by side in a grid?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "states_display_mode_list_list", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_display_mode_persists_vlm", + "screenshot": "states_display_mode_persists_vlm.png", + "assertion": "After the app was restarted, on this Library screen are the book covers still stacked vertically in a single-column LIST (one book per row) rather than in a side-by-side grid?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "states_display_mode_persists", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_display_highlight_vlm", + "screenshot": "states_display_highlight_vlm.png", + "assertion": "In the 'Display mode' row (segments 'Grid' and 'List'), is exactly one of the two segments visually highlighted with a coloured/filled background pill (the selected one) while the other is plain?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_display_highlight", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_font_style_italic_highlight_vlm", + "screenshot": "states_font_style_italic_highlight_vlm.png", + "assertion": "In the 'Font style' row (segments 'Normal' and 'Italic'), is the 'Italic' segment the one visually highlighted with a coloured/filled background pill (marking it selected) rather than 'Normal'?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_font_style_italic_highlight", + "rigor": { + "jump_kind": "none", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_progress_count_change_highlight_vlm", + "screenshot": "states_progress_count_change_highlight_vlm.png", + "assertion": "In the 'Progress count' row (segments 'Percentage' and 'Quantity'), is the 'Quantity' segment the one visually highlighted with a coloured/filled background pill (marking it selected)?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_progress_count_change_highlight", + "rigor": { + "jump_kind": "none", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_text_align_highlight_vlm", + "screenshot": "states_text_align_highlight_vlm.png", + "assertion": "In the 'Text alignment' row (segments Start, Justify, Center, End), is the 'Center' segment the one visually highlighted with a coloured/filled background pill (marking it selected)?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_text_align_highlight", + "rigor": { + "jump_kind": "none", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + } + ], + "merged_from_files": 1, + "source_shapes": { + "list": 1 + } +} \ No newline at end of file diff --git a/android/alialbaali-noto/LICENSE.md b/android/alialbaali-noto/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/android/alialbaali-noto/LICENSE.md @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/android/alialbaali-noto/instance.json b/android/alialbaali-noto/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..347af6752108c1aa3e32b9c8d31955e5bcd93bea --- /dev/null +++ b/android/alialbaali-noto/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "android/alialbaali-noto", + "platform": "android", + "repo": "https://github.com/alialbaali/Noto", + "commit": "a1863c169f12d6852edc1c03d080a050647d3964", + "patches": [], + "package": "com.noto.debug", + "license": null +} diff --git a/android/alialbaali-noto/reference/launch.sh b/android/alialbaali-noto/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8 --- /dev/null +++ b/android/alialbaali-noto/reference/launch.sh @@ -0,0 +1,9 @@ +#!/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 1 diff --git a/android/alialbaali-noto/tests/android_computation_eval.json b/android/alialbaali-noto/tests/android_computation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..1bbd6629b1bc92100f54b2cf323b4ddb7e4d9d0e --- /dev/null +++ b/android/alialbaali-noto/tests/android_computation_eval.json @@ -0,0 +1,233 @@ +{ + "module": "computation", + "total": 22, + "passed": 22, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 19, + "passed": 19, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 3, + "passed": 3, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.1579, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 22, + "depth_ge1": 22, + "depth_ge2": 18, + "value": 22, + "vlm_fine": 0 + }, + "results": [ + { + "test": "computation_wc_empty", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "0 Words" + }, + { + "test": "computation_wc_one", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "1 Word" + }, + { + "test": "computation_wc_two", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "2 Words" + }, + { + "test": "computation_wc_three", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "3 Words" + }, + { + "test": "computation_wc_four", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "4 Words" + }, + { + "test": "computation_wc_four_vlm", + "passed": true, + "message": "VLM: Q='In this note editor screen, is the text '4 Words' displayed in the header row near the top (next to the folder title)?' A=YES expect=YES", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In this note editor screen, is the text '4 Words' displayed in the header row near the top (next to the folder title)?", + "tag": "content" + }, + { + "test": "computation_wc_five", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "5 Words" + }, + { + "test": "computation_wc_seven_single_chars", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "7 Words" + }, + { + "test": "computation_wc_multi_space", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "2 Words" + }, + { + "test": "computation_wc_lead_trail_space", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "2 Words" + }, + { + "test": "computation_wc_punctuation", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "2 Words" + }, + { + "test": "computation_wc_title_excluded_empty", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "0 Words" + }, + { + "test": "computation_wc_title_excluded_body", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "2 Words" + }, + { + "test": "computation_folder_count_one", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "1 Note" + }, + { + "test": "computation_folder_count_two", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "2 Notes" + }, + { + "test": "computation_folder_count_three", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "3 Notes" + }, + { + "test": "computation_home_cards_count", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "All=2, Recent=2" + }, + { + "test": "computation_home_cards_count_vlm", + "passed": true, + "message": "VLM: Q='On this home screen, does the 'All' library card show the number 2 as its note count?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: On this home screen, does the 'All' library card show the number 2 as its note count?", + "tag": "content" + }, + { + "test": "computation_folders_count_one", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "1 Folder" + }, + { + "test": "computation_folders_count_two", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "2 Folders" + }, + { + "test": "computation_reading_paging", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "1 / 1 Note" + }, + { + "test": "computation_reading_paging_vlm", + "passed": true, + "message": "VLM: Q='In this full-screen reading view, is the paging indicator '1 / 1 Note' displayed (showing you are on note 1 of 1)?' A=YES expect=YES", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In this full-screen reading view, is the paging indicator '1 / 1 Note' displayed (showing you are on note 1 of 1)?", + "tag": "content" + } + ] +} \ No newline at end of file diff --git a/android/alialbaali-noto/tests/android_interaction_eval.json b/android/alialbaali-noto/tests/android_interaction_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..69ee55027793203207e99d1929eef9509f30f4a5 --- /dev/null +++ b/android/alialbaali-noto/tests/android_interaction_eval.json @@ -0,0 +1,228 @@ +{ + "module": "interaction", + "total": 21, + "passed": 21, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 14, + "passed": 14, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 7, + "passed": 7, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.5, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 21, + "depth_ge1": 20, + "depth_ge2": 10, + "value": 15, + "vlm_fine": 5 + }, + "results": [ + { + "test": "interaction_create_note", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "note 'Groceries' in list" + }, + { + "test": "interaction_second_create_two_rows", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "both FirstNote & SecondNote present" + }, + { + "test": "interaction_multi_record_integrity", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "3 notes A/B/C present" + }, + { + "test": "interaction_duplicate_note", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "two 'DupMe' rows after Duplicate" + }, + { + "test": "interaction_duplicate_note_vlm", + "passed": true, + "message": "VLM: Q='Are there two note cards with the same title text positioned immediately one above the other (adjacent) in the note list?' A=YES expect=YES", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Are there two note cards with the same title text positioned immediately one above the other (adjacent) in the note list?", + "tag": "position" + }, + { + "test": "interaction_edit_note_body_persists", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "note body 'alpha beta'" + }, + { + "test": "interaction_create_folder", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "folder 'Projects' on HOME" + }, + { + "test": "interaction_create_two_folders", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "both 'Projects' & 'Ideas' on HOME" + }, + { + "test": "interaction_note_survives_process_death", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "'Persist1' survives restart" + }, + { + "test": "interaction_folder_survives_process_death", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "'KeepMe' folder survives restart" + }, + { + "test": "interaction_edited_body_survives_process_death", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "body 'saved body xyz' after restart" + }, + { + "test": "interaction_selection_check_dark_vlm", + "passed": true, + "message": "VLM: Q='The selected note row shows a small circular check/tick badge in its corner: is that badge a SOLID DARK/BLACK filled circle (not a hollow outline)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: The selected note row shows a small circular check/tick badge in its corner: is that badge a SOLID DARK/BLACK filled circle (not a hollow outline)?", + "tag": "color" + }, + { + "test": "interaction_selection_check_badge_vlm", + "passed": true, + "message": "VLM: Q='Does exactly one note row show a filled circular check/tick badge in its corner marking it as selected, while the other row has none?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Does exactly one note row show a filled circular check/tick badge in its corner marking it as selected, while the other row has none?", + "tag": "shape" + }, + { + "test": "interaction_selection_action_bar_vlm", + "passed": true, + "message": "VLM: Q='Is a bottom action bar with several selection action icons (reminder, pin, share, archive and a more-options button) rendered along the bottom of the screen?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is a bottom action bar with several selection action icons (reminder, pin, share, archive and a more-options button) rendered along the bottom of the screen?", + "tag": "layout" + }, + { + "test": "interaction_multi_select_count", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "2 selected" + }, + { + "test": "interaction_pin_note", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "'Pinned' section appears" + }, + { + "test": "interaction_pinned_section_vlm", + "passed": true, + "message": "VLM: Q='Is there a 'Pinned' section heading near the top of the note list with a note shown directly beneath it, positioned above the rest of the notes?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is there a 'Pinned' section heading near the top of the note list with a note shown directly beneath it, positioned above the rest of the notes?", + "tag": "position" + }, + { + "test": "interaction_note_options_grid_vlm", + "passed": true, + "message": "VLM: Q='Does this bottom sheet titled 'Note options' show a grid/list of several labeled action tiles such as Add reminder, Reading Mode, Pin, Share, Archive, Duplicate, Copy, Move to and Delete?' A=YES expect=YES", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Does this bottom sheet titled 'Note options' show a grid/list of several labeled action tiles such as Add reminder, Reading Mode, Pin, Share, Archive, Duplicate, Copy, Move to and Delete?", + "tag": "layout" + }, + { + "test": "interaction_move_note_between_folders", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "MoveMe left General, in Dest" + }, + { + "test": "interaction_new_folder_note_roundtrip", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "'Day1' in fresh folder 'Trip'" + }, + { + "test": "interaction_created_note_card_vlm", + "passed": true, + "message": "VLM: Q='In the note card, is the title line ('CardTitle') rendered in a LARGER or bolder font than, and positioned above, the body-preview line ('card body preview')?' A=YES expect=YES", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In the note card, is the title line ('CardTitle') rendered in a LARGER or bolder font than, and positioned above, the body-preview line ('card body preview')?", + "tag": "size" + } + ] +} \ No newline at end of file diff --git a/android/alialbaali-noto/tests/android_navigation_eval.json b/android/alialbaali-noto/tests/android_navigation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..16ef36cb1c56d315d6567649c681824f44cdd4a6 --- /dev/null +++ b/android/alialbaali-noto/tests/android_navigation_eval.json @@ -0,0 +1,263 @@ +{ + "module": "navigation", + "total": 25, + "passed": 25, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 19, + "passed": 19, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 6, + "passed": 6, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.3158, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 25, + "depth_ge1": 25, + "depth_ge2": 10, + "value": 0, + "vlm_fine": 3 + }, + "results": [ + { + "test": "nav_reach_folder", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "folder note-list shown (fab 'Create note' appeared); HOME sheet title 'Noto Debug' gone" + }, + { + "test": "nav_reach_home_from_folder", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "HOME sheet title 'Noto Debug' reappeared; folder fab 'Create note' gone" + }, + { + "test": "nav_reach_settings", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Settings surface visible ('About' row appeared); 'Noto Debug' gone" + }, + { + "test": "nav_reach_settings_vlm", + "passed": true, + "message": "VLM: Q='Is a settings screen showing a vertical list of labelled rows, each row with a small leading icon on its left?' A=YES expect=YES", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is a settings screen showing a vertical list of labelled rows, each row with a small leading icon on its left?", + "tag": "layout" + }, + { + "test": "nav_reach_recent", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Recent screen shown (grouping header 'Today' appeared); HOME sheet 'Noto Debug' gone" + }, + { + "test": "nav_reach_all", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "All-notes screen shown (bottom-bar 'Collapse' appeared); 'Noto Debug' gone" + }, + { + "test": "nav_reach_archived", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Archived screen shown (bottom-bar 'Collapse' appeared); 'Noto Debug' gone" + }, + { + "test": "nav_reach_more_menu", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "home more menu shown ('Folders vault' appeared); HOME fab 'Create folder' gone" + }, + { + "test": "nav_reach_more_menu_vlm", + "passed": true, + "message": "VLM: Q='Is a small menu sheet showing a short vertical list of text entries (vault / archive / settings), overlaying the screen near the bottom?' A=YES expect=YES", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is a small menu sheet showing a short vertical list of text entries (vault / archive / settings), overlaying the screen near the bottom?", + "tag": "layout" + }, + { + "test": "nav_reach_search", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "in-folder search field (til_search) appeared; folder 'Folder options' action gone" + }, + { + "test": "nav_reach_notes_view", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Notes-view dialog shown ('Apply' appeared); folder fab 'Create note' gone" + }, + { + "test": "nav_reach_notes_view_vlm", + "passed": true, + "message": "VLM: Q='Is a bottom sheet dialog anchored to the lower portion of the screen, overlaying a dimmed screen behind it?' A=YES expect=YES", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is a bottom sheet dialog anchored to the lower portion of the screen, overlaying a dimmed screen behind it?", + "tag": "position" + }, + { + "test": "nav_reach_folder_options", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "folder-options sheet shown ('New note shortcut' appeared); fab 'Create note' gone" + }, + { + "test": "nav_chain_editor", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "note editor shown (Body field appeared); folder fab 'Create note' gone" + }, + { + "test": "nav_chain_editor_vlm", + "passed": true, + "message": "VLM: Q='Is there a back-arrow icon at the very top-left of the screen, next to the folder title in the toolbar?' A=YES expect=YES", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is there a back-arrow icon at the very top-left of the screen, next to the folder title in the toolbar?", + "tag": "position" + }, + { + "test": "nav_chain_general_settings", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "General settings shown ('Theme' row appeared); Settings-only 'Support Noto' gone" + }, + { + "test": "nav_chain_theme_dialog", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "Theme dialog shown (option 'Light' appeared); General row 'Language' gone" + }, + { + "test": "nav_chain_note_options", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Note-options sheet shown ('Note options' title appeared); selection subtitle '… Selected' gone" + }, + { + "test": "nav_chain_reading_mode", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "Reading Mode shown (paging arrow 'Next' appeared); 'Note options' gone" + }, + { + "test": "nav_chain_reading_mode_vlm", + "passed": true, + "message": "VLM: Q='Is there a solid black rounded-square button with a white pencil icon centered along the very bottom of the screen, with a small paging arrow to its left and another to its right?' A=YES expect=YES", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is there a solid black rounded-square button with a white pencil icon centered along the very bottom of the screen, with a small paging arrow to its left and another to its right?", + "tag": "position" + }, + { + "test": "nav_back_editor_to_home", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "HOME sheet 'Noto Debug' restored after BACK; editor Body field gone" + }, + { + "test": "nav_back_settings_to_folder", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "folder fab 'Create note' restored after BACK; Settings 'About' gone" + }, + { + "test": "nav_back_general_to_settings", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Settings 'Support Noto' restored after BACK; General 'Theme' row gone" + }, + { + "test": "nav_back_reading_to_folder", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "folder fab 'Create note' restored after BACK; reading-mode 'Next' arrow gone" + }, + { + "test": "nav_folder_bottom_bar_vlm", + "passed": true, + "message": "VLM: Q='Is there a horizontal row of action icons along the bottom of the screen (a menu/hamburger, a plus/add, and search), forming a bottom app bar?' A=YES expect=YES", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is there a horizontal row of action icons along the bottom of the screen (a menu/hamburger, a plus/add, and search), forming a bottom app bar?", + "tag": "layout" + } + ] +} \ No newline at end of file diff --git a/android/alialbaali-noto/tests/android_states_eval.json b/android/alialbaali-noto/tests/android_states_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..70274c8809edc866c56ad6836eb941b2d276b519 --- /dev/null +++ b/android/alialbaali-noto/tests/android_states_eval.json @@ -0,0 +1,295 @@ +{ + "module": "states", + "total": 28, + "passed": 28, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 17, + "passed": 17, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 11, + "passed": 11, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.6471, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 28, + "depth_ge1": 26, + "depth_ge2": 16, + "value": 10, + "vlm_fine": 9 + }, + "results": [ + { + "test": "states_selection_on", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "iv_selected absent -> present; subtitle gains ' • 1 Selected'" + }, + { + "test": "states_selection_on_vlm", + "passed": true, + "message": "VLM: Q='Does exactly one note row show a solid, filled circular check/selection badge (a coloured circle with a checkmark) on it?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Does exactly one note row show a solid, filled circular check/selection badge (a coloured circle with a checkmark) on it?", + "tag": "shape" + }, + { + "test": "states_selection_bar_vlm", + "passed": true, + "message": "VLM: Q='Is a horizontal action bar of icon buttons (reminder, pin, share, archive) shown along the bottom of the screen?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is a horizontal action bar of icon buttons (reminder, pin, share, archive) shown along the bottom of the screen?", + "tag": "layout" + }, + { + "test": "states_selection_off", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "subtitle ' • 1 Selected' -> no 'Selected'; iv_selected removed" + }, + { + "test": "states_multiselect_two", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "'1 Selected' / 1 badge -> '2 Selected' / 2 badges" + }, + { + "test": "states_selection_count_increment", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "subtitle '• 1 Selected' -> '• 2 Selected'" + }, + { + "test": "states_all_chip_active", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "tv_all_label 'All' + ib_new_label present as the active filter row" + }, + { + "test": "states_all_chip_active_vlm", + "passed": true, + "message": "VLM: Q='Near the top of the note list, the row starts with an 'All' label and a neighbouring icon button. Is the 'All' label drawn as a FILLED solid (dark) pill/box with light text, while the neighbouring button is only an OUTLINED (unfilled, white-interior) box?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Near the top of the note list, the row starts with an 'All' label and a neighbouring icon button. Is the 'All' label drawn as a FILLED solid (dark) pill/box with light text, while the neighbouring button is only an OUTLINED (unfilled, white-interior) box?", + "tag": "color" + }, + { + "test": "states_undo_disabled_vlm", + "passed": true, + "message": "VLM: Q='In the bottom toolbar of this note editor, does the Undo (left curved arrow) icon look greyed-out / dimmed compared with the other toolbar icons?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In the bottom toolbar of this note editor, does the Undo (left curved arrow) icon look greyed-out / dimmed compared with the other toolbar icons?", + "tag": "color" + }, + { + "test": "states_undo_enable", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "ib_undo enabled 'false' -> 'true' after an edit" + }, + { + "test": "states_redo_stays_disabled", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "after an edit: ib_redo enabled 'false' (nothing to redo), ib_undo 'true'" + }, + { + "test": "states_undo_history_disabled", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "fresh note: ib_undo_history & ib_redo_history enabled 'false'" + }, + { + "test": "states_theme_light_vlm", + "passed": true, + "message": "VLM: Q='Is the overall app background LIGHT (white / very pale) with dark text, rather than a dark/black background?' A=YES expect=YES", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is the overall app background LIGHT (white / very pale) with dark text, rather than a dark/black background?", + "tag": "color" + }, + { + "test": "states_theme_selected_mark_vlm", + "passed": true, + "message": "VLM: Q='In this Theme option list, is the 'Light' option visibly marked as the current selection (a filled radio dot or a highlighted row) while the other options are not?' A=YES expect=YES", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In this Theme option list, is the 'Light' option visibly marked as the current selection (a filled radio dot or a highlighted row) while the other options are not?", + "tag": "shape" + }, + { + "test": "states_theme_persists_vlm", + "passed": true, + "message": "VLM: Q='Is the overall app background still LIGHT (white / very pale) with dark text after the app was restarted?' A=YES expect=YES", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is the overall app background still LIGHT (white / very pale) with dark text after the app was restarted?", + "tag": "color" + }, + { + "test": "states_theme_persists", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "Theme row 'Light' after selection AND still 'Light' after relaunch" + }, + { + "test": "states_theme_dark_vlm", + "passed": true, + "message": "VLM: Q='Is the overall app background now DARK (near-black / very dark) with light-coloured text?' A=YES expect=YES", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is the overall app background now DARK (near-black / very dark) with light-coloured text?", + "tag": "color" + }, + { + "test": "states_show_count_thumb_vlm", + "passed": true, + "message": "VLM: Q='On the 'Show notes count' settings row, is there a switch whose thumb is toward the RIGHT / in the ON position (the track filled/coloured)?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: On the 'Show notes count' settings row, is there a switch whose thumb is toward the RIGHT / in the ON position (the track filled/coloured)?", + "tag": "position" + }, + { + "test": "states_show_count_toggle", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "HOME note-count nodes present -> absent after toggling off" + }, + { + "test": "states_show_count_persists", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "HOME count nodes absent both before AND after relaunch" + }, + { + "test": "states_notes_view_current_state", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Filtering=Inclusive, Sorting=Creation date, Ordering=Descending, Grouping=None" + }, + { + "test": "states_ordering_toggle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "order value 'Descending' -> 'Ascending' (Ascending text appears)" + }, + { + "test": "states_reading_paging_position", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "tv_notes_count desc == '1 / M Note(s)' (paging at position 1)" + }, + { + "test": "states_reading_paging_vlm", + "passed": true, + "message": "VLM: Q='In this full-screen reading view, near the top under the folder name, is a page-position indicator rendered showing something like '1 / 1 Note' or '1 / 2 Note'?' A=YES expect=YES", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In this full-screen reading view, near the top under the folder name, is a page-position indicator rendered showing something like '1 / 1 Note' or '1 / 2 Note'?", + "tag": "layout" + }, + { + "test": "states_body_focus", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "et_note_body focused 'false' -> 'true'; soft keyboard visible" + }, + { + "test": "states_title_focus", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "et_note_title focused 'true' & et_note_body focused 'false'" + }, + { + "test": "states_home_cards", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "All / Recent / Scheduled / Archived cards all present on HOME" + }, + { + "test": "states_home_cards_vlm", + "passed": true, + "message": "VLM: Q='Near the top of this screen are four library cards. Do they have FOUR DISTINCT accent colours (for example blue, amber/yellow, red, and purple) rather than all being the same colour?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Near the top of this screen are four library cards. Do they have FOUR DISTINCT accent colours (for example blue, amber/yellow, red, and purple) rather than all being the same colour?", + "tag": "color" + } + ] +} \ No newline at end of file diff --git a/android/alialbaali-noto/tests/android_structure_eval.json b/android/alialbaali-noto/tests/android_structure_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..9302aca6f9751525dfab9f9a6ceb23385401083f --- /dev/null +++ b/android/alialbaali-noto/tests/android_structure_eval.json @@ -0,0 +1,229 @@ +{ + "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": 11, + "liveness": 0, + "interactive": 10, + "depth_ge1": 10, + "depth_ge2": 5, + "value": 0, + "vlm_fine": 6 + }, + "results": [ + { + "test": "structure_gate_home_sheet", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_gate_default_folder", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_gate_library_grid_count", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_folder_replaces_home", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "folder note-list subtree (notes_view/fab Create note/Folders bar) replaces home sheet" + }, + { + "test": "structure_editor_subtree_appears", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "et_note_title+et_note_body+bab_toolbar(4 ImageButtons) appear only after fab Create note" + }, + { + "test": "structure_selection_bar_appears", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "selection bar (add_reminder/pin/share/fab_selection) absent->present on long-press" + }, + { + "test": "structure_notesview_sheet_appears", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "notes-view bottom-sheet subtree (Filtering/Sorting/Apply rows) added over folder screen" + }, + { + "test": "structure_newfolder_dialog_appears", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "new-folder dialog subtree (et Title field + btn_create) added over home sheet" + }, + { + "test": "structure_note_options_sheet_appears", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Note options sheet ('Note options' title + >=5 action rows), clickable count increases" + }, + { + "test": "structure_reading_mode_subtree", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "reading-mode subtree fab_next+fab_previous+fab 'Edit' appears after Reading Mode" + }, + { + "test": "structure_settings_list_appears", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Settings list subtree (rows incl. General + About) replaces home sheet" + }, + { + "test": "structure_general_settings_rows", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "General-settings rows subtree (rows incl. Theme + Language) appears" + }, + { + "test": "structure_editor_toolbar_shape", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "bab_toolbar contains exactly 4 ImageButtons (undo_history/undo/redo/redo_history)" + }, + { + "test": "structure_home_grid_vlm", + "passed": true, + "message": "VLM: Q='In the lower white panel of this note-taking app, is there a 2 by 2 grid of exactly four rectangular cards labelled All, Recent, Scheduled and Archived?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the lower white panel of this note-taking app, is there a 2 by 2 grid of exactly four rectangular cards labelled All, Recent, Scheduled and Archived?", + "tag": "layout" + }, + { + "test": "structure_home_cards_color_vlm", + "passed": true, + "message": "VLM: Q='Are the four library cards color-coded so that each card's outline, icon and label use a DIFFERENT accent color (one blue, one amber/orange, one red, one purple)?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Are the four library cards color-coded so that each card's outline, icon and label use a DIFFERENT accent color (one blue, one amber/orange, one red, one purple)?", + "tag": "color" + }, + { + "test": "structure_home_fab_position_vlm", + "passed": true, + "message": "VLM: Q='Is there a solid dark (black) rounded-square floating button showing a small plus/add icon in the BOTTOM-RIGHT corner of the screen?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is there a solid dark (black) rounded-square floating button showing a small plus/add icon in the BOTTOM-RIGHT corner of the screen?", + "tag": "position" + }, + { + "test": "structure_editor_title_above_body_vlm", + "passed": true, + "message": "VLM: Q='In this note editor, is the single-line 'Title' input field positioned ABOVE the larger multi-line 'Body' input area?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In this note editor, is the single-line 'Title' input field positioned ABOVE the larger multi-line 'Body' input area?", + "tag": "position" + }, + { + "test": "structure_editor_toolbar_row_vlm", + "passed": true, + "message": "VLM: Q='Just ABOVE the on-screen keyboard on this note editor, is there a single horizontal row of exactly four evenly spaced icon buttons (undo/redo style arrows)?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Just ABOVE the on-screen keyboard on this note editor, is there a single horizontal row of exactly four evenly spaced icon buttons (undo/redo style arrows)?", + "tag": "position" + }, + { + "test": "structure_reading_mode_fullscreen_vlm", + "passed": true, + "message": "VLM: Q='Does this screen show the note's title and text as static (non-editable) content on a large, mostly empty full-screen page with no 'Title'/'Body' input boxes and no on-screen keyboard?' A=YES expect=YES", + "depth": 3, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does this screen show the note's title and text as static (non-editable) content on a large, mostly empty full-screen page with no 'Title'/'Body' input boxes and no on-screen keyboard?", + "tag": "layout" + }, + { + "test": "structure_folder_label_row_vlm", + "passed": true, + "message": "VLM: Q='Directly beneath the folder's 'General' title and note-count, is there a horizontal row with a filled dark pill labelled 'All' next to a small outlined add (+) button?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Directly beneath the folder's 'General' title and note-count, is there a horizontal row with a filled dark pill labelled 'All' next to a small outlined add (+) button?", + "tag": "position" + }, + { + "test": "structure_newfolder_swatches_vlm", + "passed": true, + "message": "VLM: Q='In this 'New folder' dialog, under a 'Color' label, is there a row of several small circular color swatches in different colors?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In this 'New folder' dialog, under a 'Color' label, is there a row of several small circular color swatches in different colors?", + "tag": "shape" + } + ] +} \ No newline at end of file diff --git a/android/alialbaali-noto/tests/android_testgen_kit.py b/android/alialbaali-noto/tests/android_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..61f347c5192ef231fd74d178c47780c65abb282a --- /dev/null +++ b/android/alialbaali-noto/tests/android_testgen_kit.py @@ -0,0 +1,1851 @@ +#!/usr/bin/env python3 +"""Android TestGen Kit — the single source of every test helper, so a test's +NAVIGATION 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 package +name differs): always use the module-level PACKAGE (argv[1]). Never write a package +name, an .apk path, a /data/data path, or a pixel coordinate as a literal. + python3 android_testgen_kit.py lint_sources # flags all of those + +SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery): + python3 android_testgen_kit.py audit + python3 android_testgen_kit.py lint + python3 android_testgen_kit.py lint_sources + python3 android_testgen_kit.py audit_depth [results_dir] +""" +from __future__ import annotations + +import ast +import base64 +import functools +import glob +import hashlib +import json +import math +import os +import re +import shlex +import subprocess +import sys +import time +import urllib.error +import 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.0 +SETTLE = { + "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 /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 " list[dict]: + """XML -> list of attribute dicts, each with _bounds and _center.""" + nodes = [] + for m in re.finditer(r"]+?)/?>", 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.6-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_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") + if not screencap(ss_path): + return record(test_name, False, "setup_failed: screenshot capture failed", + depth=depth, jump_kind=jump_kind, tag=tag) + + 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 record(test_name, False, "setup_failed: VLM API call failed", + depth=depth, jump_kind=jump_kind, tag=tag) + 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 record(test_name, False, + f"setup_failed: ambiguous VLM response after {VLM_RETRIES} " + f"asks {resp!r}", + depth=depth, jump_kind=jump_kind, tag=tag) + + 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) + + af = os.path.join(rd, "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({"test_name": test_name, "question": question, + "screenshot": ss_path, "vlm_response": resp, + "vlm_answer": answer, "expected": expect, + "passed": passed, "tag": tag or ""}) + try: + _write_json(af, existing) # type: ignore[arg-type] + except Exception: + with open(af, "w") as f: + json.dump(existing, f, indent=2, ensure_ascii=False) + 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 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 + tests, ignored, vlm_assertions = [], [], [] + 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} + if status == "passed": + tests.append(entry) + if name.endswith("_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), + } + 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 ignored: + print(f" {len(ignored)} baseline failure(s) excluded from the denominator " + f"(they say nothing about a recreation):") + for i in ignored[: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} \n" + " android_testgen_kit.py audit_depth [results_dir]\n" + " android_testgen_kit.py score [manifest_dir]") diff --git a/android/alialbaali-noto/tests/android_text_eval.json b/android/alialbaali-noto/tests/android_text_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..92a5614108a2ef68e028e83efef2952b98a2139c --- /dev/null +++ b/android/alialbaali-noto/tests/android_text_eval.json @@ -0,0 +1,206 @@ +{ + "module": "text", + "total": 19, + "passed": 19, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 16, + "passed": 16, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 3, + "passed": 3, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.1875, + "audit": { + "kit_api_version": 1, + "existence": 3, + "liveness": 0, + "interactive": 16, + "depth_ge1": 15, + "depth_ge2": 8, + "value": 14, + "vlm_fine": 2 + }, + "results": [ + { + "test": "text_empty_folder_placeholder", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "placeholder text == 'Folder is empty.'" + }, + { + "test": "text_empty_folder_placeholder_vlm", + "passed": true, + "message": "VLM: Q='Is a short single-line message like 'Folder is empty.' shown roughly centered in the middle of an otherwise blank note list (not at the top or bottom)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a short single-line message like 'Folder is empty.' shown roughly centered in the middle of an otherwise blank note list (not at the top or bottom)?", + "tag": "position" + }, + { + "test": "text_search_nomatch_placeholder", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "placeholder == 'No notes found containing the search term.'" + }, + { + "test": "text_search_clears_note_returns", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "'AlphaFindMe' present -> absent (nomatch) -> present (cleared)" + }, + { + "test": "text_folder_count_singular", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "subtitle content-desc == '1 Note'" + }, + { + "test": "text_folder_count_plural", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "subtitle content-desc == '2 Notes'" + }, + { + "test": "text_home_folders_count_zero", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "tv_folders_count desc == '0 Folders'" + }, + { + "test": "text_selection_subtitle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "subtitle content-desc contains '• 1 Selected'" + }, + { + "test": "text_new_note_created_timestamp", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "tv_created_at text == 'Created just now'" + }, + { + "test": "text_new_note_created_timestamp_vlm", + "passed": true, + "message": "VLM: Q='Near the BOTTOM of the note-editing area, below the text fields, are two small timestamp lines beginning with 'Created' and 'Accessed' shown one under the other?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Near the BOTTOM of the note-editing area, below the text fields, are two small timestamp lines beginning with 'Created' and 'Accessed' shown one under the other?", + "tag": "position" + }, + { + "test": "text_new_note_accessed_timestamp", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "tv_accessed_at text == 'Accessed just now'" + }, + { + "test": "text_editor_title_hint", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "et_note_title hint text == 'Title'" + }, + { + "test": "text_editor_body_hint", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "et_note_body hint text == 'Body'" + }, + { + "test": "text_echoed_note_title_body", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "folder row title=='MyNoteXYZ' body=='hello world foo bar'" + }, + { + "test": "text_reading_mode_paging_label", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "tv_notes_count desc == '1 / 1 Note'" + }, + { + "test": "text_reading_mode_paging_label_vlm", + "passed": true, + "message": "VLM: Q='Does this read-only note view display the title 'ReadMeNote' and the body text 'the quick brown fox jumps'?' A=YES expect=YES", + "depth": 4, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does this read-only note view display the title 'ReadMeNote' and the body text 'the quick brown fox jumps'?", + "tag": "content" + }, + { + "test": "text_fab_create_note_desc", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "HOME fab desc 'Create folder' -> folder fab desc 'Create note'" + }, + { + "test": "text_settings_screen_title", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "screen title text == 'Settings'" + }, + { + "test": "text_note_options_reading_mode_label", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Note-options row text == 'Reading Mode'" + } + ] +} \ No newline at end of file diff --git a/android/alialbaali-noto/tests/conftest.py b/android/alialbaali-noto/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27 --- /dev/null +++ b/android/alialbaali-noto/tests/conftest.py @@ -0,0 +1 @@ +pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"] diff --git a/android/alialbaali-noto/tests/requirements.txt b/android/alialbaali-noto/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c --- /dev/null +++ b/android/alialbaali-noto/tests/requirements.txt @@ -0,0 +1,2 @@ +pytest +pillow diff --git a/android/alialbaali-noto/tests/test_android_computation.py b/android/alialbaali-noto/tests/test_android_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..79ea5e277b414823ebd1d1486fe4ac33034ee001 --- /dev/null +++ b/android/alialbaali-noto/tests/test_android_computation.py @@ -0,0 +1,615 @@ +#!/usr/bin/env python3 +"""COMPUTATION module — Noto (minimal note-taking app). + +Lane ownership: CORE FUNCTION, input -> output. This module is the SOLE owner of +jump_kind="value": every test TYPES or CREATES an input via the real user path, +reads a FRESH ui() back, and asserts the exact COMPUTED output string it OBSERVED +the original produce. It does NOT assert reachability (navigation), the +checked/selected/enabled bit (states), CRUD data integrity (interaction), the +placeholder/label wording (text), or the view-tree shape (structure). + +THE CORE TRANSFORM = WORD COUNT. In the note editor `tv_word_count` has a +content-desc "N Words"/"1 Word" that updates LIVE as you type into `et_note_body`. +The count is a whitespace-split token count of the BODY only (title excluded). + +GROUND TRUTH — every expected value below was OBSERVED live on the original app +before authoring (see the values in each expect=), never computed from source: + empty body -> "0 Words" + "hello" -> "1 Word" (SINGULAR is "1 Word", not "1 Words") + "hello world" -> "2 Words" + "hello world foo" -> "3 Words" + "hello world foo bar" -> "4 Words" + "one two three four five" -> "5 Words" + "a b c d e f g" -> "7 Words" + "hello world" -> "2 Words" (runs of spaces collapse) + " hello world " -> "2 Words" (leading/trailing spaces trimmed) + "hello, world!" -> "2 Words" (punctuation attached to a token adds none) + long title + empty body -> "0 Words" (title does NOT count) + long title + body "just one" -> "2 Words" (title does NOT count) +Newline separation was DROPPED: typing "line1""line2" read "1 Word" on the +original (ENTER does not reliably insert a body newline — an input-path artifact, +not a word-count rule), so it is unobservable-as-a-rule and intentionally omitted. + +Secondary transform = COUNT ARITHMETIC (how many records exist, rendered as a +string). Two DIFFERENT surfaces render counts differently (OBSERVED): + * FOLDER note-list screen: `tv_folder_notes_count` CONTENT-DESC + "0 Notes" -> "1 Note" -> "2 Notes" -> "3 Notes" (singular/plural) + * HOME sheet: `tv_folders_count` CONTENT-DESC "0 Folders"/"1 Folder"/"2 Folders"; + library "All"/"Recent" cards render their count in the TEXT attribute ("2"), + NOT content-desc. + * Reading-mode paging: `tv_notes_count` content-desc "1 / 1 Note" (pos / total). + +Invoke: + python3 test_android_computation.py +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ══════════════════════════════════════════════════════════════════════════════ +# Local setup helpers (mirrors the sibling modules' conventions) +# ══════════════════════════════════════════════════════════════════════════════ + +def dismiss_prompts(): + """Dismiss the first-run system notification-permission dialog (and any stray + prompt) sitting in front of the already-loaded Noto home. Matches both the + ASCII "Don't allow" and the curly-apostrophe "Don't allow" (U+2019). The + prompt reappears after a pm clear and was seen to return on relaunch too, so + call it defensively after every launch.""" + for _ in range(3): + nodes = ui() + b = (find_node_ci(nodes, "Don't allow") or find_node_ci(nodes, "Don’t allow") + or find_node_ci(nodes, "Allow")) + if b and is_safe(b): + tap_node(b) + settle("tap") + continue + break + + +def fresh_home(): + """Virgin database (wipe) + HOME sheet. Guarantees the default 'General' + folder exists and every count starts at zero, so created records and counts + are deterministic.""" + clear_data() + launch_app() + wait_for_foreground() + dismiss_prompts() + return ui() + + +def goto_home(): + """Back out to the HOME bottom sheet (the one surface showing 'Create folder').""" + for _ in range(5): + if find_node(ui(), content_desc="Create folder"): + break + back() + settle("tap") + return ui() + + +# ── Depth-backing navigation helpers (named and_enter_*/and_reach_* so the depth +# audit can attribute the declared depth to a real navigation call). ─────────── + +def and_enter_folder(name): + """HOME sheet -> tap a folder row -> its note-list surface. Counts one + surface. Returns True when the folder title is showing.""" + n = find_node(ui(), text=name) + if n is None or not tap_node(n): + return False + settle("tap") + and_enter("folder:" + name) + tit = node_by_id(ui(), "tv_folder_title") + return tit is not None and tit.get("text") == name + + +def and_enter_editor(): + """FOLDER note-list -> tap fab 'Create note' -> the note editor. Counts one + surface. Returns True when et_note_body is present.""" + fab = find_node(ui(), content_desc="Create note") + if fab is None or not tap_node(fab): + return False + settle("tap") + and_enter("editor") + return node_by_id(ui(), "et_note_body") is not None + + +def and_reach_note_options(): + """SELECTION mode -> tap `fab_selection` 'More options' -> the Note options + sheet. Counts one surface. Returns True when 'Note options' title is showing.""" + fs = node_by_id(ui(), "fab_selection") + if fs is None or not tap_node(fs): + return False + settle("tap") + and_enter("note_options") + return find_node_ci(ui(), "Note options") is not None + + +def and_reach_reading_mode(): + """Note options sheet -> tap `tv_open_in` 'Reading Mode' -> Reading Mode. + Dismisses the first-entry immersive cling ('Got it'). Counts one surface. + Returns True when the reading-mode paging indicator is present.""" + rm = node_by_id(ui(), "tv_open_in") or find_node_ci(ui(), "Reading Mode") + if rm is None or not tap_node(rm): + return False + settle("tap") + and_enter("reading_mode") + got = find_node_ci(ui(), "Got it") + if got is not None: + tap_node(got) + settle("tap") + return node_by_id(ui(), "tv_notes_count") is not None + + +# ── Readers ────────────────────────────────────────────────────────────────── + +def read_word_count(): + """Live word-count content-desc from a FRESH dump. An extra settle absorbs the + one-frame lag between the last keystroke and the header updating.""" + settle("tap") + n = node_by_id(ui(), "tv_word_count") + return (n.get("content-desc") or "").strip() if n else "" + + +def read_folder_notes_count(): + """FOLDER note-list count, rendered as content-desc ('N Notes'/'1 Note').""" + n = node_by_id(ui(), "tv_folder_notes_count") + return (n.get("content-desc") or "").strip() if n else "" + + +def read_folders_count(): + """HOME folders count, rendered as content-desc ('N Folders'/'1 Folder').""" + n = node_by_id(ui(), "tv_folders_count") + return (n.get("content-desc") or "").strip() if n else "" + + +def card_count(nodes, title): + """HOME library card whose tv_title == `title` -> its tv_notes_count VALUE. + + OBSERVED on the HOME sheet, the count lives in the node's `text` (NOT its + content-desc, unlike the FOLDER screen), and the cards form a 2-column grid, so + the matching tv_notes_count is the one CLOSEST in BOTH x and y to the title + (the count sits just above its title inside the same card).""" + titles = [n for n in nodes + if n.get("resource-id", "").rsplit("/", 1)[-1] == "tv_title" + and n.get("text") == title] + if not titles: + return "" + tx, ty = titles[0].get("_center", (0, 0)) + best, bestd = None, 10 ** 18 + for n in nodes: + if n.get("resource-id", "").rsplit("/", 1)[-1] == "tv_notes_count": + cx, cy = n.get("_center", (0, 0)) + d = (cx - tx) ** 2 + (cy - ty) ** 2 + if d < bestd: + best, bestd = n, d + if best is None: + return "" + # Count is in `text` on this sheet; fall back to content-desc for robustness. + return (best.get("text") or best.get("content-desc") or "").strip() + + +# ── Editor / note authoring built on the navigation helpers ──────────────────── + +def open_new_editor(): + """fresh DB -> HOME -> 'General' folder -> Create note -> return the editor's + body EditText node (or None). depth after this == 2 (folder + editor).""" + fresh_home() + if not and_enter_folder("General"): + return None + if not and_enter_editor(): + return None + return node_by_id(ui(), "et_note_body") + + +def word_count_for(body_text, title_text=""): + """The star helper. Fresh note in 'General', optionally set the title, type the + body, and return the live tv_word_count content-desc. Reaching the editor is a + real depth-2 navigation (and_enter_folder + and_enter_editor), so callers may + declare depth=2 honestly. Returns (ok_reached, word_count_string).""" + body = open_new_editor() + if body is None: + return False, "" + if title_text: + tit = node_by_id(ui(), "et_note_title") + if tit is not None: + type_text(tit, title_text) + body = node_by_id(ui(), "et_note_body") + if body is None: + return False, "" + if body_text: + type_text(body, body_text) + return True, read_word_count() + + +def create_note_general(title, body="x"): + """Create a note in 'General' (auto-saved on Back). Leaves the app on HOME. + Returns True on success.""" + goto_home() + if not and_enter_folder("General"): + return False + if not and_enter_editor(): + return False + t = node_by_id(ui(), "et_note_title") + if t is None or not type_text(t, title): + return False + if body: + b = node_by_id(ui(), "et_note_body") + if b is not None: + type_text(b, body) + hide_keyboard() + back() # NEW note Back -> HOME sheet + settle("tap") + goto_home() + return True + + +def create_folder(name): + """HOME -> fab 'Create folder' -> type name -> tap `btn_create` (present and + tappable WITH the keyboard up; BACK dismisses this full-screen dialog). Leaves + the app on HOME. Returns True when the folder appears.""" + goto_home() + fab = find_node(ui(), content_desc="Create folder") + if fab is None or not tap_node(fab): + return False + settle("tap") + and_enter("new_folder_dialog") + et = node_by_id(ui(), "et") + if et is None or not type_text(et, name): + return False + btn = node_by_id(ui(), "btn_create") or find_node_ci(ui(), "Create folder") + if btn is None or not tap_node(btn): + return False + settle("tap") + goto_home() + return find_node(ui(), text=name) is not None + + +# ══════════════════════════════════════════════════════════════════════════════ +# WORD COUNT — the core transform (input -> output). depth=2 (home->folder->editor) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_wc_empty",)) +def test_wc_empty(): + """A brand-new note with an empty body reads '0 Words' (the ABSENT baseline — + the count is 0 before any word exists).""" + ok, got = word_count_for("") + passed = ok and got == "0 Words" + record("computation_wc_empty", passed, + "" if passed else ( + "feature_missing: could not reach the note editor / word count" + if not ok else f"behavior_wrong: empty body shows {got!r}, expected '0 Words'"), + depth=2, jump_kind="value", expect="0 Words") + + +@and_test(expects=("computation_wc_one",)) +def test_wc_one(): + """One word -> the SINGULAR form '1 Word' (VERIFIED on the original: singular, + not '1 Words').""" + ok, got = word_count_for("hello") + passed = ok and got == "1 Word" + record("computation_wc_one", passed, + "" if passed else ( + "feature_missing: could not reach the word count" + if not ok else f"behavior_wrong: 'hello' shows {got!r}, expected '1 Word'"), + depth=2, jump_kind="value", expect="1 Word") + + +@and_test(expects=("computation_wc_two",)) +def test_wc_two(): + """Two words -> '2 Words'.""" + ok, got = word_count_for("hello world") + passed = ok and got == "2 Words" + record("computation_wc_two", passed, + "" if passed else ( + "feature_missing: could not reach the word count" + if not ok else f"behavior_wrong: 'hello world' shows {got!r}, expected '2 Words'"), + depth=2, jump_kind="value", expect="2 Words") + + +@and_test(expects=("computation_wc_three",)) +def test_wc_three(): + """Three words -> '3 Words'.""" + ok, got = word_count_for("hello world foo") + passed = ok and got == "3 Words" + record("computation_wc_three", passed, + "" if passed else ( + "feature_missing: could not reach the word count" + if not ok else f"behavior_wrong: 'hello world foo' shows {got!r}, expected '3 Words'"), + depth=2, jump_kind="value", expect="3 Words") + + +@and_test(expects=("computation_wc_four", "computation_wc_four_vlm")) +def test_wc_four(): + """Four words -> '4 Words' (the canonical VERIFIED case). Also the VLM anchor: + confirm the computed '4 Words' is actually RENDERED in the editor header near + the folder title, not merely present in the accessibility tree.""" + ok, got = word_count_for("hello world foo bar") + passed = ok and got == "4 Words" + record("computation_wc_four", passed, + "" if passed else ( + "feature_missing: could not reach the word count" + if not ok else f"behavior_wrong: 'hello world foo bar' shows {got!r}, expected '4 Words'"), + depth=2, jump_kind="value", expect="4 Words") + # VLM #1 — the rendered word-count text in the editor header. depth matches. + vlm_assert("computation_wc_four", + "In this note editor screen, is the text '4 Words' displayed in the " + "header row near the top (next to the folder title)?", + RESULTS_DIR, depth=2, jump_kind="value", tag="content") + + +@and_test(expects=("computation_wc_five",)) +def test_wc_five(): + """Five distinct words -> '5 Words'.""" + ok, got = word_count_for("one two three four five") + passed = ok and got == "5 Words" + record("computation_wc_five", passed, + "" if passed else ( + "feature_missing: could not reach the word count" + if not ok else f"behavior_wrong: five words show {got!r}, expected '5 Words'"), + depth=2, jump_kind="value", expect="5 Words") + + +@and_test(expects=("computation_wc_seven_single_chars",)) +def test_wc_seven_single_chars(): + """Seven single-character tokens 'a b c d e f g' -> '7 Words' (each isolated + char is its own token).""" + ok, got = word_count_for("a b c d e f g") + passed = ok and got == "7 Words" + record("computation_wc_seven_single_chars", passed, + "" if passed else ( + "feature_missing: could not reach the word count" + if not ok else f"behavior_wrong: 'a b c d e f g' shows {got!r}, expected '7 Words'"), + depth=2, jump_kind="value", expect="7 Words") + + +@and_test(expects=("computation_wc_multi_space",)) +def test_wc_multi_space(): + """Runs of spaces collapse: 'hello world' -> '2 Words' (OBSERVED — the + splitter ignores empty tokens between multiple spaces).""" + ok, got = word_count_for("hello world") + passed = ok and got == "2 Words" + record("computation_wc_multi_space", passed, + "" if passed else ( + "feature_missing: could not reach the word count" + if not ok else f"behavior_wrong: 'hello world' shows {got!r}, expected '2 Words'"), + depth=2, jump_kind="value", expect="2 Words") + + +@and_test(expects=("computation_wc_lead_trail_space",)) +def test_wc_lead_trail_space(): + """Leading/trailing spaces are trimmed: ' hello world ' -> '2 Words' + (OBSERVED — boundary whitespace produces no phantom tokens).""" + ok, got = word_count_for(" hello world ") + passed = ok and got == "2 Words" + record("computation_wc_lead_trail_space", passed, + "" if passed else ( + "feature_missing: could not reach the word count" + if not ok else f"behavior_wrong: ' hello world ' shows {got!r}, expected '2 Words'"), + depth=2, jump_kind="value", expect="2 Words") + + +@and_test(expects=("computation_wc_punctuation",)) +def test_wc_punctuation(): + """Punctuation attached to a token adds no token: 'hello, world!' -> '2 Words' + (OBSERVED — the split is on whitespace only, commas/bangs ride along).""" + ok, got = word_count_for("hello, world!") + passed = ok and got == "2 Words" + record("computation_wc_punctuation", passed, + "" if passed else ( + "feature_missing: could not reach the word count" + if not ok else f"behavior_wrong: 'hello, world!' shows {got!r}, expected '2 Words'"), + depth=2, jump_kind="value", expect="2 Words") + + +@and_test(expects=("computation_wc_title_excluded_empty",)) +def test_wc_title_excluded_empty(): + """A long multi-word TITLE with an empty body still reads '0 Words' — the title + does NOT contribute to the count (VERIFIED).""" + ok, got = word_count_for("", title_text="ThisIsALongTitleWithManyWords") + passed = ok and got == "0 Words" + record("computation_wc_title_excluded_empty", passed, + "" if passed else ( + "feature_missing: could not reach the word count" + if not ok else f"behavior_wrong: long title + empty body shows {got!r}, " + f"expected '0 Words' (title must not count)"), + depth=2, jump_kind="value", expect="0 Words") + + +@and_test(expects=("computation_wc_title_excluded_body",)) +def test_wc_title_excluded_body(): + """The count reflects the BODY regardless of the title: a long title plus body + 'just one' reads '2 Words', not more (VERIFIED — body-only count).""" + ok, got = word_count_for("just one", title_text="ThisIsALongTitleWithManyWords") + passed = ok and got == "2 Words" + record("computation_wc_title_excluded_body", passed, + "" if passed else ( + "feature_missing: could not reach the word count" + if not ok else f"behavior_wrong: title + body 'just one' shows {got!r}, " + f"expected '2 Words' (body only)"), + depth=2, jump_kind="value", expect="2 Words") + + +# ══════════════════════════════════════════════════════════════════════════════ +# COUNT ARITHMETIC — record totals rendered as strings (input=create, output=count) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_folder_count_one",)) +def test_folder_count_one(): + """Creating the FIRST note in a cleared 'General' turns the folder count + '0 Notes' -> '1 Note' (SINGULAR). Positive+negative: 0 before, 1 after.""" + fresh_home() + if not and_enter_folder("General"): + record("computation_folder_count_one", False, + "setup_failed: could not open the 'General' folder", + depth=2, jump_kind="value", expect="1 Note") + return + before = read_folder_notes_count() + goto_home() + made = create_note_general("CountOne") + ok = False + got = "" + if made and and_enter_folder("General"): + got = read_folder_notes_count() + ok = before == "0 Notes" and got == "1 Note" + record("computation_folder_count_one", ok, + "" if ok else ( + "feature_missing: could not create a note / read the folder count" + if not made else f"behavior_wrong: count was {before!r} -> {got!r}, " + f"expected '0 Notes' -> '1 Note'"), + depth=2, jump_kind="value", expect="1 Note") + + +@and_test(expects=("computation_folder_count_two",)) +def test_folder_count_two(): + """A second create makes the folder count '2 Notes' (plural).""" + fresh_home() + m1 = create_note_general("CountA") + m2 = create_note_general("CountB") + got = "" + ok = False + if m1 and m2 and and_enter_folder("General"): + got = read_folder_notes_count() + ok = got == "2 Notes" + record("computation_folder_count_two", ok, + "" if ok else ( + "feature_missing: could not create two notes / read the folder count" + if not (m1 and m2) else f"behavior_wrong: count shows {got!r}, expected '2 Notes'"), + depth=2, jump_kind="value", expect="2 Notes") + + +@and_test(expects=("computation_folder_count_three",)) +def test_folder_count_three(): + """Three creates -> '3 Notes' (the arithmetic keeps accumulating).""" + fresh_home() + made = all(create_note_general(t) for t in ("C1", "C2", "C3")) + got = "" + ok = False + if made and and_enter_folder("General"): + got = read_folder_notes_count() + ok = got == "3 Notes" + record("computation_folder_count_three", ok, + "" if ok else ( + "feature_missing: could not create three notes / read the folder count" + if not made else f"behavior_wrong: count shows {got!r}, expected '3 Notes'"), + depth=2, jump_kind="value", expect="3 Notes") + + +@and_test(expects=("computation_home_cards_count", "computation_home_cards_count_vlm")) +def test_home_cards_count(): + """After creating 2 notes, the HOME 'All' AND 'Recent' library cards both show + '2' — the note total propagates to the derived library counters (the count is + rendered in the card's text). VLM: confirm the number is RENDERED on 'All'.""" + fresh_home() + m1 = create_note_general("CardA") + m2 = create_note_general("CardB") + goto_home() + nodes = ui() + all_c = card_count(nodes, "All") + rec_c = card_count(nodes, "Recent") + ok = (m1 and m2) and all_c == "2" and rec_c == "2" + record("computation_home_cards_count", ok, + "" if ok else ( + "feature_missing: could not create notes / read the library cards" + if not (m1 and m2) else f"behavior_wrong: All={all_c!r} Recent={rec_c!r}, " + f"expected both '2'"), + depth=1, jump_kind="value", expect="All=2, Recent=2") + # VLM #2 — the count number rendered on the colored 'All' card. + vlm_assert("computation_home_cards_count", + "On this home screen, does the 'All' library card show the number 2 " + "as its note count?", + RESULTS_DIR, depth=1, jump_kind="value", tag="content") + + +@and_test(expects=("computation_folders_count_one",)) +def test_folders_count_one(): + """Creating one user folder turns the HOME folders count '0 Folders' -> + '1 Folder' (SINGULAR; the default 'General' is excluded from this count).""" + fresh_home() + before = read_folders_count() + made = create_folder("Work") + got = read_folders_count() + ok = made and before == "0 Folders" and got == "1 Folder" + record("computation_folders_count_one", ok, + "" if ok else ( + "feature_missing: could not create a folder / read the folders count" + if not made else f"behavior_wrong: folders count was {before!r} -> {got!r}, " + f"expected '0 Folders' -> '1 Folder'"), + depth=1, jump_kind="value", expect="1 Folder") + + +@and_test(expects=("computation_folders_count_two",)) +def test_folders_count_two(): + """A second user folder -> '2 Folders' (plural).""" + fresh_home() + m1 = create_folder("Work") + m2 = create_folder("Home") + got = read_folders_count() + ok = m1 and m2 and got == "2 Folders" + record("computation_folders_count_two", ok, + "" if ok else ( + "feature_missing: could not create two folders / read the count" + if not (m1 and m2) else f"behavior_wrong: folders count shows {got!r}, " + f"expected '2 Folders'"), + depth=1, jump_kind="value", expect="2 Folders") + + +@and_test(expects=("computation_reading_paging", + "computation_reading_paging_vlm")) +def test_reading_paging(): + """With exactly ONE note, Reading Mode's paging indicator reads '1 / 1 Note' + (position / total arithmetic). depth=3: home->folder->note-options->reading. + VLM: confirm the '1 / 1 Note' indicator is rendered in the reading-mode chrome.""" + fresh_home() + made = create_note_general("OnlyNote", "solo body") + got = "" + reached = False + if made and and_enter_folder("General"): + note = node_by_id(ui(), "tv_note_title") + if note is not None and long_press(note): + settle("tap") + if and_reach_note_options() and and_reach_reading_mode(): + reached = True + pn = node_by_id(ui(), "tv_notes_count") + got = (pn.get("content-desc") or "").strip() if pn else "" + ok = reached and got == "1 / 1 Note" + record("computation_reading_paging", ok, + "" if ok else ( + "feature_missing: could not reach Reading Mode / its paging indicator" + if not reached else f"behavior_wrong: paging shows {got!r}, expected '1 / 1 Note'"), + depth=3, jump_kind="value", expect="1 / 1 Note") + # VLM #3 — the rendered paging indicator in the reading-mode header. + vlm_assert("computation_reading_paging", + "In this full-screen reading view, is the paging indicator " + "'1 / 1 Note' displayed (showing you are on note 1 of 1)?", + RESULTS_DIR, depth=3, jump_kind="value", tag="content") + + +# ══════════════════════════════════════════════════════════════════════════════ +TESTS = [ + test_wc_empty, + test_wc_one, + test_wc_two, + test_wc_three, + test_wc_four, + test_wc_five, + test_wc_seven_single_chars, + test_wc_multi_space, + test_wc_lead_trail_space, + test_wc_punctuation, + test_wc_title_excluded_empty, + test_wc_title_excluded_body, + test_folder_count_one, + test_folder_count_two, + test_folder_count_three, + test_home_cards_count, + test_folders_count_one, + test_folders_count_two, + test_reading_paging, +] + +if __name__ == "__main__": + run_suite(TESTS, "computation") diff --git a/android/alialbaali-noto/tests/test_android_interaction.py b/android/alialbaali-noto/tests/test_android_interaction.py new file mode 100644 index 0000000000000000000000000000000000000000..d03e7b59c8e1b90339adef71070e9014084a6e23 --- /dev/null +++ b/android/alialbaali-noto/tests/test_android_interaction.py @@ -0,0 +1,722 @@ +#!/usr/bin/env python3 +"""INTERACTION module — Noto (minimal note-taking app). + +Lane ownership: EFFECT-BY-CONSEQUENCE on user DATA. This lane creates/duplicates/ +edits/moves records, drives 3+ step sequences, asserts multi-record integrity, and +is the SOLE owner of long-press / context menus and of DATA persistence across +process death. Every test drives the app to the surface via the real user path, +performs the action, then reads the consequence back out of a FRESH ui() and +asserts it equals what was observed on the original. + +What this lane does NOT assert (ceded to other lanes): the exact word-count number +(computation), the checked/selected bit or SETTINGS persistence (states), pure +screen reachability (navigation), the exact placeholder/label wording (text), +view-tree shape (structure). Here we assert the DATA changed — a record appeared, +duplicated, moved, or survived a restart. + +VERIFIED LIVE before authoring (the risky ones): + * Folder create: type into `et`, then tap `btn_create` WITH the keyboard up — + this dialog is a full-screen ScrollView and BACK/hide_keyboard dismisses it. + * Note create + auto-save: type title/body -> hide_keyboard() -> back() lands on + the HOME sheet (not the folder); reopen the folder to see the row. + * Note-body edit APPENDS at the cursor (input text does not clear the field), so + to reach 'alpha beta' we start from 'alpha' and type ' beta'. + * Pin: long-press -> `bab_selection` `pin` button -> a "Pinned" section header + (tv_title text="Pinned") APPEARS and the note moves under it. (Deterministic; + the note-options label does NOT reliably flip, so we assert the section.) + * Selection highlight: the selected row is marked by a solid dark filled circular + CHECK badge (NOT a tinted row background — the background stays the same), so + the colour VLM asks about the badge fill, not the row. + * Move: long-press -> `fab_selection` -> `tv_move_note` -> "Move to" picker -> + tap the destination row (single tap commits) -> note LEAVES source, ARRIVES + in destination. + * Duplicate -> 2 identical rows, count +1. Multi-select -> "N Notes • K Selected". + +Invoke: + python3 test_android_interaction.py +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ══════════════════════════════════════════════════════════════════════════════ +# Local setup helpers +# ══════════════════════════════════════════════════════════════════════════════ + +def dismiss_prompts(): + """Dismiss the first-run system notification-permission dialog (and any stray + prompt) sitting in front of the already-loaded Noto home. Both the ASCII + "Don't allow" and the curly-apostrophe "Don't allow" (U+2019) are matched. The + prompt reliably reappears after a full pm clear, but it was observed to return + on a plain relaunch too, so we call this defensively after every launch.""" + for _ in range(3): + nodes = ui() + b = (find_node_ci(nodes, "Don't allow") or find_node_ci(nodes, "Don’t allow") + or find_node_ci(nodes, "Allow")) + if b and is_safe(b): + tap_node(b) + settle("tap") + continue + break + + +def fresh_home(): + """Virgin database (wipe) + HOME sheet. Guarantees the default 'General' + folder exists and counts start at zero, so created records are deterministic.""" + clear_data() + launch_app() + wait_for_foreground() + dismiss_prompts() + return ui() + + +def relaunched_home(): + """Force-stop + relaunch WITHOUT wiping (the persistence probe), then dismiss + any prompt and drive back to the HOME sheet.""" + force_stop_and_relaunch() + wait_for_foreground() + dismiss_prompts() + return goto_home() + + +def goto_home(): + """Back out to the HOME bottom sheet from wherever we are (the sheet is the one + surface that shows the 'Create folder' fab).""" + for _ in range(4): + if find_node(ui(), content_desc="Create folder"): + break + back() + settle("tap") + return ui() + + +# ── Depth-backing navigation helpers (named and_enter_*/and_reach_* so the audit +# can attribute the declared depth to a real navigation call). ──────────────── + +def and_enter_folder(name): + """HOME sheet -> tap a folder row -> its note-list surface. Counts one + surface. Returns True when the folder title is showing.""" + n = find_node(ui(), text=name) + if n is None or not tap_node(n): + return False + settle("tap") + and_enter("folder:" + name) + tit = node_by_id(ui(), "tv_folder_title") + return tit is not None and tit.get("text") == name + + +def and_enter_editor(): + """FOLDER note-list -> tap fab 'Create note' -> the note editor. Counts one + surface. Returns True when et_note_title is present.""" + fab = find_node(ui(), content_desc="Create note") + if fab is None or not tap_node(fab): + return False + settle("tap") + and_enter("editor") + return node_by_id(ui(), "et_note_title") is not None + + +def and_reach_note_options(): + """SELECTION mode -> tap `fab_selection` 'More options' -> the Note options + sheet. Counts one surface. Returns True when 'Note options' title is showing.""" + fs = node_by_id(ui(), "fab_selection") + if fs is None or not tap_node(fs): + return False + settle("tap") + and_enter("note_options") + return find_node_ci(ui(), "Note options") is not None + + +def and_reach_move_picker(): + """Note options sheet -> tap `tv_move_note` 'Move to...' -> the 'Move to' + folder picker. Counts one surface. Returns True when the picker title shows.""" + mv = node_by_id(ui(), "tv_move_note") + if mv is None or not tap_node(mv): + return False + settle("tap") + and_enter("move_picker") + return find_node_ci(ui(), "Move to") is not None + + +# ── Data-authoring helpers built on the navigation helpers. They END on the HOME +# sheet, so callers reopen the folder to read the consequence back. ──────────── + +def create_note(folder, title, body=""): + """Open `folder`, create a note with `title`/`body`, auto-save via + hide_keyboard()+back() (which lands on the HOME sheet). Returns True on + success. Leaves the app on the HOME sheet.""" + if not and_enter_folder(folder): + return False + if not and_enter_editor(): + return False + t = node_by_id(ui(), "et_note_title") + if t is None or not type_text(t, title): + return False + if body: + b = node_by_id(ui(), "et_note_body") + if b is not None: + type_text(b, body) + hide_keyboard() + back() # NEW note Back -> HOME sheet + settle("tap") + goto_home() + return True + + +def create_folder(name): + """HOME sheet -> fab 'Create folder' -> type name into `et` -> tap `btn_create` + (present and tappable WITH the keyboard up; do NOT hide the keyboard, BACK + dismisses this full-screen dialog). Returns True when the folder appears on + HOME. Leaves the app on the HOME sheet.""" + fab = find_node(ui(), content_desc="Create folder") + if fab is None or not tap_node(fab): + return False + settle("tap") + and_enter("new_folder_dialog") + et = node_by_id(ui(), "et") + if et is None or not type_text(et, name): + return False + btn = node_by_id(ui(), "btn_create") or find_node_ci(ui(), "Create folder") + if btn is None or not tap_node(btn): + return False + settle("tap") + goto_home() + return find_node(ui(), text=name) is not None + + +def count_note_rows(nodes, title): + """How many visible note rows have this exact title.""" + return sum(1 for n in nodes + if n.get("resource-id", "").rsplit("/", 1)[-1] == "tv_note_title" + and n.get("text") == title) + + +def first_body_text(nodes): + """The text of the first note-body row, or "".""" + for n in nodes: + if n.get("resource-id", "").rsplit("/", 1)[-1] == "tv_note_body": + return n.get("text", "") + return "" + + +def open_selection(folder, title): + """Open `folder` and long-press the note `title` to enter selection mode. + Returns the selection subtitle content-desc (or None).""" + if not and_enter_folder(folder): + return None + note = find_node(ui(), text=title) + if note is None or not long_press(note): + return None + settle("tap") + sub = node_by_id(ui(), "tv_folder_notes_count") + return sub.get("content-desc") if sub else None + + +# ══════════════════════════════════════════════════════════════════════════════ +# CRUD +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_create_note",)) +def test_create_note(): + """Create a note in 'General' and read its title back from a fresh folder view.""" + fresh_home() + absent = find_node(ui(), text="Groceries") is None + made = create_note("General", "Groceries", "milk eggs") + if not made: + record("interaction_create_note", False, + "feature_missing: could not reach the note editor / create a note", + depth=2, jump_kind="value", expect="note 'Groceries' in list") + return + and_enter_folder("General") + row = find_node(ui(), text="Groceries") + ok = absent and row is not None + record("interaction_create_note", ok, + "" if ok else "behavior_wrong: created note not present in the folder list", + depth=2, jump_kind="value", expect="note 'Groceries' in list") + + +@and_test(expects=("interaction_second_create_two_rows",)) +def test_second_create_yields_two_rows(): + """Two distinct creates in a cleared folder -> BOTH rows present at once + (a recreation that keeps only the last row fails this).""" + fresh_home() + made1 = create_note("General", "FirstNote", "b1") + made2 = create_note("General", "SecondNote", "b2") + if not (made1 and made2): + record("interaction_second_create_two_rows", False, + "feature_missing: could not create two notes", + depth=2, jump_kind="value", expect="both FirstNote & SecondNote present") + return + and_enter_folder("General") + nodes = ui() + ok = (find_node(nodes, text="FirstNote") is not None + and find_node(nodes, text="SecondNote") is not None) + record("interaction_second_create_two_rows", ok, + "" if ok else "behavior_wrong: both notes not present simultaneously", + depth=2, jump_kind="value", expect="both FirstNote & SecondNote present") + + +@and_test(expects=("interaction_multi_record_integrity",)) +def test_multi_record_integrity(): + """Create 3 uniquely-named notes -> all 3 titles present at the same time. + (Row presence is dump-readable, so this stays a rule assertion — no VLM.)""" + fresh_home() + made = (create_note("General", "Note A", "aa") + and create_note("General", "Note B", "bb") + and create_note("General", "Note C", "cc")) + if not made: + record("interaction_multi_record_integrity", False, + "feature_missing: could not create three notes", + depth=2, jump_kind="value", expect="3 notes A/B/C present") + return + and_enter_folder("General") + nodes = ui() + ok = all(find_node(nodes, text=t) is not None + for t in ("Note A", "Note B", "Note C")) + record("interaction_multi_record_integrity", ok, + "" if ok else "behavior_wrong: not all of A/B/C present together", + depth=2, jump_kind="value", expect="3 notes A/B/C present") + + +@and_test(expects=("interaction_duplicate_note", + "interaction_duplicate_note_vlm")) +def test_duplicate_note(): + """Long-press a note -> More options -> Duplicate -> two identical rows.""" + fresh_home() + if not create_note("General", "DupMe", "dupbody"): + record("interaction_duplicate_note", False, + "feature_missing: could not create the note to duplicate", + depth=2, jump_kind="value", expect="two 'DupMe' rows after Duplicate") + record("interaction_duplicate_note_vlm", False, + "setup_failed: could not create the note to duplicate", + depth=2, jump_kind="none", tag="position") + return + if open_selection("General", "DupMe") is None: + record("interaction_duplicate_note", False, + "setup_failed: could not enter selection mode via long-press", + depth=2, jump_kind="value", expect="two 'DupMe' rows after Duplicate") + record("interaction_duplicate_note_vlm", False, + "setup_failed: could not enter selection mode", + depth=2, jump_kind="none", tag="position") + return + before_n = count_note_rows(ui(), "DupMe") + reached = and_reach_note_options() + dup = node_by_id(ui(), "tv_duplicate_note") + if not reached or dup is None or not tap_node(dup): + record("interaction_duplicate_note", False, + "feature_missing: Duplicate action not available in note options", + depth=2, jump_kind="value", expect="two 'DupMe' rows after Duplicate") + record("interaction_duplicate_note_vlm", False, + "setup_failed: Duplicate action not available", + depth=2, jump_kind="none", tag="position") + return + settle("tap") + after_n = count_note_rows(ui(), "DupMe") + ok = before_n == 1 and after_n == 2 + record("interaction_duplicate_note", ok, + "" if ok else f"behavior_wrong: expected 1->2 identical rows, got " + f"{before_n}->{after_n}", + depth=2, jump_kind="value", expect="two 'DupMe' rows after Duplicate") + # Fine-grained: the duplicate sits DIRECTLY adjacent to the original. + vlm_assert("interaction_duplicate_note", + "Are there two note cards with the same title text positioned " + "immediately one above the other (adjacent) in the note list?", + depth=2, jump_kind="value", tag="position") + + +@and_test(expects=("interaction_edit_note_body_persists",)) +def test_edit_note_body_persists(): + """Create a note body 'alpha', reopen it, APPEND ' beta' (input text appends at + the cursor), save, reopen -> body reads 'alpha beta'.""" + fresh_home() + if not create_note("General", "EditMe", "alpha"): + record("interaction_edit_note_body_persists", False, + "feature_missing: could not create the note to edit", + depth=2, jump_kind="value", expect="note body 'alpha beta'") + return + if not and_enter_folder("General"): + record("interaction_edit_note_body_persists", False, + "setup_failed: could not reopen the folder", + depth=2, jump_kind="value", expect="note body 'alpha beta'") + return + row = find_node(ui(), text="EditMe") + if row is None or not tap_node(row): + record("interaction_edit_note_body_persists", False, + "setup_failed: could not open the existing note", + depth=2, jump_kind="value", expect="note body 'alpha beta'") + return + settle("tap") + and_enter("editor") + body = node_by_id(ui(), "et_note_body") + # APPEND to the existing 'alpha': typing lands at the cursor after the text. + if body is None or not type_text(body, " beta"): + record("interaction_edit_note_body_persists", False, + "setup_failed: could not type into the note body", + depth=2, jump_kind="value", expect="note body 'alpha beta'") + return + hide_keyboard() + back() + settle("tap") + goto_home() + and_enter_folder("General") + got = first_body_text(ui()) + ok = got == "alpha beta" + record("interaction_edit_note_body_persists", ok, + "" if ok else f"behavior_wrong: edited body not persisted (got {got!r})", + depth=2, jump_kind="value", expect="note body 'alpha beta'") + + +@and_test(expects=("interaction_create_folder",)) +def test_create_folder(): + """Create a folder 'Projects' -> it appears on the HOME sheet.""" + fresh_home() + absent = find_node(ui(), text="Projects") is None + made = create_folder("Projects") + ok = absent and made + record("interaction_create_folder", ok, + "" if ok else "behavior_wrong: folder 'Projects' not created on HOME", + depth=1, jump_kind="value", expect="folder 'Projects' on HOME") + + +@and_test(expects=("interaction_create_two_folders",)) +def test_create_two_folders(): + """Create two folders -> BOTH 'Projects' and 'Ideas' present on HOME at once.""" + fresh_home() + made1 = create_folder("Projects") + made2 = create_folder("Ideas") + nodes = ui() + ok = (made1 and made2 + and find_node(nodes, text="Projects") is not None + and find_node(nodes, text="Ideas") is not None) + record("interaction_create_two_folders", ok, + "" if ok else "behavior_wrong: both folders not present on HOME", + depth=1, jump_kind="value", expect="both 'Projects' & 'Ideas' on HOME") + + +# ══════════════════════════════════════════════════════════════════════════════ +# DATA persistence across process death (this lane owns these) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_note_survives_process_death",)) +def test_note_survives_process_death(): + """Create note 'Persist1' -> force_stop_and_relaunch() -> reopen 'General' -> + the note is still there. An in-memory-only recreation fails this.""" + fresh_home() + if not create_note("General", "Persist1", "keepme"): + record("interaction_note_survives_process_death", False, + "feature_missing: could not create the note to persist", + depth=1, jump_kind="value", expect="'Persist1' survives restart") + return + relaunched_home() + and_enter_folder("General") + ok = find_node(ui(), text="Persist1") is not None + record("interaction_note_survives_process_death", ok, + "" if ok else "behavior_wrong: note did not survive process death", + depth=1, jump_kind="value", expect="'Persist1' survives restart") + + +@and_test(expects=("interaction_folder_survives_process_death",)) +def test_folder_survives_process_death(): + """Create folder 'KeepMe' -> force_stop_and_relaunch() -> still on HOME.""" + fresh_home() + if not create_folder("KeepMe"): + record("interaction_folder_survives_process_death", False, + "feature_missing: could not create the folder to persist", + depth=0, jump_kind="value", expect="'KeepMe' folder survives restart") + return + relaunched_home() + ok = find_node(ui(), text="KeepMe") is not None + record("interaction_folder_survives_process_death", ok, + "" if ok else "behavior_wrong: folder did not survive process death", + depth=0, jump_kind="value", expect="'KeepMe' folder survives restart") + + +@and_test(expects=("interaction_edited_body_survives_process_death",)) +def test_edited_body_survives_process_death(): + """Create a note with a distinctive body marker, save, then + force_stop_and_relaunch() and reopen the folder -> body still reads the marker. + The strongest probe: an in-memory-only recreation cannot pass it.""" + fresh_home() + if not create_note("General", "PersistBody", "saved body xyz"): + record("interaction_edited_body_survives_process_death", False, + "feature_missing: could not create the note", + depth=1, jump_kind="value", expect="body 'saved body xyz' after restart") + return + relaunched_home() + if not and_enter_folder("General"): + record("interaction_edited_body_survives_process_death", False, + "setup_failed: could not reopen the folder after restart", + depth=1, jump_kind="value", expect="body 'saved body xyz' after restart") + return + got = first_body_text(ui()) + ok = got == "saved body xyz" + record("interaction_edited_body_survives_process_death", ok, + "" if ok else f"behavior_wrong: note body not persisted across restart " + f"(got {got!r})", + depth=1, jump_kind="value", expect="body 'saved body xyz' after restart") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Long-press / selection sequences (sole owner) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_multi_select_count", + "interaction_selection_check_dark_vlm", + "interaction_selection_check_badge_vlm", + "interaction_selection_action_bar_vlm")) +def test_multi_select_count(): + """Long-press one note (1 Selected) then tap a second note -> subtitle + '2 Notes • 2 Selected'. Multi-select COUNT sequence via long-press.""" + fresh_home() + made = (create_note("General", "SelA", "sa") + and create_note("General", "SelB", "sb")) + if not made: + record("interaction_multi_select_count", False, + "feature_missing: could not create two notes", + depth=1, jump_kind="transition", expect="2 selected") + for nm, tg in (("interaction_selection_check_dark_vlm", "color"), + ("interaction_selection_check_badge_vlm", "shape"), + ("interaction_selection_action_bar_vlm", "layout")): + record(nm, False, "setup_failed: could not create two notes", + depth=1, jump_kind="none", tag=tg) + return + sub1 = open_selection("General", "SelA") + one_ok = sub1 is not None and "1 Selected" in sub1 + # VLM (single-selection visual state): the selection is marked by a solid dark + # filled CHECK badge on the selected row (the row background does NOT tint), an + # action bar renders along the bottom. + vlm_assert("interaction_selection_check_dark", + "The selected note row shows a small circular check/tick badge in " + "its corner: is that badge a SOLID DARK/BLACK filled circle (not a " + "hollow outline)?", + depth=1, jump_kind="transition", tag="color") + vlm_assert("interaction_selection_check_badge", + "Does exactly one note row show a filled circular check/tick badge " + "in its corner marking it as selected, while the other row has none?", + depth=1, jump_kind="transition", tag="shape") + vlm_assert("interaction_selection_action_bar", + "Is a bottom action bar with several selection action icons " + "(reminder, pin, share, archive and a more-options button) rendered " + "along the bottom of the screen?", + depth=1, jump_kind="transition", tag="layout") + # add the second note to the selection + second = find_node(ui(), text="SelB") + if second is not None: + tap_node(second) + settle("tap") + sub2n = node_by_id(ui(), "tv_folder_notes_count") + sub2 = sub2n.get("content-desc") if sub2n else "" + two_ok = "2 Selected" in (sub2 or "") + ok = one_ok and two_ok + record("interaction_multi_select_count", ok, + "" if ok else f"behavior_wrong: multi-select count wrong " + f"(1st={sub1!r}, 2nd={sub2!r})", + depth=1, jump_kind="transition", expect="2 selected") + + +@and_test(expects=("interaction_pin_note", + "interaction_pinned_section_vlm")) +def test_pin_note(): + """Create two notes, long-press one, tap the selection-bar `pin` -> a 'Pinned' + section header APPEARS and the pinned note sits above the 'Notes' header. + (Verified live: the note-options label does not reliably toggle, but the + 'Pinned' section is a deterministic, dump-readable DATA consequence.)""" + fresh_home() + made = (create_note("General", "PinTop", "pt") + and create_note("General", "PlainNote", "pn")) + if not made: + record("interaction_pin_note", False, + "feature_missing: could not create notes to pin", + depth=1, jump_kind="transition", expect="'Pinned' section appears") + record("interaction_pinned_section_vlm", False, + "setup_failed: could not create notes to pin", + depth=1, jump_kind="none", tag="position") + return + if open_selection("General", "PinTop") is None: + record("interaction_pin_note", False, + "setup_failed: could not enter selection mode via long-press", + depth=1, jump_kind="transition", expect="'Pinned' section appears") + record("interaction_pinned_section_vlm", False, + "setup_failed: could not enter selection mode", + depth=1, jump_kind="none", tag="position") + return + before_pinned = find_node(ui(), text="Pinned") is not None # in folder: false + pinbtn = node_by_id(ui(), "pin") + if pinbtn is None or (pinbtn.get("content-desc") or "").lower() != "pin" \ + or not tap_node(pinbtn): + record("interaction_pin_note", False, + "feature_missing: Pin action not available in the selection bar", + depth=1, jump_kind="transition", expect="'Pinned' section appears") + record("interaction_pinned_section_vlm", False, + "setup_failed: Pin action not available", + depth=1, jump_kind="none", tag="position") + return + settle("tap") + nodes = ui() + pinned_hdr = find_node(nodes, text="Pinned") + after_pinned = pinned_hdr is not None + # the pinned note must sit above the plain note (pinned section on top) + order_ok = True + pin_row = find_node(nodes, text="PinTop") + plain_row = find_node(nodes, text="PlainNote") + if pinned_hdr and pin_row and plain_row and "_bounds" in pin_row \ + and "_bounds" in plain_row: + order_ok = pin_row["_bounds"][1] < plain_row["_bounds"][1] + ok = (not before_pinned) and after_pinned and order_ok + record("interaction_pin_note", ok, + "" if ok else "behavior_wrong: pinning did not add a 'Pinned' section " + "with the note on top", + depth=1, jump_kind="transition", expect="'Pinned' section appears") + vlm_assert("interaction_pinned_section", + "Is there a 'Pinned' section heading near the top of the note list " + "with a note shown directly beneath it, positioned above the rest of " + "the notes?", + depth=1, jump_kind="transition", tag="position") + + +@and_test(expects=("interaction_note_options_grid_vlm",)) +def test_note_options_grid_vlm(): + """Reach the Note-options sheet and VLM its grid of labeled action tiles.""" + fresh_home() + if not create_note("General", "OptNote", "on"): + record("interaction_note_options_grid_vlm", False, + "setup_failed: could not create the note", + depth=2, jump_kind="none", tag="layout") + return + if open_selection("General", "OptNote") is None or not and_reach_note_options(): + record("interaction_note_options_grid_vlm", False, + "setup_failed: could not reach the Note options sheet", + depth=2, jump_kind="none", tag="layout") + return + vlm_assert("interaction_note_options_grid", + "Does this bottom sheet titled 'Note options' show a grid/list of " + "several labeled action tiles such as Add reminder, Reading Mode, " + "Pin, Share, Archive, Duplicate, Copy, Move to and Delete?", + depth=2, jump_kind="value", tag="layout") + + +@and_test(expects=("interaction_move_note_between_folders",)) +def test_move_note_between_folders(): + """Create a 2nd folder, create a note in 'General', then long-press -> + More options -> Move to... -> pick the 2nd folder. Assert the note LEFT + 'General' AND ARRIVED in the destination (multi-record integrity across + folders).""" + fresh_home() + made_folder = create_folder("Dest") + made_note = create_note("General", "MoveMe", "mv") + if not (made_folder and made_note): + record("interaction_move_note_between_folders", False, + "feature_missing: could not create the folder or note for a move", + depth=2, jump_kind="value", expect="MoveMe left General, in Dest") + return + if open_selection("General", "MoveMe") is None or not and_reach_note_options(): + record("interaction_move_note_between_folders", False, + "setup_failed: could not reach note options for the move", + depth=2, jump_kind="value", expect="MoveMe left General, in Dest") + return + if not and_reach_move_picker(): + record("interaction_move_note_between_folders", False, + "feature_missing: 'Move to' picker did not open", + depth=2, jump_kind="value", expect="MoveMe left General, in Dest") + return + dest = find_node(ui(), text="Dest") + if dest is None or not tap_node(dest): + record("interaction_move_note_between_folders", False, + "behavior_wrong: destination folder 'Dest' not listed in the picker", + depth=2, jump_kind="value", expect="MoveMe left General, in Dest") + return + settle("tap") + # assert it LEFT General + goto_home() + left = False + if and_enter_folder("General"): + left = find_node(ui(), text="MoveMe") is None + # assert it ARRIVED in Dest + goto_home() + arrived = False + if and_enter_folder("Dest"): + arrived = find_node(ui(), text="MoveMe") is not None + ok = left and arrived + record("interaction_move_note_between_folders", ok, + "" if ok else f"behavior_wrong: move failed (left_General={left}, " + f"arrived_Dest={arrived})", + depth=2, jump_kind="value", expect="MoveMe left General, in Dest") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3+ step sequence across a freshly created folder +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_new_folder_note_roundtrip",)) +def test_new_folder_note_roundtrip(): + """Create folder 'Trip' -> open it -> create note 'Day1' in it -> back to HOME + -> reopen 'Trip' -> 'Day1' present. Multi-step CRUD across a fresh folder.""" + fresh_home() + if not create_folder("Trip"): + record("interaction_new_folder_note_roundtrip", False, + "feature_missing: could not create the folder", + depth=2, jump_kind="value", expect="'Day1' in fresh folder 'Trip'") + return + if not create_note("Trip", "Day1", "d1"): + record("interaction_new_folder_note_roundtrip", False, + "feature_missing: could not create a note in the new folder", + depth=2, jump_kind="value", expect="'Day1' in fresh folder 'Trip'") + return + goto_home() + ok = False + if and_enter_folder("Trip"): + ok = find_node(ui(), text="Day1") is not None + record("interaction_new_folder_note_roundtrip", ok, + "" if ok else "behavior_wrong: 'Day1' not present in freshly created " + "folder 'Trip'", + depth=2, jump_kind="value", expect="'Day1' in fresh folder 'Trip'") + + +@and_test(expects=("interaction_created_note_card_vlm",)) +def test_created_note_card_vlm(): + """After creating a note, its card renders with the title text larger/bolder + ABOVE the body-preview text.""" + fresh_home() + if not create_note("General", "CardTitle", "card body preview"): + record("interaction_created_note_card_vlm", False, + "setup_failed: could not create the note", + depth=2, jump_kind="none", tag="size") + return + if not and_enter_folder("General"): + record("interaction_created_note_card_vlm", False, + "setup_failed: could not reopen the folder", + depth=2, jump_kind="none", tag="size") + return + vlm_assert("interaction_created_note_card", + "In the note card, is the title line ('CardTitle') rendered in a " + "LARGER or bolder font than, and positioned above, the body-preview " + "line ('card body preview')?", + depth=2, jump_kind="value", tag="size") + + +# ══════════════════════════════════════════════════════════════════════════════ + +TESTS = [ + test_create_note, + test_second_create_yields_two_rows, + test_multi_record_integrity, + test_duplicate_note, + test_edit_note_body_persists, + test_create_folder, + test_create_two_folders, + test_note_survives_process_death, + test_folder_survives_process_death, + test_edited_body_survives_process_death, + test_multi_select_count, + test_pin_note, + test_note_options_grid_vlm, + test_move_note_between_folders, + test_new_folder_note_roundtrip, + test_created_note_card_vlm, +] + +if __name__ == "__main__": + run_suite(TESTS, "interaction") diff --git a/android/alialbaali-noto/tests/test_android_navigation.py b/android/alialbaali-noto/tests/test_android_navigation.py new file mode 100644 index 0000000000000000000000000000000000000000..06284eda5180868fe2060ddb9e9a84770a516b06 --- /dev/null +++ b/android/alialbaali-noto/tests/test_android_navigation.py @@ -0,0 +1,589 @@ +#!/usr/bin/env python3 +"""NAVIGATION module — Noto (minimal note-taking app). + +Lane ownership: surface REACHABILITY and back-stack integrity. This lane is the +SOLE owner of jump_kind="reach" and of depth>=2 chains. Every jump is proven with +and_reach(before, after, target, source): the TARGET surface's discriminating +element APPEARED and the SOURCE surface's element DISAPPEARED. A screen that was +in the dump all along was never reached. Reaching a screen by relaunching the app +is NOT navigation and is never done here. + +No content values, no checked/selected state, no exact-string content assertions — +those belong to other lanes. This file only asserts that we ARRIVED and LEFT. + +Invoke: + python3 test_android_navigation.py +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ── Local prompt handling ──────────────────────────────────────────────────── +def dismiss_prompts(): + """Dismiss the first-run system notification-permission dialog (and any stray + prompt) sitting in front of the already-loaded Noto home. The curly-apostrophe + "Don’t allow" (U+2019) and the ASCII form are both matched.""" + for _ in range(3): + nodes = ui() + b = (find_node_ci(nodes, "Don't allow") or find_node_ci(nodes, "Don’t allow") + or find_node_ci(nodes, "Allow")) + if b and is_safe(b): + tap_node(b) + settle("tap") + continue + break + + +def open_home(): + """Every test's clean entry point: relaunch (data kept), wait for the app to + foreground, dismiss the perm prompt, return the HOME-sheet node tree.""" + restart_app() + wait_for_foreground() + dismiss_prompts() + return ui() + + +def fresh_home(): + """Virgin state (wipe data) + HOME sheet — used once to guarantee the default + 'General' folder exists before we seed a note for the deep chains.""" + clear_data() + launch_app() + wait_for_foreground() + dismiss_prompts() + return ui() + + +# ── One seeded note so the selection / note-options / reading-mode chains have a +# record to navigate to. We CREATE it in setup, then assert the JUMP, never the +# creation (that belongs to the interaction lane). ─────────────────────────── +SEED_BODY = "noto nav seed note" + + +def ensure_seed_note(): + """Guarantee at least one note exists in the default 'General' folder, so the + deep chains have a row to long-press. Idempotent enough: if a note is already + present we leave it. Returns True when a note row is visible in the folder.""" + open_home() + nodes = ui() + g = find_node(nodes, text="General") + if g is None or not tap_node(g): + return False + settle("tap") + nodes = ui() + if find_by_class(nodes, "") and (node_by_id(nodes, "tv_note_body") + or node_by_id(nodes, "tv_note_title")): + return True + # No note yet — create one via the folder fab, type a body, back out to save. + fab = node_by_id(nodes, "fab") or find_node(nodes, content_desc="Create note") + if fab is None or not tap_node(fab): + return False + settle("tap") + body = node_by_id(ui(), "et_note_body") + if body is not None: + type_text(body, SEED_BODY) + hide_keyboard() + back() # new-note Back persists and returns to the HOME sheet + settle("tap") + dismiss_prompts() + nodes = ui() + g = find_node(nodes, text="General") + if g is None or not tap_node(g): + return False + settle("tap") + nodes = ui() + return (node_by_id(nodes, "tv_note_body") is not None + or node_by_id(nodes, "tv_note_title") is not None) + + +# ══════════════════════════════════════════════════════════════════════════════ +# Depth-family helpers — the and_enter_*/and_reach_* NAME is what the depth audit +# looks for. Each performs the hops and (for and_reach_*) proves the jump. +# ══════════════════════════════════════════════════════════════════════════════ + +def and_reach_folder(nodes=None, name="General"): + """HOME sheet -> tap a folder row -> FOLDER note-list. Proven reach: the + folder fab 'Create note' appears, the sheet title 'Noto Debug' vanishes.""" + nodes = ui() if nodes is None else nodes + row = find_node(nodes, text=name) + if row is None: + return False + return and_reach_surface(row, "Create note", "Noto Debug") + + +def and_enter_folder(nodes=None, name="General"): + """Land on a folder note-list, tolerating that it may already be showing. + Returns (ok, nodes). Used as the first hop of the deeper chains where the + per-hop reach is asserted by the caller's final and_reach.""" + nodes = ui() if nodes is None else nodes + row = find_node(nodes, text=name) + if row is None: + return False, nodes + if not tap_node(row): + return False, nodes + and_enter("folder") + return True, ui() + + +def and_enter_editor(nodes=None): + """FOLDER -> fab 'Create note' -> NOTE editor. Returns (ok, nodes).""" + nodes = ui() if nodes is None else nodes + fab = node_by_id(nodes, "fab") or find_node(nodes, content_desc="Create note") + if fab is None or not tap_node(fab): + return False, nodes + and_enter("editor") + return True, ui() + + +def and_enter_settings(nodes=None): + """HOME -> ib_settings -> SETTINGS (Compose). Returns (ok, nodes).""" + nodes = ui() if nodes is None else nodes + btn = node_by_id(nodes, "ib_settings") or find_node(nodes, content_desc="Settings") + if btn is None or not tap_node(btn): + return False, nodes + and_enter("settings") + return True, ui() + + +def and_reach_settings(nodes=None): + """HOME -> ib_settings -> SETTINGS, proven: a Settings-only row ('About') + appears and the HOME sheet title 'Noto Debug' vanishes. Counts one surface.""" + nodes = ui() if nodes is None else nodes + btn = node_by_id(nodes, "ib_settings") or find_node(nodes, content_desc="Settings") + if btn is None: + return False + return and_reach_surface(btn, "About", "Noto Debug") + + +def and_enter_general_settings(nodes=None): + """SETTINGS -> 'General' row -> GENERAL settings (Compose). Returns (ok, nodes).""" + nodes = ui() if nodes is None else nodes + row = find_node_ci(nodes, "General") + if row is None or not tap_node(row): + return False, nodes + and_enter("general") + return True, ui() + + +def and_reach_selection(nodes=None): + """FOLDER -> long-press a note row -> selection mode. Proven by the selection + subtitle ('… Selected') appearing. Counts one surface. Returns (ok, nodes).""" + nodes = ui() if nodes is None else nodes + note = (find_node(nodes, text=SEED_BODY) + or node_by_id(nodes, "tv_note_body") + or node_by_id(nodes, "tv_note_title")) + if note is None: + return False, nodes + before = and_showing(nodes) + long_press(note) + settle("tap") + after = and_showing() + if not and_reach(before, after, "Selected"): + return False, ui() + and_enter("selection") + return True, ui() + + +def and_reach_note_options(nodes=None): + """selection mode -> fab_selection 'More options' -> NOTE options sheet. + Proven: 'Note options' title appears, the 'Selected' subtitle vanishes.""" + nodes = ui() if nodes is None else nodes + fs = node_by_id(nodes, "fab_selection") or find_node(nodes, content_desc="More options") + if fs is None: + return False + return and_reach_surface(fs, "Note options", "Selected") + + +def and_reach_reading_mode(nodes=None): + """NOTE options -> 'Reading Mode' -> READING MODE. A first-run SYSTEM immersive + cling ('Got it') may appear over it; dismiss it if present, then prove the + reach by the paging arrow 'Next' being visible and 'Note options' gone.""" + nodes = ui() if nodes is None else nodes + rm = node_by_id(nodes, "tv_open_in") or find_node_ci(nodes, "Reading Mode") + if rm is None: + return False + before = and_showing(nodes) + if not tap_node(rm): + return False + settle("tap") + got = find_node_ci(ui(), "Got it") + if got is not None: + tap_node(got) + settle("tap") + after = and_showing() + ok = and_reach(before, after, "Next", "Note options") + if ok: + and_enter("reading") + return ok + + +# ══════════════════════════════════════════════════════════════════════════════ +# depth=1 reaches — top-level destinations +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_folder",)) +def test_reach_folder(): + open_home() + ok = and_reach_folder() + record("nav_reach_folder", ok, + "" if ok else "feature_missing: HOME folder row did not open the note-list", + depth=1, jump_kind="reach", + expect="folder note-list shown (fab 'Create note' appeared); " + "HOME sheet title 'Noto Debug' gone") + + +@and_test(expects=("nav_reach_home_from_folder",)) +def test_reach_home_from_folder(): + open_home() + ok_f, nodes = and_enter_folder() + ham = find_node(nodes, content_desc="Folders") if ok_f else None + ok = ok_f and ham is not None and and_reach_surface(ham, "Noto Debug", "Create note") + record("nav_reach_home_from_folder", ok, + "" if ok else "behavior_wrong: 'Folders' hamburger did not return to the HOME sheet", + depth=1, jump_kind="reach", + expect="HOME sheet title 'Noto Debug' reappeared; folder fab 'Create note' gone") + + +@and_test(expects=("nav_reach_settings", "nav_reach_settings_vlm")) +def test_reach_settings(): + open_home() + ok = and_reach_settings() + record("nav_reach_settings", ok, + "" if ok else "feature_missing: no reachable Settings surface", + depth=1, jump_kind="reach", + expect="Settings surface visible ('About' row appeared); 'Noto Debug' gone") + vlm_assert("nav_reach_settings", + "Is a settings screen showing a vertical list of labelled rows, " + "each row with a small leading icon on its left?", + RESULTS_DIR, depth=1, jump_kind="reach", tag="layout") + + +@and_test(expects=("nav_reach_recent",)) +def test_reach_recent(): + open_home() + nodes = ui() + card = find_node(nodes, text="Recent") + ok = card is not None and and_reach_surface(card, "Today", "Noto Debug") + record("nav_reach_recent", ok, + "" if ok else "feature_missing: 'Recent' library card did not open the Recent screen", + depth=1, jump_kind="reach", + expect="Recent screen shown (grouping header 'Today' appeared); " + "HOME sheet 'Noto Debug' gone") + + +@and_test(expects=("nav_reach_all",)) +def test_reach_all(): + open_home() + nodes = ui() + card = find_node(nodes, text="All") + ok = card is not None and and_reach_surface(card, "Collapse", "Noto Debug") + record("nav_reach_all", ok, + "" if ok else "feature_missing: 'All' library card did not open the All-notes screen", + depth=1, jump_kind="reach", + expect="All-notes screen shown (bottom-bar 'Collapse' appeared); 'Noto Debug' gone") + + +@and_test(expects=("nav_reach_archived",)) +def test_reach_archived(): + open_home() + nodes = ui() + card = find_node(nodes, text="Archived") + ok = card is not None and and_reach_surface(card, "Collapse", "Noto Debug") + record("nav_reach_archived", ok, + "" if ok else "feature_missing: 'Archived' library card did not open the Archived screen", + depth=1, jump_kind="reach", + expect="Archived screen shown (bottom-bar 'Collapse' appeared); 'Noto Debug' gone") + + +@and_test(expects=("nav_reach_more_menu", "nav_reach_more_menu_vlm")) +def test_reach_more_menu(): + open_home() + nodes = ui() + more = node_by_id(nodes, "ib_more") or find_node(nodes, content_desc="More options") + ok = more is not None and and_reach_surface(more, "Folders vault", "Create folder") + record("nav_reach_more_menu", ok, + "" if ok else "feature_missing: 'More options' did not open the home more menu", + depth=1, jump_kind="reach", + expect="home more menu shown ('Folders vault' appeared); HOME fab 'Create folder' gone") + vlm_assert("nav_reach_more_menu", + "Is a small menu sheet showing a short vertical list of text entries " + "(vault / archive / settings), overlaying the screen near the bottom?", + RESULTS_DIR, depth=1, jump_kind="reach", tag="layout") + + +@and_test(expects=("nav_reach_search",)) +def test_reach_search(): + open_home() + ok_f, nodes = and_enter_folder() + srch = node_by_id(nodes, "search") or find_node(nodes, content_desc="Search") if ok_f else None + ok = ok_f and srch is not None and and_reach_surface(srch, "til_search", "Folder options") + record("nav_reach_search", ok, + "" if ok else "feature_missing: folder 'Search' did not open the in-folder search field", + depth=1, jump_kind="reach", + expect="in-folder search field (til_search) appeared; folder 'Folder options' action gone") + + +@and_test(expects=("nav_reach_notes_view", "nav_reach_notes_view_vlm")) +def test_reach_notes_view(): + open_home() + ok_f, nodes = and_enter_folder() + nv = node_by_id(nodes, "notes_view") or find_node(nodes, content_desc="Notes view") if ok_f else None + ok = ok_f and nv is not None and and_reach_surface(nv, "Apply", "Create note") + record("nav_reach_notes_view", ok, + "" if ok else "feature_missing: 'Notes view' did not open the sort/filter dialog", + depth=1, jump_kind="reach", + expect="Notes-view dialog shown ('Apply' appeared); folder fab 'Create note' gone") + vlm_assert("nav_reach_notes_view", + "Is a bottom sheet dialog anchored to the lower portion of the screen, " + "overlaying a dimmed screen behind it?", + RESULTS_DIR, depth=1, jump_kind="reach", tag="position") + + +@and_test(expects=("nav_reach_folder_options",)) +def test_reach_folder_options(): + open_home() + ok_f, nodes = and_enter_folder() + more = node_by_id(nodes, "more") or find_node(nodes, content_desc="Folder options") if ok_f else None + ok = ok_f and more is not None and and_reach_surface(more, "New note shortcut", "Create note") + record("nav_reach_folder_options", ok, + "" if ok else "feature_missing: 'Folder options' did not open the folder options sheet", + depth=1, jump_kind="reach", + expect="folder-options sheet shown ('New note shortcut' appeared); fab 'Create note' gone") + + +# ══════════════════════════════════════════════════════════════════════════════ +# depth>=2 chains — this lane owns these +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_chain_editor", "nav_chain_editor_vlm")) +def test_chain_home_folder_editor(): + """HOME -> General folder -> NOTE editor (two hops); assert the final jump.""" + open_home() + ok_f, nodes = and_enter_folder() # hop 1 + ok = False + if ok_f: + fab = node_by_id(nodes, "fab") or find_node(nodes, content_desc="Create note") + ok = fab is not None and and_reach_surface(fab, "Body", "Create note") # hop 2 + record("nav_chain_editor", ok, + "" if ok else "behavior_wrong: HOME->folder->editor chain did not reach the note editor", + depth=2, jump_kind="reach", + expect="note editor shown (Body field appeared); folder fab 'Create note' gone") + vlm_assert("nav_chain_editor", + "Is there a back-arrow icon at the very top-left of the screen, next to " + "the folder title in the toolbar?", + RESULTS_DIR, depth=2, jump_kind="reach", tag="position") + + +@and_test(expects=("nav_chain_general_settings",)) +def test_chain_home_settings_general(): + """HOME -> Settings -> General settings (two hops).""" + open_home() + ok_s, nodes = and_enter_settings() # hop 1 + ok = False + if ok_s: + gen = find_node_ci(nodes, "General") + ok = gen is not None and and_reach_surface(gen, "Theme", "Support Noto") # hop 2 + record("nav_chain_general_settings", ok, + "" if ok else "behavior_wrong: Settings->General chain did not reach General settings", + depth=2, jump_kind="reach", + expect="General settings shown ('Theme' row appeared); Settings-only 'Support Noto' gone") + + +@and_test(expects=("nav_chain_theme_dialog",)) +def test_chain_theme_dialog(): + """HOME -> Settings -> General -> THEME dialog (three hops).""" + open_home() + ok_s, nodes = and_enter_settings() # hop 1 + ok_g, nodes = (and_enter_general_settings(nodes) if ok_s else (False, nodes)) # hop 2 + ok = False + if ok_g: + theme = find_node_ci(nodes, "Theme") + ok = theme is not None and and_reach_surface(theme, "Light", "Language") # hop 3 + record("nav_chain_theme_dialog", ok, + "" if ok else "behavior_wrong: General->Theme chain did not open the Theme dialog", + depth=3, jump_kind="reach", + expect="Theme dialog shown (option 'Light' appeared); General row 'Language' gone") + + +@and_test(expects=("nav_chain_note_options",)) +def test_chain_note_options(): + """FOLDER -> long-press note -> selection -> NOTE options sheet (two hops from + the folder). The note we navigate to is CREATED in setup; we assert the jump.""" + if not ensure_seed_note(): + record("nav_chain_note_options", False, + "setup_failed: could not create/reach a note row to long-press", + depth=2, jump_kind="reach", + expect="Note-options sheet shown after long-press -> More options") + return + ok_sel, nodes = and_reach_selection() # hop 1: folder -> selection + ok = ok_sel and and_reach_note_options(nodes) # hop 2: selection -> note options + record("nav_chain_note_options", ok, + "" if ok else "behavior_wrong: long-press -> More options did not open the Note-options sheet", + depth=2, jump_kind="reach", + expect="Note-options sheet shown ('Note options' title appeared); " + "selection subtitle '… Selected' gone") + + +@and_test(expects=("nav_chain_reading_mode", "nav_chain_reading_mode_vlm")) +def test_chain_reading_mode(): + """NOTE options -> 'Reading Mode' -> READING MODE (three hops from the folder).""" + if not ensure_seed_note(): + record("nav_chain_reading_mode", False, + "setup_failed: could not create/reach a note row to long-press", + depth=3, jump_kind="reach", + expect="Reading Mode shown (paging arrow 'Next' appeared)") + vlm_assert("nav_chain_reading_mode", + "Is there a solid black rounded-square button with a white pencil " + "icon centered along the very bottom of the screen, with a small " + "paging arrow to its left and another to its right?", + RESULTS_DIR, depth=3, jump_kind="reach", tag="position") + return + ok_sel, nodes = and_reach_selection() # hop 1 + ok_opts = ok_sel and and_reach_note_options(nodes) # hop 2 + ok = ok_opts and and_reach_reading_mode() # hop 3 + record("nav_chain_reading_mode", ok, + "" if ok else "behavior_wrong: 'Reading Mode' did not open the read-only reader", + depth=3, jump_kind="reach", + expect="Reading Mode shown (paging arrow 'Next' appeared); 'Note options' gone") + vlm_assert("nav_chain_reading_mode", + "Is there a solid black rounded-square button with a white pencil icon " + "centered along the very bottom of the screen, with a small paging arrow " + "to its left and another to its right?", + RESULTS_DIR, depth=3, jump_kind="reach", tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Back-stack integrity — the reverse jump proven by and_reach on BACK +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_back_editor_to_home",)) +def test_back_editor_to_home(): + """From a NEW note (fab 'Create note'), BACK returns to the HOME sheet.""" + open_home() + ok_f, nodes = and_enter_folder() # hop 1 + ok_e, nodes = (and_enter_editor(nodes) if ok_f else (False, nodes)) # hop 2 + ok = False + if ok_e: + # Snapshot the editor surface WHILE its fields are still present. hide_keyboard() + # perturbs the tree, so capturing `before` after it would miss the Body field. + before = and_showing(nodes) + hide_keyboard() # keyboard-up BACK only dismisses the IME + and_back() # pop editor -> HOME sheet + after = and_showing() + ok = and_reach(before, after, "Noto Debug", "Body") + record("nav_back_editor_to_home", ok, + "" if ok else "behavior_wrong: BACK from a new note did not return to the HOME sheet", + depth=2, jump_kind="reach", + expect="HOME sheet 'Noto Debug' restored after BACK; editor Body field gone") + + +@and_test(expects=("nav_back_settings_to_folder",)) +def test_back_settings_to_folder(): + """Settings BACK returns to the FOLDER note-list that was behind the sheet.""" + open_home() + ok_s, nodes = and_enter_settings() # hop 1 (settings opened over the folder) + ok = False + if ok_s: + before = and_showing(nodes) + and_back() # pop settings + after = and_showing() + ok = and_reach(before, after, "Create note", "About") + record("nav_back_settings_to_folder", ok, + "" if ok else "behavior_wrong: BACK from Settings did not return to the folder note-list", + depth=1, jump_kind="reach", + expect="folder fab 'Create note' restored after BACK; Settings 'About' gone") + + +@and_test(expects=("nav_back_general_to_settings",)) +def test_back_general_to_settings(): + """General-settings BACK returns to the Settings list.""" + open_home() + ok_s, nodes = and_enter_settings() # hop 1 + ok_g, nodes = (and_enter_general_settings(nodes) if ok_s else (False, nodes)) # hop 2 + ok = False + if ok_g: + before = and_showing(nodes) + and_back() # pop general -> settings + after = and_showing() + ok = and_reach(before, after, "Support Noto", "Theme") + record("nav_back_general_to_settings", ok, + "" if ok else "behavior_wrong: BACK from General did not return to Settings", + depth=2, jump_kind="reach", + expect="Settings 'Support Noto' restored after BACK; General 'Theme' row gone") + + +@and_test(expects=("nav_back_reading_to_folder",)) +def test_back_reading_to_folder(): + """Reading-mode BACK returns to the folder note-list.""" + if not ensure_seed_note(): + record("nav_back_reading_to_folder", False, + "setup_failed: could not create/reach a note row to long-press", + depth=3, jump_kind="reach", + expect="folder note-list restored after BACK from Reading Mode") + return + ok_sel, nodes = and_reach_selection() # hop 1 + ok_opts = ok_sel and and_reach_note_options(nodes) # hop 2 + ok_read = ok_opts and and_reach_reading_mode() # hop 3 + ok = False + if ok_read: + before = and_showing() + and_back() # pop reading -> folder + after = and_showing() + ok = and_reach(before, after, "Create note", "Next") + record("nav_back_reading_to_folder", ok, + "" if ok else "behavior_wrong: BACK from Reading Mode did not return to the folder", + depth=3, jump_kind="reach", + expect="folder fab 'Create note' restored after BACK; reading-mode 'Next' arrow gone") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Extra VLM — the visual chrome that confirms arrival beyond the dump +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_folder_bottom_bar_vlm",)) +def test_folder_bottom_bar_vlm(): + open_home() + ok_f = and_reach_folder() + if not ok_f: + record("nav_folder_bottom_bar_vlm", False, + "setup_failed: could not reach a folder to photograph its bottom bar", + depth=1, jump_kind="reach", tag="layout") + return + vlm_assert("nav_folder_bottom_bar", + "Is there a horizontal row of action icons along the bottom of the " + "screen (a menu/hamburger, a plus/add, and search), forming a bottom app bar?", + RESULTS_DIR, depth=1, jump_kind="reach", tag="layout") + + +TESTS = [ + # depth=1 reaches + test_reach_folder, + test_reach_home_from_folder, + test_reach_settings, + test_reach_recent, + test_reach_all, + test_reach_archived, + test_reach_more_menu, + test_reach_search, + test_reach_notes_view, + test_reach_folder_options, + # depth>=2 chains + test_chain_home_folder_editor, + test_chain_home_settings_general, + test_chain_theme_dialog, + test_chain_note_options, + test_chain_reading_mode, + # back-stack integrity + test_back_editor_to_home, + test_back_settings_to_folder, + test_back_general_to_settings, + test_back_reading_to_folder, + # extra VLM chrome + test_folder_bottom_bar_vlm, +] + + +if __name__ == "__main__": + run_suite(TESTS, "navigation") diff --git a/android/alialbaali-noto/tests/test_android_states.py b/android/alialbaali-noto/tests/test_android_states.py new file mode 100644 index 0000000000000000000000000000000000000000..a9f7cd85e26e30769d7d7202b86665815cd8d723 --- /dev/null +++ b/android/alialbaali-noto/tests/test_android_states.py @@ -0,0 +1,959 @@ +#!/usr/bin/env python3 +"""STATES module — Noto (minimal note-taking app). + +Lane ownership: STATE CHANGE. This module is the SOLE owner of `checked`, +`selected`, `focused`, of conditional enable/disable, of page-level state machines, +and of SETTINGS / MODE PERSISTENCE across process death. Every test reads a state +BEFORE from a fresh ui(), drives the app through the real user path, reads AFTER, +asserts the flip, AND asserts the app-authored consequence — then restores. + +What this lane does NOT assert (ceded to other lanes): whether a record survives +(interaction/data), the numeric word/note count (computation), pure reachability +(navigation), the exact wording of a label/placeholder (text), view-tree shape +(structure). Here we assert a STATE FLIP (before -> after) plus what the app did. + +VERIFIED LIVE before authoring (the risky ones): + * Editor undo/redo enable: a FRESH note has ib_undo/ib_redo/ib_undo_history all + enabled="false"; after typing ONE char into et_note_body, ib_undo flips to + enabled="true" while ib_redo and ib_undo_history STAY "false". Clean + conditional-enable pair. + * Selection: long-press a note -> subtitle tv_folder_notes_count desc gains + " • 1 Selected", iv_selected (desc "Select", selected="true") APPEARS + the + bottom selection action bar (add_reminder/pin/share/archive/fab_selection). + BACK reverts the subtitle and removes iv_selected. Tapping a 2nd row in + selection mode -> " • 2 Selected", two iv_selected badges. + * "Show notes count" (General settings): flipping it OFF makes ALL tv_notes_count + (library cards) and tv_folder_notes_count nodes DISAPPEAR from the HOME sheet; + flipping ON brings them back. The Compose toggle itself exposes NO + checked/selected attribute, so the consequence (count nodes present/absent) is + the observable state, and it PERSISTS across force-stop+relaunch. + * Theme: General -> Theme -> "Light" updates the Theme row value to "Light" and + survives force_stop_and_relaunch() (row still "Light"). NOTE: selecting a theme + can re-trigger the notification-permission dialog, so dismiss_prompts() after. + * Notes-view dialog: tapping the "Ordering" row flips its value TextView + "Descending" -> "Ascending" (an "Ascending" TextView appears where none was). + * Focus: a fab-created note auto-focuses et_note_body (focused="true"); tapping + et_note_title moves focus to the title (title focused="true", body "false"). + * Reading Mode (via long-press -> More -> Reading Mode) is scoped to the single + opened note, so tv_notes_count reads "1 / 1 Note" and Next does not advance — + we therefore assert the paging-position STATE ("1 / N Note(s)" at position 1), + not a page advance. + * The tv_all_label "All" chip and the Compose theme/toggle controls expose NO + selected/checked attribute in the dump, so their highlight/thumb is a VLM colour + question; the rule half asserts the control is present as the active affordance. + +Invoke: + python3 test_android_states.py +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ══════════════════════════════════════════════════════════════════════════════ +# Local setup helpers +# ══════════════════════════════════════════════════════════════════════════════ + +def dismiss_prompts(): + """Dismiss the first-run system notification-permission dialog (and any stray + prompt) sitting in front of the already-loaded Noto home. Both ASCII "Don't + allow" and the curly-apostrophe "Don't allow" (U+2019) are matched. It can + reappear on a plain relaunch AND after selecting a theme, so call it after + every launch and after a theme change.""" + for _ in range(3): + nodes = ui() + b = (find_node_ci(nodes, "Don't allow") or find_node_ci(nodes, "Don’t allow") + or find_node_ci(nodes, "Allow")) + if b and is_safe(b): + tap_node(b) + settle("tap") + continue + break + + +def launched_home(): + """Force-stop + relaunch (data kept), dismiss any prompt, land on HOME sheet.""" + restart_app() + wait_for_foreground() + dismiss_prompts() + return goto_home() + + +def relaunched_home(): + """The persistence probe: kill the process, relaunch WITHOUT wiping, dismiss + any prompt, back to HOME sheet.""" + force_stop_and_relaunch() + wait_for_foreground() + dismiss_prompts() + return goto_home() + + +def goto_home(): + """Back out to the HOME bottom sheet (the one surface with the 'Create folder' + fab).""" + for _ in range(5): + if find_node(ui(), content_desc="Create folder"): + break + back() + settle("tap") + return ui() + + +def note_titles(nodes): + return [n for n in nodes + if n.get("resource-id", "").rsplit("/", 1)[-1] == "tv_note_title"] + + +def selected_badges(nodes): + return [n for n in nodes + if n.get("resource-id", "").rsplit("/", 1)[-1] == "iv_selected"] + + +def count_nodes(nodes): + """Every visible library-card / folder-row note-count node on HOME.""" + return [n for n in nodes + if n.get("resource-id", "").rsplit("/", 1)[-1] + in ("tv_notes_count", "tv_folder_notes_count")] + + +# ── Depth-backing navigation helpers (named and_enter_*/and_reach_* so the audit +# attributes the declared depth to a real navigation call). ───────────────── + +def and_enter_folder(name="General"): + """HOME sheet -> tap a folder row -> its note-list surface. Counts one + surface. Returns True when the folder title is showing.""" + n = find_node(ui(), text=name) + if n is None or not tap_node(n): + return False + settle("tap") + and_enter("folder:" + name) + tit = node_by_id(ui(), "tv_folder_title") + return tit is not None and tit.get("text") == name + + +def and_enter_editor(): + """FOLDER note-list -> tap fab 'Create note' -> the note editor. Counts one + surface. Returns True when et_note_title is present.""" + fab = find_node(ui(), content_desc="Create note") + if fab is None or not tap_node(fab): + return False + settle("tap") + and_enter("editor") + return node_by_id(ui(), "et_note_title") is not None + + +def and_enter_selection(title=None): + """FOLDER note-list -> LONG-PRESS a note row -> selection mode. Counts one + surface. Returns the note node long-pressed (or None).""" + nodes = ui() + note = (find_node(nodes, text=title) if title else None) or ( + note_titles(nodes)[0] if note_titles(nodes) else None) + if note is None or not long_press(note): + return None + settle("tap") + and_enter("selection") + return note + + +def and_enter_settings(): + """HOME sheet -> ib_settings 'Settings' -> the Settings list. Counts one + surface. Returns True when the 'General' row is present.""" + s = find_node(ui(), content_desc="Settings") + if s is None or not tap_node(s): + return False + settle("tap") + and_enter("settings") + return find_node(ui(), content_desc="General") is not None + + +def and_enter_general_settings(): + """HOME -> Settings -> 'General' -> General settings. Counts two surfaces (it + calls and_enter_settings first). Returns True when the 'Theme' row shows.""" + if not and_enter_settings(): + return False + g = find_node(ui(), content_desc="General") or find_node(ui(), text="General") + if g is None or not tap_node(g): + return False + settle("tap") + and_enter("general_settings") + return find_node(ui(), content_desc="Theme") is not None + + +def and_reach_theme_dialog(): + """General settings -> 'Theme' row -> Theme dialog. Counts one surface. + Returns True when the 'Light' option is present.""" + t = find_node(ui(), content_desc="Theme") + if t is None or not tap_node(t): + return False + settle("tap") + and_enter("theme_dialog") + return find_node(ui(), text="Light") is not None + + +def and_reach_notes_view(): + """FOLDER note-list -> notes_view 'Notes view' -> the sort/filter dialog. + Counts one surface. Returns True when the 'Apply' button shows.""" + nv = node_by_id(ui(), "notes_view") or find_node(ui(), content_desc="Notes view") + if nv is None or not tap_node(nv): + return False + settle("tap") + and_enter("notes_view") + return find_node_ci(ui(), "Apply") is not None + + +def and_reach_note_options(): + """SELECTION mode -> fab_selection 'More options' -> the Note options sheet. + Counts one surface. Returns True when 'Note options' shows.""" + fs = node_by_id(ui(), "fab_selection") + if fs is None or not tap_node(fs): + return False + settle("tap") + and_enter("note_options") + return find_node_ci(ui(), "Note options") is not None + + +def and_reach_reading_mode(): + """Note options sheet -> tv_open_in 'Reading Mode' -> Reading Mode; dismiss the + immersive cling. Counts one surface. Returns True when fab_next appears.""" + oi = node_by_id(ui(), "tv_open_in") or find_node_ci(ui(), "Reading Mode") + if oi is None or not tap_node(oi): + return False + settle("tap") + and_enter("reading_mode") + gotit = find_node_ci(ui(), "Got it") + if gotit: + tap_node(gotit) + settle("tap") + return find_node(ui(), content_desc="Next") is not None + + +# ── Data authoring (unique titles so counts/selection are deterministic). ────── + +def make_note(title, body=""): + """From the HOME sheet: open General -> fab 'Create note' -> type title/body -> + hide_keyboard()+back() (lands on HOME sheet). Returns True on success.""" + if not and_enter_folder("General"): + return False + if not and_enter_editor(): + return False + t = node_by_id(ui(), "et_note_title") + if t is None or not type_text(t, title): + return False + if body: + b = node_by_id(ui(), "et_note_body") + if b is not None: + type_text(b, body) + hide_keyboard() + back() + settle("tap") + goto_home() + return True + + +def theme_row_value(nodes): + """The current value TextView on the General-settings 'Theme' row.""" + row = find_node(nodes, content_desc="Theme") + if not row or "_bounds" not in row: + return None + ry = row["_bounds"][1] + for n in nodes: + if not n.get("class", "").endswith("TextView"): + continue + b = n.get("_bounds") + if (b and abs(b[1] - ry) < 90 and n.get("text") in ( + "Follow system + Dark", "Follow system + Black", + "Light", "Dark", "Black")): + return n.get("text") + return None + + +def set_theme(option): + """From HOME: drive to the Theme dialog and select `option`. Returns the Theme + row value observed afterward (after dismissing any re-triggered prompt).""" + if not and_enter_general_settings(): + return None + if not and_reach_theme_dialog(): + return None + opt = find_node(ui(), text=option) or find_node(ui(), content_desc=option) + if opt is None or not tap_node(opt): + return None + settle("tap") + dismiss_prompts() # selecting a theme can re-show the notif prompt + return theme_row_value(ui()) + + +# ══════════════════════════════════════════════════════════════════════════════ +# SELECTION state machine (checked/selected is THIS lane's) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_selection_on", "states_selection_on_vlm", + "states_selection_bar_vlm")) +def test_selection_turns_on(): + """Long-press a note -> selection mode ON: iv_selected APPEARS, subtitle gains + ' • 1 Selected'.""" + launched_home() + make_note("SelOne", "sel body one") + if not and_enter_folder("General"): + record("states_selection_on", False, + "setup_failed: could not open the General folder", + depth=1, jump_kind="transition", + expect="not-selected -> selected") + return + before = ui() + sub_before = (node_by_id(before, "tv_folder_notes_count") or {}).get("content-desc", "") + badges_before = len(selected_badges(before)) + note = and_enter_selection("SelOne") + if note is None: + record("states_selection_on", False, + "setup_failed: long-press did not register on the note row", + depth=1, jump_kind="transition", + expect="not-selected -> selected") + return + after = ui() + sub_after = (node_by_id(after, "tv_folder_notes_count") or {}).get("content-desc", "") + sel_node = node_by_id(after, "iv_selected") + badges_after = len(selected_badges(after)) + ok = (badges_before == 0 and badges_after >= 1 + and "Selected" not in sub_before and "Selected" in sub_after + and sel_node is not None and sel_node.get("selected") == "true") + record("states_selection_on", ok, + "" if ok else ("behavior_wrong: long-press did not enter selection " + f"(iv_selected {badges_before}->{badges_after}, " + f"subtitle {sub_before!r}->{sub_after!r})"), + depth=1, jump_kind="transition", + expect="iv_selected absent -> present; subtitle gains ' • 1 Selected'") + vlm_assert("states_selection_on", + "Does exactly one note row show a solid, filled circular check/" + "selection badge (a coloured circle with a checkmark) on it?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="shape") + vlm_assert("states_selection_bar", + "Is a horizontal action bar of icon buttons (reminder, pin, share, " + "archive) shown along the bottom of the screen?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="layout") + + +@and_test(expects=("states_selection_off",)) +def test_selection_turns_off(): + """From selection ON, BACK -> selection OFF: subtitle drops 'Selected', + iv_selected gone.""" + launched_home() + make_note("SelOff", "sel off body") + if not and_enter_folder("General"): + record("states_selection_off", False, + "setup_failed: could not open the General folder", + depth=1, jump_kind="transition", expect="selected -> not-selected") + return + note = and_enter_selection("SelOff") + if note is None: + record("states_selection_off", False, + "setup_failed: could not enter selection mode", + depth=1, jump_kind="transition", expect="selected -> not-selected") + return + on = ui() + sub_on = (node_by_id(on, "tv_folder_notes_count") or {}).get("content-desc", "") + badges_on = len(selected_badges(on)) + and_back() # BACK exits selection mode + settle("tap") + off = ui() + sub_off = (node_by_id(off, "tv_folder_notes_count") or {}).get("content-desc", "") + badges_off = len(selected_badges(off)) + ok = ("Selected" in sub_on and badges_on >= 1 + and "Selected" not in sub_off and badges_off == 0) + record("states_selection_off", ok, + "" if ok else ("behavior_wrong: BACK did not clear selection " + f"(subtitle {sub_on!r}->{sub_off!r}, " + f"badges {badges_on}->{badges_off})"), + depth=1, jump_kind="transition", + expect="subtitle ' • 1 Selected' -> no 'Selected'; iv_selected removed") + + +@and_test(expects=("states_multiselect_two",)) +def test_multiselect_two(): + """Long-press one note, tap a second -> two iv_selected badges, subtitle + ' • 2 Selected'.""" + launched_home() + make_note("MultiA", "multi body a") + make_note("MultiB", "multi body b") + if not and_enter_folder("General"): + record("states_multiselect_two", False, + "setup_failed: could not open the General folder", + depth=1, jump_kind="transition", + expect="1 selected -> 2 selected") + return + rows = note_titles(ui()) + if len(rows) < 2: + record("states_multiselect_two", False, + "setup_failed: fewer than two note rows to multi-select", + depth=1, jump_kind="transition", + expect="1 selected -> 2 selected") + return + if and_enter_selection() is None: + record("states_multiselect_two", False, + "setup_failed: could not enter selection mode", + depth=1, jump_kind="transition", + expect="1 selected -> 2 selected") + return + one = ui() + sub_one = (node_by_id(one, "tv_folder_notes_count") or {}).get("content-desc", "") + badges_one = len(selected_badges(one)) + rows = note_titles(ui()) + tapped = tap_node(rows[1]) if len(rows) > 1 else False + settle("tap") + two = ui() + sub_two = (node_by_id(two, "tv_folder_notes_count") or {}).get("content-desc", "") + badges_two = len(selected_badges(two)) + ok = (tapped and badges_one == 1 and badges_two == 2 + and "1 Selected" in sub_one and "2 Selected" in sub_two) + record("states_multiselect_two", ok, + "" if ok else ("behavior_wrong: second tap did not add a selection " + f"(badges {badges_one}->{badges_two}, " + f"subtitle {sub_one!r}->{sub_two!r})"), + depth=1, jump_kind="transition", + expect="'1 Selected' / 1 badge -> '2 Selected' / 2 badges") + + +@and_test(expects=("states_selection_count_increment",)) +def test_selection_count_increment(): + """With >=2 notes, the ' • K Selected' count increments 1 -> 2 as a second row + is tapped (the selected-count state).""" + launched_home() + make_note("IncA", "inc body a") + make_note("IncB", "inc body b") + if not and_enter_folder("General"): + record("states_selection_count_increment", False, + "setup_failed: could not open the General folder", + depth=1, jump_kind="transition", expect="count 1 -> 2") + return + if and_enter_selection() is None: + record("states_selection_count_increment", False, + "setup_failed: could not enter selection mode", + depth=1, jump_kind="transition", expect="count 1 -> 2") + return + sub1 = (node_by_id(ui(), "tv_folder_notes_count") or {}).get("content-desc", "") + rows = note_titles(ui()) + if len(rows) < 2 or not tap_node(rows[1]): + record("states_selection_count_increment", False, + "setup_failed: could not tap a second row", + depth=1, jump_kind="transition", expect="count 1 -> 2") + return + settle("tap") + sub2 = (node_by_id(ui(), "tv_folder_notes_count") or {}).get("content-desc", "") + ok = "1 Selected" in sub1 and "2 Selected" in sub2 + record("states_selection_count_increment", ok, + "" if ok else ("behavior_wrong: selected-count did not increment " + f"({sub1!r} -> {sub2!r})"), + depth=1, jump_kind="transition", + expect="subtitle '• 1 Selected' -> '• 2 Selected'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# LABEL FILTER CHIP (the "All" chip is the active/selected filter) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_all_chip_active", "states_all_chip_active_vlm")) +def test_all_label_chip_active(): + """The folder screen's tv_all_label 'All' chip is the active filter (a + filled/highlighted chip) while the add-label button is an outlined affordance. + The dump exposes no selected attribute on the chip, so the rule half asserts + the chip and the add-label button both exist as the filter row, and the VLM + verifies the fill/outline colour distinction.""" + launched_home() + if not and_enter_folder("General"): + record("states_all_chip_active", False, + "setup_failed: could not open the General folder", + depth=1, jump_kind="value", expect="'All' chip present as active filter") + return + nodes = ui() + chip = node_by_id(nodes, "tv_all_label") or find_node_ci(nodes, "All") + add = node_by_id(nodes, "ib_new_label") or find_node(nodes, content_desc="Create label") + ok = chip is not None and chip.get("text") == "All" and add is not None + record("states_all_chip_active", ok, + "" if ok else "feature_missing: no 'All' filter chip + add-label button row", + depth=1, jump_kind="value", + expect="tv_all_label 'All' + ib_new_label present as the active filter row") + vlm_assert("states_all_chip_active", + "Near the top of the note list, the row starts with an 'All' label " + "and a neighbouring icon button. Is the 'All' label drawn as a FILLED " + "solid (dark) pill/box with light text, while the neighbouring button " + "is only an OUTLINED (unfilled, white-interior) box?", + RESULTS_DIR, depth=1, jump_kind="value", tag="color") + + +# ══════════════════════════════════════════════════════════════════════════════ +# EDITOR conditional enable/disable (enabled transitions are THIS lane's) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_undo_enable", "states_undo_disabled_vlm")) +def test_undo_enables_after_typing(): + """A FRESH note has ib_undo enabled='false'; after typing into et_note_body it + flips to enabled='true' (the app-authored consequence of there being an edit to + undo).""" + launched_home() + if not and_enter_folder("General") or not and_enter_editor(): + record("states_undo_enable", False, + "setup_failed: could not reach the note editor", + depth=2, jump_kind="transition", expect="undo disabled -> enabled") + return + fresh = ui() + undo0 = node_by_id(fresh, "ib_undo") + before = undo0.get("enabled") if undo0 else None + # VLM the disabled state on the fresh note BEFORE we type. + vlm_assert("states_undo_disabled", + "In the bottom toolbar of this note editor, does the Undo (left " + "curved arrow) icon look greyed-out / dimmed compared with the other " + "toolbar icons?", + RESULTS_DIR, depth=2, jump_kind="transition", tag="color") + body = node_by_id(ui(), "et_note_body") + if body is None or not type_text(body, "x"): + record("states_undo_enable", False, + "setup_failed: could not type into the note body", + depth=2, jump_kind="transition", expect="undo disabled -> enabled") + return + after = ui() + undo1 = find_closest_match(after, undo0) if undo0 else node_by_id(after, "ib_undo") + undo1 = node_by_id(after, "ib_undo") or undo1 + now = undo1.get("enabled") if undo1 else None + ok = before == "false" and now == "true" + record("states_undo_enable", ok, + "" if ok else ("behavior_wrong: ib_undo enabled did not flip false->true " + f"(before={before}, after={now})"), + depth=2, jump_kind="transition", + expect="ib_undo enabled 'false' -> 'true' after an edit") + + +@and_test(expects=("states_redo_stays_disabled",)) +def test_redo_stays_disabled_after_typing(): + """Conditional-enable pair: after typing (undo now enabled) there is nothing to + REDO yet, so ib_redo STAYS enabled='false'. A specific resulting state.""" + launched_home() + if not and_enter_folder("General") or not and_enter_editor(): + record("states_redo_stays_disabled", False, + "setup_failed: could not reach the note editor", + depth=2, jump_kind="value", expect="ib_redo enabled == 'false'") + return + body = node_by_id(ui(), "et_note_body") + if body is None or not type_text(body, "y"): + record("states_redo_stays_disabled", False, + "setup_failed: could not type into the note body", + depth=2, jump_kind="value", expect="ib_redo enabled == 'false'") + return + after = ui() + redo = node_by_id(after, "ib_redo") + undo = node_by_id(after, "ib_undo") + ok = (redo is not None and redo.get("enabled") == "false" + and undo is not None and undo.get("enabled") == "true") + record("states_redo_stays_disabled", ok, + "" if ok else ("behavior_wrong: after an edit redo should be disabled " + "while undo is enabled " + f"(redo={redo.get('enabled') if redo else None}, " + f"undo={undo.get('enabled') if undo else None})"), + depth=2, jump_kind="value", + expect="after an edit: ib_redo enabled 'false' (nothing to redo), ib_undo 'true'") + + +@and_test(expects=("states_undo_history_disabled",)) +def test_undo_history_disabled_on_fresh_note(): + """On a FRESH note ib_undo_history is enabled='false' (no history yet) — the + initial disabled state of the history control. Specific resulting state.""" + launched_home() + if not and_enter_folder("General") or not and_enter_editor(): + record("states_undo_history_disabled", False, + "setup_failed: could not reach the note editor", + depth=2, jump_kind="value", expect="ib_undo_history enabled == 'false'") + return + fresh = ui() + uh = node_by_id(fresh, "ib_undo_history") + rh = node_by_id(fresh, "ib_redo_history") + ok = (uh is not None and uh.get("enabled") == "false" + and rh is not None and rh.get("enabled") == "false") + record("states_undo_history_disabled", ok, + "" if ok else ("behavior_wrong: history controls should be disabled on a " + f"fresh note (undo_history={uh.get('enabled') if uh else None}, " + f"redo_history={rh.get('enabled') if rh else None})"), + depth=2, jump_kind="value", + expect="fresh note: ib_undo_history & ib_redo_history enabled 'false'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# SETTINGS / MODE PERSISTENCE (the strongest anti-shell probe — THIS lane owns it) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_theme_persists", "states_theme_light_vlm", + "states_theme_persists_vlm", "states_theme_selected_mark_vlm", + "states_theme_dark_vlm")) +def test_theme_light_persists_across_restart(): + """Select the 'Light' theme -> the General-settings Theme row reads 'Light' AND + the app recolours light; then force_stop_and_relaunch() -> the row is STILL + 'Light' (mode persisted across process death). Finally restore a dark theme.""" + launched_home() + val = set_theme("Light") + # VLM: after selecting Light, capture the (light) app + the marked option state. + # set_theme returns us to General settings; snapshot it for the colour check. + vlm_assert("states_theme_light", + "Is the overall app background LIGHT (white / very pale) with dark " + "text, rather than a dark/black background?", + RESULTS_DIR, depth=3, jump_kind="transition", tag="color") + # Re-open the theme dialog to VLM the currently-selected option marker. + if and_reach_theme_dialog(): + vlm_assert("states_theme_selected_mark", + "In this Theme option list, is the 'Light' option visibly marked " + "as the current selection (a filled radio dot or a highlighted " + "row) while the other options are not?", + RESULTS_DIR, depth=3, jump_kind="value", tag="shape") + back() # close the dialog + settle("tap") + ok_select = val == "Light" + + # Persistence probe: kill + relaunch, then re-read the Theme row. + relaunched_home() + persisted = None + if and_enter_general_settings(): + persisted = theme_row_value(ui()) + vlm_assert("states_theme_persists", + "Is the overall app background still LIGHT (white / very pale) with " + "dark text after the app was restarted?", + RESULTS_DIR, depth=3, jump_kind="transition", tag="color") + ok = ok_select and persisted == "Light" + record("states_theme_persists", ok, + "" if ok else ("behavior_wrong: theme did not select/persist as Light " + f"(after-select={val!r}, after-restart={persisted!r})"), + depth=3, jump_kind="transition", + expect="Theme row 'Light' after selection AND still 'Light' after relaunch") + + # Verify a DARK surface via the UNCONDITIONAL "Dark" option (not "Follow + # system + Dark" — on this emulator the system is in light mode, so that would + # resolve LIGHT). "Dark" renders dark regardless, which is what we VLM here. + # NOTE: the persistence probe above left us DEEP in General settings, but + # set_theme() navigates from the HOME sheet — so return HOME first, else its + # nested and_enter_settings() misfires and the theme never actually changes. + goto_home() + set_theme("Dark") + goto_home() + vlm_assert("states_theme_dark", + "Is the overall app background now DARK (near-black / very dark) with " + "light-coloured text?", + RESULTS_DIR, depth=3, jump_kind="transition", tag="color") + # Restore the app's DEFAULT theme so no later test (in this or another lane) + # inherits a forced Dark/Light surface: the default is "Follow system + Dark", + # which on this light-mode emulator renders the light appearance every lane was + # authored against. + goto_home() + set_theme("Follow system + Dark") + goto_home() + + +@and_test(expects=("states_show_count_toggle", "states_show_count_thumb_vlm")) +def test_show_notes_count_toggle_consequence(): + """Flip the 'Show notes count' General setting -> its app-authored consequence: + every tv_notes_count / tv_folder_notes_count node on the HOME sheet DISAPPEARS + (they are present before, absent after). Then flip it back.""" + launched_home() + home_before = ui() + counts_before = len(count_nodes(home_before)) + if not and_enter_general_settings(): + record("states_show_count_toggle", False, + "setup_failed: could not reach General settings", + depth=2, jump_kind="transition", expect="count nodes present -> absent") + return + snc = find_node(ui(), content_desc="Show notes count") or find_node_ci(ui(), "Show notes count") + if snc is None: + record("states_show_count_toggle", False, + "feature_missing: no 'Show notes count' setting", + depth=2, jump_kind="transition", expect="count nodes present -> absent") + return + # VLM the toggle's thumb BEFORE we flip it (it should read ON, thumb to the right). + vlm_assert("states_show_count_thumb", + "On the 'Show notes count' settings row, is there a switch whose thumb " + "is toward the RIGHT / in the ON position (the track filled/coloured)?", + RESULTS_DIR, depth=2, jump_kind="transition", tag="position") + tap_node(snc) + settle("tap") + goto_home() + home_after = ui() + counts_after = len(count_nodes(home_after)) + ok = counts_before >= 1 and counts_after == 0 + record("states_show_count_toggle", ok, + "" if ok else ("behavior_wrong: toggling 'Show notes count' did not hide " + f"the HOME count nodes (before={counts_before}, " + f"after={counts_after})"), + depth=2, jump_kind="transition", + expect="HOME note-count nodes present -> absent after toggling off") + # Restore: flip it back ON. + if and_enter_general_settings(): + back_snc = find_node(ui(), content_desc="Show notes count") + if back_snc: + tap_node(back_snc) + settle("tap") + goto_home() + + +@and_test(expects=("states_show_count_persists",)) +def test_show_notes_count_persists_across_restart(): + """SETTINGS PERSISTENCE: turn 'Show notes count' OFF, force_stop_and_relaunch(), + and confirm the HOME count nodes are STILL absent (the mode survived process + death). Then restore it ON.""" + launched_home() + if not and_enter_general_settings(): + record("states_show_count_persists", False, + "setup_failed: could not reach General settings", + depth=2, jump_kind="transition", + expect="counts hidden persists across relaunch") + return + snc = find_node(ui(), content_desc="Show notes count") + if snc is None: + record("states_show_count_persists", False, + "feature_missing: no 'Show notes count' setting", + depth=2, jump_kind="transition", + expect="counts hidden persists across relaunch") + return + tap_node(snc) # turn OFF + settle("tap") + goto_home() + hidden_before = len(count_nodes(ui())) == 0 + relaunched_home() # kill + relaunch, no wipe + hidden_after = len(count_nodes(ui())) == 0 + ok = hidden_before and hidden_after + record("states_show_count_persists", ok, + "" if ok else ("behavior_wrong: 'Show notes count'=off did not persist " + f"(hidden before restart={hidden_before}, " + f"after={hidden_after})"), + depth=2, jump_kind="transition", + expect="HOME count nodes absent both before AND after relaunch") + # Restore ON. + if and_enter_general_settings(): + back_snc = find_node(ui(), content_desc="Show notes count") + if back_snc: + tap_node(back_snc) + settle("tap") + goto_home() + + +# ══════════════════════════════════════════════════════════════════════════════ +# NOTES-VIEW dialog state (the folder's current sort/filter selections) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_notes_view_current_state",)) +def test_notes_view_current_state(): + """Open the Notes-view dialog: it renders the folder's CURRENT view state — + Filtering=Inclusive, Sorting=Creation date, Ordering=Descending, Grouping=None. + Assert those current-state values are present (page-level state).""" + launched_home() + if not and_enter_folder("General") or not and_reach_notes_view(): + record("states_notes_view_current_state", False, + "setup_failed: could not open the Notes-view dialog", + depth=1, jump_kind="value", + expect="rows show Inclusive / Creation date / Descending / None") + return + nodes = ui() + have = {t: find_node(nodes, text=t) is not None + for t in ("Inclusive", "Creation date", "Descending", "None")} + labels = all(find_node(nodes, content_desc=c) is not None + for c in ("Filtering", "Sorting", "Ordering", "Grouping")) + ok = labels and all(have.values()) + record("states_notes_view_current_state", ok, + "" if ok else ("behavior_wrong: Notes-view dialog missing a current-state " + f"value (present={have}, labels={labels})"), + depth=1, jump_kind="value", + expect="Filtering=Inclusive, Sorting=Creation date, Ordering=Descending, Grouping=None") + + +@and_test(expects=("states_ordering_toggle",)) +def test_notes_view_ordering_toggle(): + """In the Notes-view dialog, tapping the 'Ordering' row flips its value from + 'Descending' -> 'Ascending' (an 'Ascending' TextView appears where there was + none). A before->after value flip of the sort-order state.""" + launched_home() + if not and_enter_folder("General") or not and_reach_notes_view(): + record("states_ordering_toggle", False, + "setup_failed: could not open the Notes-view dialog", + depth=1, jump_kind="transition", expect="Descending -> Ascending") + return + before = ui() + asc_before = find_node(before, text="Ascending") is not None + desc_before = find_node(before, text="Descending") is not None + row = find_node(before, content_desc="Ordering") + if row is None or not tap_node(row): + record("states_ordering_toggle", False, + "setup_failed: could not tap the Ordering row", + depth=1, jump_kind="transition", expect="Descending -> Ascending") + return + settle("tap") + after = ui() + asc_after = find_node(after, text="Ascending") is not None + ok = desc_before and not asc_before and asc_after + record("states_ordering_toggle", ok, + "" if ok else ("behavior_wrong: tapping Ordering did not flip the order " + f"value (Ascending before={asc_before}, after={asc_after})"), + depth=1, jump_kind="transition", + expect="order value 'Descending' -> 'Ascending' (Ascending text appears)") + + +# ══════════════════════════════════════════════════════════════════════════════ +# READING-MODE paging state +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_reading_paging_position", "states_reading_paging_vlm")) +def test_reading_mode_paging_position(): + """Open a note in Reading Mode -> the tv_notes_count paging indicator renders + the current page position as 'N / M Note(s)', starting at position 1. Assert + that page-position state is present and begins at 1.""" + launched_home() + make_note("ReadOne", "reading body one") + if not and_enter_folder("General"): + record("states_reading_paging_position", False, + "setup_failed: could not open the General folder", + depth=3, jump_kind="value", expect="paging indicator at position 1 ('1 / M')") + return + if and_enter_selection("ReadOne") is None: + record("states_reading_paging_position", False, + "setup_failed: could not enter selection mode", + depth=3, jump_kind="value", expect="paging indicator at position 1 ('1 / M')") + return + if not and_reach_note_options() or not and_reach_reading_mode(): + record("states_reading_paging_position", False, + "setup_failed: could not reach Reading Mode", + depth=3, jump_kind="value", expect="paging indicator at position 1 ('1 / M')") + return + nodes = ui() + ind = node_by_id(nodes, "tv_notes_count") + desc = ind.get("content-desc", "") if ind else "" + # Format "N / M Note(s)" at position 1. + ok = ind is not None and desc.startswith("1 /") and "Note" in desc + record("states_reading_paging_position", ok, + "" if ok else ("behavior_wrong: Reading-Mode paging indicator not at " + f"position 1 (desc={desc!r})"), + depth=3, jump_kind="value", + expect="tv_notes_count desc == '1 / M Note(s)' (paging at position 1)") + vlm_assert("states_reading_paging", + "In this full-screen reading view, near the top under the folder " + "name, is a page-position indicator rendered showing something like " + "'1 / 1 Note' or '1 / 2 Note'?", + RESULTS_DIR, depth=3, jump_kind="value", tag="layout") + + +# ══════════════════════════════════════════════════════════════════════════════ +# FOCUS (SOLE owner of focus) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_body_focus",)) +def test_body_field_focus(): + """Tap et_note_body -> it holds focus (focused='true') AND the soft keyboard is + up (keyboard_visible()). We first move focus AWAY (tap the title) so the tap on + the body is a genuine focus transition, not a no-op on the auto-focused field.""" + launched_home() + if not and_enter_folder("General") or not and_enter_editor(): + record("states_body_focus", False, + "setup_failed: could not reach the note editor", + depth=2, jump_kind="transition", expect="body focused false -> true") + return + # Move focus to the title first so the body starts UNfocused. + title = node_by_id(ui(), "et_note_title") + if title is not None: + tap_node(title) + settle("keyboard") + pre = ui() + body_pre = node_by_id(pre, "et_note_body") + before = body_pre.get("focused") if body_pre else None + if body_pre is None or not tap_node(body_pre): + record("states_body_focus", False, + "setup_failed: could not tap the note body", + depth=2, jump_kind="transition", expect="body focused false -> true") + return + settle("keyboard") + post = ui() + body_post = node_by_id(post, "et_note_body") + after = body_post.get("focused") if body_post else None + kbd = keyboard_visible() + ok = before == "false" and after == "true" and kbd + record("states_body_focus", ok, + "" if ok else ("behavior_wrong: tapping the body did not focus it with the " + f"keyboard up (focused {before}->{after}, keyboard={kbd})"), + depth=2, jump_kind="transition", + expect="et_note_body focused 'false' -> 'true'; soft keyboard visible") + + +@and_test(expects=("states_title_focus",)) +def test_title_field_focus_moves(): + """A fab-created note auto-focuses the body; tapping et_note_title MOVES focus + to the title — title focused='true', body focused='false' (focus is exclusive).""" + launched_home() + if not and_enter_folder("General") or not and_enter_editor(): + record("states_title_focus", False, + "setup_failed: could not reach the note editor", + depth=2, jump_kind="transition", expect="focus moves body -> title") + return + pre = ui() + title_pre = node_by_id(pre, "et_note_title") + body_pre = node_by_id(pre, "et_note_body") + body_foc_before = body_pre.get("focused") if body_pre else None + if title_pre is None or not tap_node(title_pre): + record("states_title_focus", False, + "setup_failed: could not tap the title field", + depth=2, jump_kind="transition", expect="focus moves body -> title") + return + settle("keyboard") + post = ui() + title_post = node_by_id(post, "et_note_title") + body_post = node_by_id(post, "et_note_body") + title_foc = title_post.get("focused") if title_post else None + body_foc = body_post.get("focused") if body_post else None + ok = body_foc_before == "true" and title_foc == "true" and body_foc == "false" + record("states_title_focus", ok, + "" if ok else ("behavior_wrong: focus did not move from body to title " + f"(body was {body_foc_before}; now title={title_foc}, " + f"body={body_foc})"), + depth=2, jump_kind="transition", + expect="et_note_title focused 'true' & et_note_body focused 'false'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# HOME library-card accent colours (a persistent visual state of the home) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_home_cards", "states_home_cards_vlm")) +def test_home_library_cards_state(): + """The HOME sheet always shows its 4 library cards (All/Recent/Scheduled/ + Archived), each a persistent shortcut. Rule half asserts the 4 titles are + present; the VLM verifies each card carries a DISTINCT accent colour — a + rendered state the dump cannot report.""" + launched_home() + nodes = ui() + titles = {n.get("text") for n in nodes + if n.get("resource-id", "").rsplit("/", 1)[-1] == "tv_title"} + ok = {"All", "Recent", "Scheduled", "Archived"} <= titles + record("states_home_cards", ok, + "" if ok else f"feature_missing: HOME library cards incomplete (saw {sorted(titles)})", + depth=0, jump_kind="value", + expect="All / Recent / Scheduled / Archived cards all present on HOME") + vlm_assert("states_home_cards", + "Near the top of this screen are four library cards. Do they have " + "FOUR DISTINCT accent colours (for example blue, amber/yellow, red, " + "and purple) rather than all being the same colour?", + RESULTS_DIR, depth=0, jump_kind="value", tag="color") + + +# ══════════════════════════════════════════════════════════════════════════════ +TESTS = [ + test_selection_turns_on, + test_selection_turns_off, + test_multiselect_two, + test_selection_count_increment, + test_all_label_chip_active, + test_undo_enables_after_typing, + test_redo_stays_disabled_after_typing, + test_undo_history_disabled_on_fresh_note, + test_theme_light_persists_across_restart, + test_show_notes_count_toggle_consequence, + test_show_notes_count_persists_across_restart, + test_notes_view_current_state, + test_notes_view_ordering_toggle, + test_reading_mode_paging_position, + test_body_field_focus, + test_title_field_focus_moves, + test_home_library_cards_state, +] + +if __name__ == "__main__": + run_suite(TESTS, "states") diff --git a/android/alialbaali-noto/tests/test_android_structure.py b/android/alialbaali-noto/tests/test_android_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..da667813f652e58d47ea49763ae9b2335ec0a3fa --- /dev/null +++ b/android/alialbaali-noto/tests/test_android_structure.py @@ -0,0 +1,564 @@ +#!/usr/bin/env python3 +"""STRUCTURE module — Noto (minimal note-taking app). + +Lane ownership: (1) the GATE — the app launches and its top-level surfaces +exist; (2) tree-SHAPE deltas — an interaction changes the view tree's SHAPE +(subtree added/removed / surface_changed). No content strings, no computed +values, no checked/selected/focus, no reachability-by-jump claims. + +Invoke: + python3 test_android_structure.py +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ── Local prompt handling ─────────────────────────────────────────────────── +LIBRARY_CARDS = ("All", "Recent", "Scheduled", "Archived") + + +def dismiss_prompts(): + """Dismiss the first-run system notification-permission dialog (and any other + stray prompt) that sits in front of the already-loaded Noto home.""" + for _ in range(3): + nodes = ui() + b = (find_node_ci(nodes, "Don't allow") or find_node_ci(nodes, "Don’t allow") + or find_node_ci(nodes, "Allow")) + if b and is_safe(b): + tap_node(b) + settle("tap") + continue + break + + +def fresh_home(): + """Deterministic virgin state: wipe data, relaunch, clear the perm prompt, + return the HOME-sheet node tree.""" + clear_data() + launch_app() + wait_for_foreground() + dismiss_prompts() + return ui() + + +# ── Depth-family helpers (names back the declared depth) ───────────────────── +def and_enter_folder(nodes=None, name="General"): + """HOME sheet -> tap a folder row -> FOLDER note-list. Returns (ok, nodes).""" + nodes = ui() if nodes is None else nodes + title = find_node(nodes, text=name) + if title is None: + return False, nodes + if not tap_node(title): + return False, nodes + and_enter("folder") + return True, ui() + + +def and_enter_editor(): + """FOLDER -> fab 'Create note' -> NOTE editor. Assumes on a folder screen.""" + nodes = ui() + fab = find_node(nodes, content_desc="Create note") or node_by_id(nodes, "fab") + if fab is None or not tap_node(fab): + return False, nodes + and_enter("editor") + return True, ui() + + +def and_enter_settings(nodes): + """HOME -> ib_settings -> SETTINGS (Compose).""" + btn = node_by_id(nodes, "ib_settings") or find_node(nodes, content_desc="Settings") + if btn is None or not tap_node(btn): + return False, nodes + and_enter("settings") + return True, ui() + + +def and_reach_selection(row_node): + """FOLDER note row -> long-press -> selection mode. Counts one surface. + Returns (ok, selection_nodes).""" + if row_node is None or not long_press(row_node): + return False, ui() + and_enter("selection") + return True, ui() + + +def and_enter_note_options(sel_nodes): + """selection -> fab_selection 'More options' -> Note-options sheet.""" + fs = node_by_id(sel_nodes, "fab_selection") or find_node(sel_nodes, content_desc="More options") + if fs is None or not tap_node(fs): + return False, ui() + and_enter("note_options") + return True, ui() + + +def and_enter_reading_mode(opt_nodes): + """Note options -> 'Reading Mode' (tv_open_in) -> reading mode; dismiss the + first-run immersive 'Got it' cling if it appears.""" + rm = node_by_id(opt_nodes, "tv_open_in") or find_node_ci(opt_nodes, "Reading Mode") + if rm is None or not tap_node(rm): + return False, ui() + and_enter("reading_mode") + settle("tap") + cling = find_node_ci(ui(), "Got it") + if cling and is_safe(cling): + tap_node(cling) + settle("tap") + return True, ui() + + +def make_one_note(title="StructNote", body="alpha beta"): + """From a FRESH folder screen, create a single note. Auto-save persists it on + Back, which returns to the HOME sheet; this re-opens the folder so the note + row is visible. Returns (ok, folder_nodes).""" + ok, _ = and_enter_editor() + if not ok: + return False, ui() + nodes = ui() + et_title = node_by_id(nodes, "et_note_title") + et_body = node_by_id(nodes, "et_note_body") + if et_title is None or et_body is None: + return False, ui() + type_text(et_title, title) + type_text(et_body, body) + hide_keyboard() # MUST precede back(): back() with the keyboard up + back() # only dismisses the keyboard, not the editor. + settle("tap") + nodes = ui() + if node_by_id(nodes, "tv_dialog_title") is not None: # landed on HOME sheet + ok_f, nodes = and_enter_folder(nodes) + if not ok_f: + return False, nodes + return True, nodes + + +def find_note_row(nodes, title): + """The note-list row is a tv_note_title TextView carrying the note title.""" + for n in nodes: + if (n.get("resource-id", "").rsplit("/", 1)[-1] == "tv_note_title" + and n.get("text") == title): + return n + return None + + +def open_folder_from_fresh(name="General"): + """fresh_home() then enter the named folder. Returns (ok, folder_nodes).""" + nodes = fresh_home() + return and_enter_folder(nodes, name) + + +# ════════════════════════════════════════════════════════════════════════════ +# GATE tests (jump_kind="none", depth=0) — kept few (<=30%) +# ════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_gate_home_sheet",)) +def test_gate_home_sheet(): + """App launches -> HOME bottom sheet exists: title + a library card + fab.""" + if not device_online(): + record("structure_gate_home_sheet", False, + "setup_failed: device/tunnel offline", depth=0, jump_kind="none") + return + nodes = fresh_home() + title = node_by_id(nodes, "tv_dialog_title") + has_card = any(find_node(nodes, text=t) for t in LIBRARY_CARDS) + fab = node_by_id(nodes, "fab") or find_node(nodes, content_desc="Create folder") + ok = bool(wait_for_foreground()) and bool(title) and has_card and bool(fab) + record("structure_gate_home_sheet", ok, + "" if ok else "setup_failed: HOME sheet (title + card + fab) not present", + depth=0, jump_kind="none") + + +@and_test(expects=("structure_gate_default_folder",)) +def test_gate_default_folder(): + """Fresh launch shows the default 'General' folder row (tv_folder_title).""" + nodes = fresh_home() + titles = [n.get("text", "") for n in nodes + if n.get("resource-id", "").rsplit("/", 1)[-1] == "tv_folder_title"] + ok = "General" in titles + record("structure_gate_default_folder", ok, + "" if ok else "feature_missing: default 'General' folder row absent", + depth=0, jump_kind="none") + + +@and_test(expects=("structure_gate_library_grid_count",)) +def test_gate_library_grid_count(): + """HOME sheet has the 4 library-card shortcut subtree (SHAPE, not values): + all 4 shortcut cards {All,Recent,Scheduled,Archived} present.""" + nodes = fresh_home() + present = [t for t in LIBRARY_CARDS if find_node(nodes, text=t)] + ok = len(present) >= 4 + record("structure_gate_library_grid_count", ok, + "" if ok else f"feature_missing: only {len(present)}/4 library cards present", + depth=0, jump_kind="none") + + +# ════════════════════════════════════════════════════════════════════════════ +# SHAPE-DELTA tests (the bulk) — trigger an interaction, assert the tree SHAPE +# changed. +# ════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_folder_replaces_home",)) +def test_folder_replaces_home(): + """Tap 'General' -> FOLDER note-list subtree REPLACES the HOME-sheet subtree. + surface_changed True AND the folder screen adds notes_view + fab 'Create + note' + bottom-bar 'Folders' that HOME lacked.""" + nodes = fresh_home() + before = and_showing(nodes) + home_had_notesview = node_by_id(nodes, "notes_view") is not None + ok_tap, fnodes = and_enter_folder(nodes, "General") + after = and_showing(fnodes) + notes_view = node_by_id(fnodes, "notes_view") or find_node(fnodes, content_desc="Notes view") + create_note = find_node(fnodes, content_desc="Create note") + folders_btn = find_node(fnodes, content_desc="Folders") + added = bool(notes_view) and bool(create_note) and bool(folders_btn) + changed = surface_changed(before, after) + ok = ok_tap and changed and added and not home_had_notesview + record("structure_folder_replaces_home", ok, + "" if ok else "behavior_wrong: folder note-list subtree did not replace home sheet", + depth=1, jump_kind="transition", + expect="folder note-list subtree (notes_view/fab Create note/Folders bar) replaces home sheet") + + +@and_test(expects=("structure_editor_subtree_appears",)) +def test_editor_subtree_appears(): + """FOLDER -> fab 'Create note' -> NOTE editor subtree appears: et_note_title + + et_note_body + bab_toolbar with 4 toolbar ImageButtons. Absent BEFORE.""" + ok_folder, fnodes = open_folder_from_fresh("General") + before_title = node_by_id(fnodes, "et_note_title") + ok_editor, enodes = and_enter_editor() + et_title = node_by_id(enodes, "et_note_title") + et_body = node_by_id(enodes, "et_note_body") + toolbar = node_by_id(enodes, "bab_toolbar") + tb_buttons = [node_by_id(enodes, r) for r in + ("ib_undo_history", "ib_undo", "ib_redo", "ib_redo_history")] + n_buttons = sum(1 for b in tb_buttons if b is not None) + ok = (ok_folder and ok_editor and before_title is None + and et_title is not None and et_body is not None + and toolbar is not None and n_buttons == 4) + record("structure_editor_subtree_appears", ok, + "" if ok else "behavior_wrong: editor subtree (title/body/4-button toolbar) did not appear", + depth=2, jump_kind="transition", + expect="et_note_title+et_note_body+bab_toolbar(4 ImageButtons) appear only after fab Create note") + + +@and_test(expects=("structure_selection_bar_appears",)) +def test_selection_bar_appears(): + """Create a note, LONG-PRESS its row -> selection action-bar subtree appears. + 'archive' also lives on the plain folder bar, so the selection-UNIQUE ids + (add_reminder/pin/share/fab_selection) are what must go absent->present.""" + sel_ids = ("add_reminder", "pin", "share", "fab_selection") + ok_folder, _ = open_folder_from_fresh("General") + made, fnodes = make_one_note("SelNote", "one two") + row = find_note_row(fnodes, "SelNote") + if row is None: + scroll_into_view("SelNote") + row = find_note_row(ui(), "SelNote") + before_nodes = ui() + n_before = sum(1 for r in sel_ids if node_by_id(before_nodes, r) is not None) + ok_sel, anodes = and_reach_selection(row) + n_after = sum(1 for r in sel_ids if node_by_id(anodes, r) is not None) + ok = ok_folder and made and ok_sel and n_before == 0 and n_after == len(sel_ids) + record("structure_selection_bar_appears", ok, + "" if ok else f"behavior_wrong: selection action-bar subtree not added by long-press " + f"(before={n_before}, after={n_after})", + depth=1, jump_kind="transition", + expect="selection bar (add_reminder/pin/share/fab_selection) absent->present on long-press") + + +@and_test(expects=("structure_notesview_sheet_appears",)) +def test_notesview_sheet_appears(): + """FOLDER -> notes_view -> a bottom-sheet subtree appears (rows Filtering/ + Sorting/Apply). surface_changed True vs the folder screen.""" + ok_folder, fnodes = open_folder_from_fresh("General") + before = and_showing(fnodes) + btn = node_by_id(fnodes, "notes_view") or find_node(fnodes, content_desc="Notes view") + tapped = tap_node(btn) if btn else False + and_enter("notes_view") + anodes = ui() + after = and_showing(anodes) + has_rows = (find_node_ci(anodes, "Filtering") is not None + and find_node_ci(anodes, "Sorting") is not None + and find_node_ci(anodes, "Apply") is not None) + ok = ok_folder and tapped and surface_changed(before, after) and has_rows + record("structure_notesview_sheet_appears", ok, + "" if ok else "behavior_wrong: Notes-view dialog subtree (Filtering/Sorting/Apply) did not appear", + depth=1, jump_kind="transition", + expect="notes-view bottom-sheet subtree (Filtering/Sorting/Apply rows) added over folder screen") + + +@and_test(expects=("structure_newfolder_dialog_appears",)) +def test_newfolder_dialog_appears(): + """HOME -> fab 'Create folder' -> New-folder dialog subtree appears + (et Title field + btn_create). surface_changed True.""" + nodes = fresh_home() + before = and_showing(nodes) + fab = node_by_id(nodes, "fab") or find_node(nodes, content_desc="Create folder") + tapped = tap_node(fab) if fab else False + and_enter("new_folder") + anodes = ui() + after = and_showing(anodes) + et = node_by_id(anodes, "et") + btn_create = node_by_id(anodes, "btn_create") + title = find_node_ci(anodes, "New folder") + ok = (tapped and surface_changed(before, after) and et is not None + and btn_create is not None and title is not None) + record("structure_newfolder_dialog_appears", ok, + "" if ok else "behavior_wrong: New-folder dialog subtree (et Title + btn_create) did not appear", + depth=1, jump_kind="transition", + expect="new-folder dialog subtree (et Title field + btn_create) added over home sheet") + + +@and_test(expects=("structure_note_options_sheet_appears",)) +def test_note_options_sheet_appears(): + """selection -> fab_selection 'More options' -> Note-options sheet appears + (tv_dialog_title 'Note options' + many action rows). Assert the count of + clickable rows increased and >=5 named option rows are present.""" + ok_folder, _ = open_folder_from_fresh("General") + made, fnodes = make_one_note("OptNote", "a b") + row = find_note_row(fnodes, "OptNote") or (scroll_into_view("OptNote") and find_note_row(ui(), "OptNote")) + ok_sel, sel_nodes = and_reach_selection(row) + n_before = len([n for n in sel_nodes if n.get("clickable") == "true"]) + ok_opt, onodes = and_enter_note_options(sel_nodes) + title = node_by_id(onodes, "tv_dialog_title") + is_options = bool(title and title.get("text", "") == "Note options") + option_rows = [node_by_id(onodes, r) for r in + ("tv_open_in", "tv_pin_note", "tv_share_note", "tv_duplicate_note", + "tv_copy_to_clipboard", "tv_move_note")] + n_options = sum(1 for r in option_rows if r is not None) + n_after = len([n for n in onodes if n.get("clickable") == "true"]) + ok = (ok_folder and made and ok_sel and ok_opt and is_options + and n_options >= 5 and n_after > n_before) + record("structure_note_options_sheet_appears", ok, + "" if ok else f"behavior_wrong: Note-options sheet subtree did not appear / rows not increased " + f"(options={n_options}, clickable {n_before}->{n_after})", + depth=2, jump_kind="transition", + expect="Note options sheet ('Note options' title + >=5 action rows), clickable count increases") + + +@and_test(expects=("structure_reading_mode_subtree",)) +def test_reading_mode_subtree(): + """Note options -> 'Reading Mode' -> reading-mode subtree + (fab_next + fab_previous + fab 'Edit') appears.""" + ok_folder, _ = open_folder_from_fresh("General") + made, fnodes = make_one_note("ReadNote", "x y") + row = find_note_row(fnodes, "ReadNote") or (scroll_into_view("ReadNote") and find_note_row(ui(), "ReadNote")) + ok_sel, sel_nodes = and_reach_selection(row) + ok_opt, onodes = and_enter_note_options(sel_nodes) + ok_read, rnodes = and_enter_reading_mode(onodes) + fab_next = node_by_id(rnodes, "fab_next") or find_node(rnodes, content_desc="Next") + fab_prev = node_by_id(rnodes, "fab_previous") or find_node(rnodes, content_desc="Previous") + fab_edit = find_node(rnodes, content_desc="Edit") + ok = (ok_folder and made and ok_sel and ok_opt and ok_read + and fab_next is not None and fab_prev is not None and fab_edit is not None) + record("structure_reading_mode_subtree", ok, + "" if ok else "behavior_wrong: reading-mode subtree (fab_next/fab_previous/fab Edit) did not appear", + depth=3, jump_kind="transition", + expect="reading-mode subtree fab_next+fab_previous+fab 'Edit' appears after Reading Mode") + + +@and_test(expects=("structure_settings_list_appears",)) +def test_settings_list_appears(): + """HOME -> ib_settings -> Settings list subtree appears (rows incl. 'General' + and 'About'). surface_changed True.""" + nodes = fresh_home() + before = and_showing(nodes) + ok_settings, snodes = and_enter_settings(nodes) + after = and_showing(snodes) + has_general = find_node_ci(snodes, "General") is not None + has_about = find_node_ci(snodes, "About") is not None + ok = ok_settings and surface_changed(before, after) and has_general and has_about + record("structure_settings_list_appears", ok, + "" if ok else "behavior_wrong: Settings list subtree (General/About rows) did not appear", + depth=1, jump_kind="transition", + expect="Settings list subtree (rows incl. General + About) replaces home sheet") + + +@and_test(expects=("structure_general_settings_rows",)) +def test_general_settings_rows(): + """Settings -> 'General' -> General-settings rows subtree appears (rows incl. + 'Theme' and 'Language'). surface_changed vs the Settings list.""" + nodes = fresh_home() + ok_settings, snodes = and_enter_settings(nodes) + before = and_showing(snodes) + gen = find_node_ci(snodes, "General") + tapped = tap_node(gen) if gen else False + and_enter("general") + gnodes = ui() + after = and_showing(gnodes) + has_theme = (find_node_ci(gnodes, "Theme") is not None + or scroll_into_view("Theme") is not None) + has_language = (find_node_ci(ui(), "Language") is not None + or scroll_into_view("Language") is not None) + ok = ok_settings and tapped and surface_changed(before, after) and has_theme and has_language + record("structure_general_settings_rows", ok, + "" if ok else "behavior_wrong: General-settings rows subtree (Theme/Language) did not appear", + depth=2, jump_kind="transition", + expect="General-settings rows subtree (rows incl. Theme + Language) appears") + + +@and_test(expects=("structure_editor_toolbar_shape",)) +def test_editor_toolbar_shape(): + """Open the editor as the trigger, then assert the toolbar bab_toolbar has a + FIXED shape: exactly the 4 ImageButtons row + (undo_history/undo/redo/redo_history).""" + ok_folder, fnodes = open_folder_from_fresh("General") + before = node_by_id(fnodes, "bab_toolbar") + ok_editor, enodes = and_enter_editor() + toolbar = node_by_id(enodes, "bab_toolbar") + ids = ("ib_undo_history", "ib_undo", "ib_redo", "ib_redo_history") + present = [node_by_id(enodes, r) for r in ids] + n_present = sum(1 for b in present if b is not None) + all_imgbtn = all(b is not None and "ImageButton" in b.get("class", "") for b in present) + ok = (ok_folder and ok_editor and before is None + and toolbar is not None and n_present == 4 and all_imgbtn) + record("structure_editor_toolbar_shape", ok, + "" if ok else f"behavior_wrong: editor toolbar shape wrong " + f"({n_present}/4 ImageButtons, all_imgbtn={all_imgbtn})", + depth=2, jump_kind="transition", + expect="bab_toolbar contains exactly 4 ImageButtons (undo_history/undo/redo/redo_history)") + + +# ════════════════════════════════════════════════════════════════════════════ +# VLM tests — EXACTLY 8 records. Navigate to the correct screen, then screenshot +# and ask a specific YES/NO rendered-property question phrased from what the +# original actually renders (verified from live screenshots). +# ════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_home_grid_vlm",)) +def test_home_grid_vlm(): + """HOME shows a 2x2 grid of FOUR library cards.""" + fresh_home() + vlm_assert("structure_home_grid", + "In the lower white panel of this note-taking app, is there a 2 by 2 " + "grid of exactly four rectangular cards labelled All, Recent, " + "Scheduled and Archived?", + RESULTS_DIR, depth=0, jump_kind="none", tag="layout") + + +@and_test(expects=("structure_home_cards_color_vlm",)) +def test_home_cards_color_vlm(): + """The four library cards are color-coded (each a different accent color on + its border/icon/label). Verified render: outlined cards, All=blue, + Recent=amber, Scheduled=red, Archived=purple.""" + fresh_home() + vlm_assert("structure_home_cards_color", + "Are the four library cards color-coded so that each card's outline, " + "icon and label use a DIFFERENT accent color (one blue, one " + "amber/orange, one red, one purple)?", + RESULTS_DIR, depth=0, jump_kind="none", tag="color") + + +@and_test(expects=("structure_home_fab_position_vlm",)) +def test_home_fab_position_vlm(): + """The 'Create folder' action button (a dark rounded-square with a folder+add + icon) sits in the bottom-right corner of HOME.""" + fresh_home() + vlm_assert("structure_home_fab_position", + "Is there a solid dark (black) rounded-square floating button " + "showing a small plus/add icon in the BOTTOM-RIGHT corner of the " + "screen?", + RESULTS_DIR, depth=0, jump_kind="none", tag="position") + + +@and_test(expects=("structure_editor_title_above_body_vlm",)) +def test_editor_title_above_body_vlm(): + """Note editor: the Title field is ABOVE the Body field.""" + open_folder_from_fresh("General") + and_enter_editor() + vlm_assert("structure_editor_title_above_body", + "In this note editor, is the single-line 'Title' input field " + "positioned ABOVE the larger multi-line 'Body' input area?", + RESULTS_DIR, depth=2, jump_kind="none", tag="position") + + +@and_test(expects=("structure_editor_toolbar_row_vlm",)) +def test_editor_toolbar_row_vlm(): + """Note editor: a horizontal row of exactly 4 toolbar icons sits just above + the on-screen keyboard (verified: undo-history/undo/redo/redo-history).""" + open_folder_from_fresh("General") + and_enter_editor() # editor auto-focuses Title -> keyboard is up + vlm_assert("structure_editor_toolbar_row", + "Just ABOVE the on-screen keyboard on this note editor, is there a " + "single horizontal row of exactly four evenly spaced icon buttons " + "(undo/redo style arrows)?", + RESULTS_DIR, depth=2, jump_kind="none", tag="position") + + +@and_test(expects=("structure_reading_mode_fullscreen_vlm",)) +def test_reading_mode_fullscreen_vlm(): + """Reading mode is a full-screen / immersive layout: the note title and body + render as static text on a mostly-empty page, with only a small edit FAB and + prev/next arrows for chrome.""" + open_folder_from_fresh("General") + made, fnodes = make_one_note("VlmRead", "hello world here") + row = find_note_row(fnodes, "VlmRead") or (scroll_into_view("VlmRead") and find_note_row(ui(), "VlmRead")) + ok_sel, sel_nodes = and_reach_selection(row) + if ok_sel: + ok_opt, onodes = and_enter_note_options(sel_nodes) + if ok_opt: + and_enter_reading_mode(onodes) + vlm_assert("structure_reading_mode_fullscreen", + "Does this screen show the note's title and text as static " + "(non-editable) content on a large, mostly empty full-screen page " + "with no 'Title'/'Body' input boxes and no on-screen keyboard?", + RESULTS_DIR, depth=3, jump_kind="none", tag="layout") + + +@and_test(expects=("structure_folder_label_row_vlm",)) +def test_folder_label_row_vlm(): + """On the folder screen, the label filter row (an 'All' chip + add-label + button) sits directly under the folder title/subtitle.""" + open_folder_from_fresh("General") + vlm_assert("structure_folder_label_row", + "Directly beneath the folder's 'General' title and note-count, is " + "there a horizontal row with a filled dark pill labelled 'All' next " + "to a small outlined add (+) button?", + RESULTS_DIR, depth=1, jump_kind="none", tag="position") + + +@and_test(expects=("structure_newfolder_swatches_vlm",)) +def test_newfolder_swatches_vlm(): + """The New-folder dialog shows a row of colored circular color-swatches.""" + nodes = fresh_home() + fab = node_by_id(nodes, "fab") or find_node(nodes, content_desc="Create folder") + if fab: + tap_node(fab) + and_enter("new_folder") + vlm_assert("structure_newfolder_swatches", + "In this 'New folder' dialog, under a 'Color' label, is there a row " + "of several small circular color swatches in different colors?", + RESULTS_DIR, depth=1, jump_kind="none", tag="shape") + + +# ── Registry & entrypoint ──────────────────────────────────────────────────── +TESTS = [ + # GATE + test_gate_home_sheet, + test_gate_default_folder, + test_gate_library_grid_count, + # SHAPE deltas + test_folder_replaces_home, + test_editor_subtree_appears, + test_selection_bar_appears, + test_notesview_sheet_appears, + test_newfolder_dialog_appears, + test_note_options_sheet_appears, + test_reading_mode_subtree, + test_settings_list_appears, + test_general_settings_rows, + test_editor_toolbar_shape, + # VLM (exactly 8) + test_home_grid_vlm, + test_home_cards_color_vlm, + test_home_fab_position_vlm, + test_editor_title_above_body_vlm, + test_editor_toolbar_row_vlm, + test_reading_mode_fullscreen_vlm, + test_folder_label_row_vlm, + test_newfolder_swatches_vlm, +] + +if __name__ == "__main__": + run_suite(TESTS, "structure") diff --git a/android/alialbaali-noto/tests/test_android_text.py b/android/alialbaali-noto/tests/test_android_text.py new file mode 100644 index 0000000000000000000000000000000000000000..f37c3e53d379d1c77243d907ef69d66776bc2ebd --- /dev/null +++ b/android/alialbaali-noto/tests/test_android_text.py @@ -0,0 +1,719 @@ +#!/usr/bin/env python3 +"""TEXT module — Noto (minimal note-taking app). + +Lane ownership: CONTENT / OUTPUT text, and the SOLE owner of exact-string +equality. Every test drives the app through the real user path and then reads the +PRODUCED string out of a fresh ui(), asserting it matches what the original +renders — a dynamic count string ("1 Note" vs "2 Notes"), a status/subtitle line +that a trigger creates (" • 1 Selected"), an empty-state / no-match placeholder, +an input HINT, an icon control's content-desc, echoed user text, and the +reading-mode paging label. The discriminating half is the CHANGE: the string is +ABSENT before the trigger and PRESENT after, so a dead shell that clones the +layout but implements nothing FAILS. + +What this lane does NOT assert (ceded): the numeric word/note COUNT (computation — +we assert the singular/plural WORDING, never the number), a checked/selected bit +(states), pure reachability or tree shape (navigation / structure), whether a +record survives a kill (interaction/data). A label we TAP to navigate is +navigation's trigger; the same label ASSERTED as content is ours. + +VERIFIED LIVE before authoring (character-for-character, on com.noto.debug): + * Empty folder: tv_placeholder text == "Folder is empty." + * Search no-match (query "zzzznomatch"): tv_placeholder text == + "No notes found containing the search term." (trailing period). The matching + note row DISAPPEARS during the query and returns when it is cleared. + * Folder subtitle tv_folder_notes_count content-desc == "0 Notes" (empty) / + "1 Note" (singular) / "2 Notes" (plural). + * HOME sheet tv_folders_count content-desc == "0 Folders" on a cleared install + (the default General folder is excluded). + * Long-press a note -> subtitle content-desc == "1 Note • 1 Selected" + (bullet U+2022) where none was. + * A fab-created note: tv_created_at text == "Created just now", + tv_accessed_at text == "Accessed just now"; empty editor et_note_title hint + == "Title", et_note_body hint == "Body". + * A typed note echoes verbatim in its folder row (tv_note_title / tv_note_body) + and again in Reading Mode (drawn read-only text). + * Reading Mode (long-press -> More options -> "Reading Mode") is scoped to the + single opened note, so tv_notes_count content-desc == "1 / 1 Note". + * fab content-desc == "Create note" (in a folder) / "Create folder" (on HOME); + Settings screen title == "Settings"; Note-options sheet row == "Reading Mode". + +VLM budget for this file: EXACTLY 3 vlm_assert records (2 fine-grained position + +1 content), reserved for text that is either drawn read-only (reading mode) or +whose POSITION on screen adds real signal a dump cannot give. + +Invoke: + python3 test_android_text.py +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ══════════════════════════════════════════════════════════════════════════════ +# Local setup helpers +# ══════════════════════════════════════════════════════════════════════════════ + +def dismiss_prompts(): + """Dismiss the first-run system notification-permission dialog (and any stray + prompt) sitting in front of the already-loaded Noto home. Both ASCII "Don't + allow" and the curly-apostrophe "Don't allow" (U+2019) are matched. It can + reappear on a plain relaunch, so call it after every launch/restart.""" + for _ in range(3): + nodes = ui() + b = (find_node_ci(nodes, "Don't allow") or find_node_ci(nodes, "Don’t allow") + or find_node_ci(nodes, "Allow")) + if b and is_safe(b): + tap_node(b) + settle("tap") + continue + break + + +def fresh_home(): + """Kill + relaunch (data kept), dismiss any prompt, land on the HOME sheet.""" + restart_app() + wait_for_foreground() + dismiss_prompts() + return ui() + + +def clean_home(): + """pm clear -> virgin install (default General folder, 0 notes, 0 folders), + dismiss the first-run prompt, land on the HOME sheet.""" + clear_data() + launch_app() + wait_for_foreground() + dismiss_prompts() + return ui() + + +def on_home_sheet(nodes=None): + nodes = ui() if nodes is None else nodes + return node_by_id(nodes, "tv_dialog_title") is not None + + +def all_text(nodes): + return " | ".join(n.get("text", "") for n in nodes if n.get("text")) + + +def norm(s): + return (s or "").strip().casefold() + + +def subtitle_desc(nodes=None): + """The folder-view subtitle content-desc (note count / selection / paging).""" + nodes = ui() if nodes is None else nodes + n = node_by_id(nodes, "tv_folder_notes_count") or node_by_id(nodes, "tv_notes_count") + return n.get("content-desc", "") if n else "" + + +def note_rows(nodes): + return [n for n in nodes + if n.get("resource-id", "").rsplit("/", 1)[-1] == "tv_note_title"] + + +# ── Depth-backing navigation helpers (named and_enter_*/and_reach_* so the audit +# attributes each declared depth to a real navigation call). ───────────────── + +def and_enter_folder(name="General"): + """HOME sheet -> tap a folder row -> its note-list surface. Counts one + surface. Returns True when the folder title is showing.""" + n = find_node(ui(), text=name) + if n is None or not tap_node(n): + return False + settle("tap") + and_enter("folder:" + name) + tit = node_by_id(ui(), "tv_folder_title") + return tit is not None and tit.get("text") == name + + +def and_enter_editor(): + """FOLDER note-list -> fab 'Create note' -> the note editor. Counts one + surface. Returns True when et_note_title is present.""" + fab = find_node(ui(), content_desc="Create note") + if fab is None or not tap_node(fab): + return False + settle("tap") + and_enter("editor") + return node_by_id(ui(), "et_note_title") is not None + + +def and_enter_search(): + """FOLDER note-list -> bottom-bar 'Search' -> the search surface. Counts one + surface. Returns True when the et_search field is present.""" + s = find_node(ui(), content_desc="Search") + if s is None or not tap_node(s): + return False + settle("tap") + and_enter("search") + return node_by_id(ui(), "et_search") is not None + + +def and_enter_selection(title=None): + """FOLDER note-list -> LONG-PRESS a note row -> selection mode. Counts one + surface. Returns the note node long-pressed (or None).""" + nodes = ui() + note = (find_node(nodes, text=title) if title else None) or ( + note_rows(nodes)[0] if note_rows(nodes) else None) + if note is None or not long_press(note): + return None + settle("tap") + and_enter("selection") + return note + + +def and_reach_note_options(): + """SELECTION mode -> fab_selection 'More options' -> the Note-options bottom + sheet. Counts one surface. Returns True when the sheet title shows.""" + mo = node_by_id(ui(), "fab_selection") or find_node(ui(), content_desc="More options") + if mo is None or not tap_node(mo): + return False + settle("tap") + and_enter("note_options") + t = node_by_id(ui(), "tv_dialog_title") + return t is not None and norm(t.get("text")) == norm("Note options") + + +def and_reach_reading_mode(): + """Note-options sheet -> 'Reading Mode' row -> the reading surface. Counts one + surface. Dismisses the first-run immersive cling if it appears. Returns True + when the reading paging label (tv_notes_count) is present.""" + rm = find_node_ci(ui(), "Reading Mode") or node_by_id(ui(), "tv_open_in") + if rm is None or not tap_node(rm): + return False + settle("tap") + and_enter("reading_mode") + got = find_node_ci(ui(), "Got it") or node_by_id(ui(), "ok") + if got and is_safe(got): + tap_node(got) + settle("tap") + return node_by_id(ui(), "tv_notes_count") is not None + + +def and_enter_settings(): + """HOME sheet -> ib_settings 'Settings' -> the Settings list. Counts one + surface. Returns True when the 'General' row is present.""" + s = node_by_id(ui(), "ib_settings") or find_node(ui(), content_desc="Settings") + if s is None or not tap_node(s): + return False + settle("tap") + and_enter("settings") + return (find_node(ui(), content_desc="General") is not None + or find_node(ui(), text="General") is not None) + + +# ── Note-authoring helper (drives the real user path; Back auto-saves) ───────── + +def create_note_in_general(title, body=""): + """From a fresh HOME sheet: open General, fab a new note, type title/body, + hide the keyboard and Back (auto-save -> HOME sheet). Returns True on success. + Assumes the caller has already reached a HOME sheet.""" + if not and_enter_folder("General"): + return False + if not and_enter_editor(): + return False + t = node_by_id(ui(), "et_note_title") + if t is None or not type_text(t, title): + return False + if body: + b = node_by_id(ui(), "et_note_body") + if b is not None: + type_text(b, body) + hide_keyboard() + back() # auto-save; from a fab note -> HOME sheet + settle("tap") + and_reset_depth() + return on_home_sheet() + + +# ══════════════════════════════════════════════════════════════════════════════ +# Tests +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_empty_folder_placeholder", "text_empty_folder_placeholder_vlm")) +def test_empty_folder_placeholder(): + """A cleared General folder shows the empty-state placeholder verbatim.""" + clean_home() + if not and_enter_folder("General"): + record("text_empty_folder_placeholder", False, + "setup_failed: could not open the General folder from HOME", + depth=1, jump_kind="value", expect="placeholder 'Folder is empty.'") + return + ph = node_by_id(ui(), "tv_placeholder") + got = ph.get("text", "") if ph else "" + ok = norm(got) == norm("Folder is empty.") + record("text_empty_folder_placeholder", ok, + "" if ok else f"behavior_wrong: empty-folder placeholder was {got!r}, " + f"expected 'Folder is empty.'", + depth=1, jump_kind="value", expect="placeholder text == 'Folder is empty.'") + vlm_assert("text_empty_folder_placeholder", + "Is a short single-line message like 'Folder is empty.' shown " + "roughly centered in the middle of an otherwise blank note list " + "(not at the top or bottom)?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("text_search_nomatch_placeholder",)) +def test_search_nomatch_placeholder(): + """Searching a term no note contains shows the no-match placeholder verbatim, + where the empty-folder placeholder was NOT (before/after string).""" + clean_home() + if not and_enter_folder("General"): + record("text_search_nomatch_placeholder", False, + "setup_failed: could not open the General folder", + depth=2, jump_kind="value", + expect="placeholder == 'No notes found containing the search term.'") + return + if not and_enter_search(): + record("text_search_nomatch_placeholder", False, + "setup_failed: could not open the search surface", + depth=2, jump_kind="value", + expect="placeholder == 'No notes found containing the search term.'") + return + before = node_by_id(ui(), "tv_placeholder") + absent = norm(before.get("text") if before else "") != norm( + "No notes found containing the search term.") + et = node_by_id(ui(), "et_search") + type_text(et, "zzzznomatch") + settle("tap") + after = node_by_id(ui(), "tv_placeholder") + got = after.get("text", "") if after else "" + present = norm(got) == norm("No notes found containing the search term.") + ok = absent and present + record("text_search_nomatch_placeholder", ok, + "" if ok else f"behavior_wrong: no-match placeholder was {got!r}, " + f"expected 'No notes found containing the search term.'", + depth=2, jump_kind="value", + expect="placeholder == 'No notes found containing the search term.'") + + +@and_test(expects=("text_search_clears_note_returns",)) +def test_search_clears_note_returns(): + """A matching note row is PRESENT in the folder, ABSENT while a non-matching + query is typed, and PRESENT again once the query is cleared (string flip).""" + clean_home() + if not create_note_in_general("AlphaFindMe", "body text"): + record("text_search_clears_note_returns", False, + "setup_failed: could not create the seed note", + depth=2, jump_kind="transition", + expect="note row 'AlphaFindMe' toggles absent<->present with search") + return + if not and_enter_folder("General"): + record("text_search_clears_note_returns", False, + "setup_failed: could not reopen the General folder", + depth=2, jump_kind="transition", + expect="note row 'AlphaFindMe' toggles absent<->present with search") + return + present_before = find_node(ui(), text="AlphaFindMe") is not None + if not and_enter_search(): + record("text_search_clears_note_returns", False, + "setup_failed: could not open search", + depth=2, jump_kind="transition", + expect="note row 'AlphaFindMe' toggles absent<->present with search") + return + et = node_by_id(ui(), "et_search") + type_text(et, "zzzznomatch") + settle("tap") + absent_during = find_node(ui(), text="AlphaFindMe") is None + # The search-field end icon (content-desc "Clear") empties the QUERY box only; + # it is the input-clear affordance, not a destructive data action, so tap it + # directly (safe_tap/is_safe would veto it on the "clear" substring). + clr = node_by_id(ui(), "text_input_end_icon") or find_node(ui(), content_desc="Clear") + cleared = tap_node(clr) if clr else False + if cleared: + settle("tap") + # The note list is a RecyclerView: after the query is cleared it re-populates + # over a frame or two, so a single dump can catch it mid-recycle. Re-dump a + # bounded number of times for the restored row rather than reading only once. + present_after = False + for _ in range(4): + if find_node(ui(), text="AlphaFindMe") is not None: + present_after = True + break + settle("tap") + ok = present_before and absent_during and cleared and present_after + record("text_search_clears_note_returns", ok, + "" if ok else "behavior_wrong: note row did not toggle " + f"absent/present with the search query " + f"(before={present_before}, during={absent_during}, " + f"cleared={cleared}, after={present_after})", + depth=2, jump_kind="transition", + expect="'AlphaFindMe' present -> absent (nomatch) -> present (cleared)") + + +@and_test(expects=("text_folder_count_singular",)) +def test_folder_count_singular(): + """After exactly ONE note, the folder subtitle uses the SINGULAR wording + '1 Note' (not '1 Notes') — this is the string, not the number.""" + clean_home() + if not create_note_in_general("OnlyNoteHere"): + record("text_folder_count_singular", False, + "setup_failed: could not create the single note", + depth=1, jump_kind="value", expect="subtitle desc == '1 Note'") + return + if not and_enter_folder("General"): + record("text_folder_count_singular", False, + "setup_failed: could not reopen the General folder", + depth=1, jump_kind="value", expect="subtitle desc == '1 Note'") + return + got = subtitle_desc() + ok = norm(got) == norm("1 Note") + record("text_folder_count_singular", ok, + "" if ok else f"behavior_wrong: singular subtitle was {got!r}, " + f"expected '1 Note'", + depth=1, jump_kind="value", expect="subtitle content-desc == '1 Note'") + + +@and_test(expects=("text_folder_count_plural",)) +def test_folder_count_plural(): + """After TWO notes, the folder subtitle uses the PLURAL wording '2 Notes'.""" + clean_home() + if not create_note_in_general("FirstNoteAA"): + record("text_folder_count_plural", False, + "setup_failed: could not create the first note", + depth=1, jump_kind="value", expect="subtitle desc == '2 Notes'") + return + if not create_note_in_general("SecondNoteBB"): + record("text_folder_count_plural", False, + "setup_failed: could not create the second note", + depth=1, jump_kind="value", expect="subtitle desc == '2 Notes'") + return + if not and_enter_folder("General"): + record("text_folder_count_plural", False, + "setup_failed: could not reopen the General folder", + depth=1, jump_kind="value", expect="subtitle desc == '2 Notes'") + return + got = subtitle_desc() + ok = norm(got) == norm("2 Notes") + record("text_folder_count_plural", ok, + "" if ok else f"behavior_wrong: plural subtitle was {got!r}, " + f"expected '2 Notes'", + depth=1, jump_kind="value", expect="subtitle content-desc == '2 Notes'") + + +@and_test(expects=("text_home_folders_count_zero",)) +def test_home_folders_count_zero(): + """On a virgin install the HOME sheet folders count reads '0 Folders' (the + default General folder is excluded from the count wording).""" + clean_home() + n = node_by_id(ui(), "tv_folders_count") + got = n.get("content-desc", "") if n else "" + ok = norm(got) == norm("0 Folders") + record("text_home_folders_count_zero", ok, + "" if ok else f"behavior_wrong: HOME folders count was {got!r}, " + f"expected '0 Folders'", + depth=0, jump_kind="value", expect="tv_folders_count desc == '0 Folders'") + + +@and_test(expects=("text_selection_subtitle",)) +def test_selection_subtitle(): + """Long-pressing a note turns the folder subtitle into the selection wording + that ends with '• 1 Selected', where it did not before (string flip).""" + clean_home() + if not create_note_in_general("SelectMeNote"): + record("text_selection_subtitle", False, + "setup_failed: could not create the note to select", + depth=1, jump_kind="transition", + expect="subtitle gains '• 1 Selected'") + return + if not and_enter_folder("General"): + record("text_selection_subtitle", False, + "setup_failed: could not reopen the General folder", + depth=1, jump_kind="transition", + expect="subtitle gains '• 1 Selected'") + return + before = subtitle_desc() + absent = "selected" not in norm(before) + if and_enter_selection("SelectMeNote") is None: + record("text_selection_subtitle", False, + "setup_failed: long-press did not enter selection mode", + depth=1, jump_kind="transition", + expect="subtitle gains '• 1 Selected'") + return + after = subtitle_desc() + present = "1 selected" in norm(after) and "•" in after + ok = absent and present + record("text_selection_subtitle", ok, + "" if ok else f"behavior_wrong: selection subtitle was {after!r}, " + f"expected it to contain '• 1 Selected'", + depth=1, jump_kind="transition", + expect="subtitle content-desc contains '• 1 Selected'") + + +@and_test(expects=("text_new_note_created_timestamp", "text_new_note_created_timestamp_vlm")) +def test_new_note_created_timestamp(): + """A brand-new note's creation line reads 'Created just now', and the same + fresh editor also reads 'Accessed just now' below it.""" + clean_home() + if not and_enter_folder("General"): + record("text_new_note_created_timestamp", False, + "setup_failed: could not open the General folder", + depth=2, jump_kind="value", expect="tv_created_at == 'Created just now'") + return + if not and_enter_editor(): + record("text_new_note_created_timestamp", False, + "setup_failed: could not open the note editor", + depth=2, jump_kind="value", expect="tv_created_at == 'Created just now'") + return + nodes = ui() + created = node_by_id(nodes, "tv_created_at") + got = created.get("text", "") if created else "" + ok = norm(got) == norm("Created just now") + record("text_new_note_created_timestamp", ok, + "" if ok else f"behavior_wrong: creation line was {got!r}, " + f"expected 'Created just now'", + depth=2, jump_kind="value", expect="tv_created_at text == 'Created just now'") + vlm_assert("text_new_note_created_timestamp", + "Near the BOTTOM of the note-editing area, below the text fields, " + "are two small timestamp lines beginning with 'Created' and " + "'Accessed' shown one under the other?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("text_new_note_accessed_timestamp",)) +def test_new_note_accessed_timestamp(): + """The fresh-note access line reads 'Accessed just now' verbatim.""" + clean_home() + if not and_enter_folder("General"): + record("text_new_note_accessed_timestamp", False, + "setup_failed: could not open the General folder", + depth=2, jump_kind="value", expect="tv_accessed_at == 'Accessed just now'") + return + if not and_enter_editor(): + record("text_new_note_accessed_timestamp", False, + "setup_failed: could not open the note editor", + depth=2, jump_kind="value", expect="tv_accessed_at == 'Accessed just now'") + return + accessed = node_by_id(ui(), "tv_accessed_at") + got = accessed.get("text", "") if accessed else "" + ok = norm(got) == norm("Accessed just now") + record("text_new_note_accessed_timestamp", ok, + "" if ok else f"behavior_wrong: access line was {got!r}, " + f"expected 'Accessed just now'", + depth=2, jump_kind="value", expect="tv_accessed_at text == 'Accessed just now'") + + +@and_test(expects=("text_editor_title_hint",)) +def test_editor_title_hint(): + """An empty note-title field shows the hint 'Title'.""" + clean_home() + if not and_enter_folder("General"): + record("text_editor_title_hint", False, + "setup_failed: could not open the General folder", + depth=2, jump_kind="value", expect="et_note_title hint == 'Title'") + return + if not and_enter_editor(): + record("text_editor_title_hint", False, + "setup_failed: could not open the note editor", + depth=2, jump_kind="value", expect="et_note_title hint == 'Title'") + return + t = node_by_id(ui(), "et_note_title") + got = t.get("text", "") if t else "" + ok = norm(got) == norm("Title") + record("text_editor_title_hint", ok, + "" if ok else f"behavior_wrong: title hint was {got!r}, expected 'Title'", + depth=2, jump_kind="value", expect="et_note_title hint text == 'Title'") + + +@and_test(expects=("text_editor_body_hint",)) +def test_editor_body_hint(): + """An empty note-body field shows the hint 'Body'.""" + clean_home() + if not and_enter_folder("General"): + record("text_editor_body_hint", False, + "setup_failed: could not open the General folder", + depth=2, jump_kind="value", expect="et_note_body hint == 'Body'") + return + if not and_enter_editor(): + record("text_editor_body_hint", False, + "setup_failed: could not open the note editor", + depth=2, jump_kind="value", expect="et_note_body hint == 'Body'") + return + b = node_by_id(ui(), "et_note_body") + got = b.get("text", "") if b else "" + ok = norm(got) == norm("Body") + record("text_editor_body_hint", ok, + "" if ok else f"behavior_wrong: body hint was {got!r}, expected 'Body'", + depth=2, jump_kind="value", expect="et_note_body hint text == 'Body'") + + +@and_test(expects=("text_echoed_note_title_body",)) +def test_echoed_note_title_body(): + """User-typed title and body echo VERBATIM in the note's folder-list row — + the row was absent before the note existed (string flip).""" + clean_home() + if not and_enter_folder("General"): + record("text_echoed_note_title_body", False, + "setup_failed: could not open the General folder", + depth=1, jump_kind="value", expect="row shows 'MyNoteXYZ' + body") + return + absent = find_node(ui(), text="MyNoteXYZ") is None + and_reset_depth() + if not create_note_in_general("MyNoteXYZ", "hello world foo bar"): + record("text_echoed_note_title_body", False, + "setup_failed: could not create the note", + depth=1, jump_kind="value", expect="row shows 'MyNoteXYZ' + body") + return + if not and_enter_folder("General"): + record("text_echoed_note_title_body", False, + "setup_failed: could not reopen the General folder", + depth=1, jump_kind="value", expect="row shows 'MyNoteXYZ' + body") + return + nodes = ui() + title_ok = find_node(nodes, text="MyNoteXYZ") is not None + body_node = node_by_id(nodes, "tv_note_body") + body_ok = body_node is not None and norm(body_node.get("text")) == norm( + "hello world foo bar") + ok = absent and title_ok and body_ok + record("text_echoed_note_title_body", ok, + "" if ok else "behavior_wrong: typed title/body did not echo verbatim " + f"in the folder row (title_ok={title_ok}, body_ok={body_ok})", + depth=1, jump_kind="value", + expect="folder row title=='MyNoteXYZ' body=='hello world foo bar'") + + +@and_test(expects=("text_reading_mode_paging_label", + "text_reading_mode_paging_label_vlm")) +def test_reading_mode_paging_label(): + """In Reading Mode (scoped to the one opened note) the paging label reads + '1 / 1 Note'; the note's typed title+body render verbatim in the drawn + read-only view (VLM, content).""" + clean_home() + if not create_note_in_general("ReadMeNote", "the quick brown fox jumps"): + record("text_reading_mode_paging_label", False, + "setup_failed: could not create the note", + depth=3, jump_kind="value", expect="paging label == '1 / 1 Note'") + return + if not and_enter_folder("General"): + record("text_reading_mode_paging_label", False, + "setup_failed: could not reopen the General folder", + depth=3, jump_kind="value", expect="paging label == '1 / 1 Note'") + return + if and_enter_selection("ReadMeNote") is None: + record("text_reading_mode_paging_label", False, + "setup_failed: long-press did not enter selection mode", + depth=3, jump_kind="value", expect="paging label == '1 / 1 Note'") + return + if not and_reach_note_options(): + record("text_reading_mode_paging_label", False, + "setup_failed: could not open the Note-options sheet", + depth=3, jump_kind="value", expect="paging label == '1 / 1 Note'") + return + if not and_reach_reading_mode(): + record("text_reading_mode_paging_label", False, + "setup_failed: could not enter Reading Mode", + depth=3, jump_kind="value", expect="paging label == '1 / 1 Note'") + return + got = subtitle_desc() + ok = norm(got) == norm("1 / 1 Note") + record("text_reading_mode_paging_label", ok, + "" if ok else f"behavior_wrong: reading-mode paging label was {got!r}, " + f"expected '1 / 1 Note'", + depth=3, jump_kind="value", expect="tv_notes_count desc == '1 / 1 Note'") + vlm_assert("text_reading_mode_paging_label", + "Does this read-only note view display the title 'ReadMeNote' and " + "the body text 'the quick brown fox jumps'?", + RESULTS_DIR, tag="content") + + +@and_test(expects=("text_fab_create_note_desc",)) +def test_fab_create_note_desc(): + """Inside a folder the create button's content-desc reads 'Create note' + (it read 'Create folder' on the HOME sheet — string differs by surface).""" + clean_home() + home_fab = find_node(ui(), content_desc="Create folder") + home_ok = home_fab is not None + if not and_enter_folder("General"): + record("text_fab_create_note_desc", False, + "setup_failed: could not open the General folder", + depth=1, jump_kind="value", expect="folder fab desc == 'Create note'") + return + folder_fab = find_node(ui(), content_desc="Create note") + ok = home_ok and folder_fab is not None + record("text_fab_create_note_desc", ok, + "" if ok else "behavior_wrong: folder create button did not expose " + "content-desc 'Create note' (or HOME lacked 'Create folder')", + depth=1, jump_kind="value", + expect="HOME fab desc 'Create folder' -> folder fab desc 'Create note'") + + +@and_test(expects=("text_settings_screen_title",)) +def test_settings_screen_title(): + """Opening Settings from HOME shows the 'Settings' title where none was on the + HOME sheet (before/after string).""" + clean_home() + absent = find_node(ui(), text="Settings") is None + if not and_enter_settings(): + record("text_settings_screen_title", False, + "setup_failed: could not open Settings from HOME", + depth=1, jump_kind="value", expect="Settings title == 'Settings'") + return + present = find_node(ui(), text="Settings") is not None + ok = absent and present + record("text_settings_screen_title", ok, + "" if ok else "behavior_wrong: 'Settings' title did not appear after " + "opening Settings", + depth=1, jump_kind="value", expect="screen title text == 'Settings'") + + +@and_test(expects=("text_note_options_reading_mode_label",)) +def test_note_options_reading_mode_label(): + """The Note-options sheet (long-press -> More options) offers a row labelled + 'Reading Mode' verbatim, absent before the sheet opened (string flip).""" + clean_home() + if not create_note_in_general("OptsNote"): + record("text_note_options_reading_mode_label", False, + "setup_failed: could not create the note", + depth=2, jump_kind="value", expect="sheet row 'Reading Mode'") + return + if not and_enter_folder("General"): + record("text_note_options_reading_mode_label", False, + "setup_failed: could not reopen the General folder", + depth=2, jump_kind="value", expect="sheet row 'Reading Mode'") + return + absent = find_node(ui(), text="Reading Mode") is None + if and_enter_selection("OptsNote") is None: + record("text_note_options_reading_mode_label", False, + "setup_failed: long-press did not enter selection mode", + depth=2, jump_kind="value", expect="sheet row 'Reading Mode'") + return + if not and_reach_note_options(): + record("text_note_options_reading_mode_label", False, + "setup_failed: could not open the Note-options sheet", + depth=2, jump_kind="value", expect="sheet row 'Reading Mode'") + return + row = node_by_id(ui(), "tv_open_in") or find_node(ui(), text="Reading Mode") + got = row.get("text", "") if row else "" + present = norm(got) == norm("Reading Mode") + ok = absent and present + record("text_note_options_reading_mode_label", ok, + "" if ok else f"behavior_wrong: Note-options row was {got!r}, " + f"expected 'Reading Mode'", + depth=2, jump_kind="value", expect="Note-options row text == 'Reading Mode'") + + +TESTS = [ + test_empty_folder_placeholder, + test_search_nomatch_placeholder, + test_search_clears_note_returns, + test_folder_count_singular, + test_folder_count_plural, + test_home_folders_count_zero, + test_selection_subtitle, + test_new_note_created_timestamp, + test_new_note_accessed_timestamp, + test_editor_title_hint, + test_editor_body_hint, + test_echoed_note_title_body, + test_reading_mode_paging_label, + test_fab_create_note_desc, + test_settings_screen_title, + test_note_options_reading_mode_label, +] + + +if __name__ == "__main__": + run_suite(TESTS, "text") diff --git a/android/alialbaali-noto/tests/test_manifest.json b/android/alialbaali-noto/tests/test_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..77622266180cf4b4dd8f3552a4f4294c15d8ba71 --- /dev/null +++ b/android/alialbaali-noto/tests/test_manifest.json @@ -0,0 +1,885 @@ +{ + "manifest_version": 1, + "kit_api_version": 1, + "task_id": "Noto", + "baseline_model": "claude-opus-4-8", + "baseline_package": "", + "total": 136, + "manifest_sha": "766a1ded0bcc", + "tests": [ + { + "name": "computation::computation_folder_count_one", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_folder_count_three", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_folder_count_two", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_folders_count_one", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_folders_count_two", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_home_cards_count", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_home_cards_count_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_reading_paging", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_reading_paging_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_wc_empty", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_wc_five", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_wc_four", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_wc_four_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_wc_lead_trail_space", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_wc_multi_space", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_wc_one", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_wc_punctuation", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_wc_seven_single_chars", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_wc_three", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_wc_title_excluded_body", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_wc_title_excluded_empty", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_wc_two", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_create_folder", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_create_note", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_create_two_folders", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_created_note_card_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_duplicate_note", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_duplicate_note_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_edit_note_body_persists", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_edited_body_survives_process_death", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_folder_survives_process_death", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_move_note_between_folders", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_multi_record_integrity", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_multi_select_count", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_new_folder_note_roundtrip", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_note_options_grid_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_note_survives_process_death", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_pin_note", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_pinned_section_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_second_create_two_rows", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_selection_action_bar_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_selection_check_badge_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_selection_check_dark_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_back_editor_to_home", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_back_general_to_settings", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_back_reading_to_folder", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_back_settings_to_folder", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_chain_editor", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_chain_editor_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_chain_general_settings", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_chain_note_options", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_chain_reading_mode", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_chain_reading_mode_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_chain_theme_dialog", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_folder_bottom_bar_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_all", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_archived", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_folder", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_folder_options", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_home_from_folder", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_more_menu", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_more_menu_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_notes_view", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_notes_view_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_recent", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_search", + "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": "states::states_all_chip_active", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_all_chip_active_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_body_focus", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_home_cards", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_home_cards_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_multiselect_two", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_notes_view_current_state", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_ordering_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_reading_paging_position", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_reading_paging_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_redo_stays_disabled", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_selection_bar_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_selection_count_increment", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_selection_off", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_selection_on", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_selection_on_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_show_count_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_show_count_thumb_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_show_count_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_theme_dark_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_theme_light_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_theme_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_theme_persists_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_theme_selected_mark_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_title_focus", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_undo_disabled_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_undo_enable", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_undo_history_disabled", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "structure::structure_editor_subtree_appears", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_editor_title_above_body_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_editor_toolbar_row_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_editor_toolbar_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_folder_label_row_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_folder_replaces_home", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_default_folder", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_home_sheet", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_library_grid_count", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_general_settings_rows", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_home_cards_color_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_home_fab_position_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_home_grid_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_newfolder_dialog_appears", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_newfolder_swatches_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_note_options_sheet_appears", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_notesview_sheet_appears", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_reading_mode_fullscreen_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_reading_mode_subtree", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_selection_bar_appears", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_list_appears", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "text::text_echoed_note_title_body", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_editor_body_hint", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_editor_title_hint", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_empty_folder_placeholder", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_empty_folder_placeholder_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_fab_create_note_desc", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_folder_count_plural", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_folder_count_singular", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_home_folders_count_zero", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_new_note_accessed_timestamp", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_new_note_created_timestamp", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_new_note_created_timestamp_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_note_options_reading_mode_label", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_reading_mode_paging_label", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_reading_mode_paging_label_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_search_clears_note_returns", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_search_nomatch_placeholder", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_selection_subtitle", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_screen_title", + "module": "text", + "baseline_status": "passed" + } + ], + "ignored": [], + "vlm_assertions": [ + { + "name": "computation::computation_wc_four_vlm", + "module": "computation", + "tag": "content" + }, + { + "name": "computation::computation_home_cards_count_vlm", + "module": "computation", + "tag": "content" + }, + { + "name": "computation::computation_reading_paging_vlm", + "module": "computation", + "tag": "content" + }, + { + "name": "interaction::interaction_duplicate_note_vlm", + "module": "interaction", + "tag": "position" + }, + { + "name": "interaction::interaction_selection_check_dark_vlm", + "module": "interaction", + "tag": "color" + }, + { + "name": "interaction::interaction_selection_check_badge_vlm", + "module": "interaction", + "tag": "shape" + }, + { + "name": "interaction::interaction_selection_action_bar_vlm", + "module": "interaction", + "tag": "layout" + }, + { + "name": "interaction::interaction_pinned_section_vlm", + "module": "interaction", + "tag": "position" + }, + { + "name": "interaction::interaction_note_options_grid_vlm", + "module": "interaction", + "tag": "layout" + }, + { + "name": "interaction::interaction_created_note_card_vlm", + "module": "interaction", + "tag": "size" + }, + { + "name": "navigation::nav_reach_settings_vlm", + "module": "navigation", + "tag": "layout" + }, + { + "name": "navigation::nav_reach_more_menu_vlm", + "module": "navigation", + "tag": "layout" + }, + { + "name": "navigation::nav_reach_notes_view_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_chain_editor_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_chain_reading_mode_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_folder_bottom_bar_vlm", + "module": "navigation", + "tag": "layout" + }, + { + "name": "states::states_selection_on_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_selection_bar_vlm", + "module": "states", + "tag": "layout" + }, + { + "name": "states::states_all_chip_active_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_undo_disabled_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_theme_light_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_theme_selected_mark_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_theme_persists_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_theme_dark_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_show_count_thumb_vlm", + "module": "states", + "tag": "position" + }, + { + "name": "states::states_reading_paging_vlm", + "module": "states", + "tag": "layout" + }, + { + "name": "states::states_home_cards_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "structure::structure_home_grid_vlm", + "module": "structure", + "tag": "layout" + }, + { + "name": "structure::structure_home_cards_color_vlm", + "module": "structure", + "tag": "color" + }, + { + "name": "structure::structure_home_fab_position_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_editor_title_above_body_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_editor_toolbar_row_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_reading_mode_fullscreen_vlm", + "module": "structure", + "tag": "layout" + }, + { + "name": "structure::structure_folder_label_row_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_newfolder_swatches_vlm", + "module": "structure", + "tag": "shape" + }, + { + "name": "text::text_empty_folder_placeholder_vlm", + "module": "text", + "tag": "position" + }, + { + "name": "text::text_new_note_created_timestamp_vlm", + "module": "text", + "tag": "position" + }, + { + "name": "text::text_reading_mode_paging_label_vlm", + "module": "text", + "tag": "content" + } + ], + "vlm_total": 38 +} \ No newline at end of file diff --git a/android/alialbaali-noto/vlm_assertions.json b/android/alialbaali-noto/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..cf070e7e3d01b3dcf8ff07460a92203deda913fe --- /dev/null +++ b/android/alialbaali-noto/vlm_assertions.json @@ -0,0 +1,796 @@ +{ + "schema_version": 2, + "instance_id": "android/alialbaali-noto", + "grading": { + "mode": "inline", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 39, + "with_verdict": 38, + "calibrated": 0, + "usable": null, + "scored_records": 38, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "structure_home_grid_vlm", + "screenshot": "structure_home_grid_vlm.png", + "assertion": "Near the top of this note-taking app's list, is there a 2 by 2 grid of exactly four rectangular cards (labelled All, Recent, Scheduled, Archived)?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "structure_home_grid", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_home_cards_color_vlm", + "screenshot": "structure_home_cards_color_vlm.png", + "assertion": "Are the four library cards each filled with a DIFFERENT solid background color (for example one blue, one amber/orange, one red, one purple), rather than all the same color?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "structure_home_cards_color", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_home_fab_position_vlm", + "screenshot": "structure_home_fab_position_vlm.png", + "assertion": "Is there a circular floating action button (a round '+' / add button) located in the BOTTOM-RIGHT corner of the screen?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_home_fab_position", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_editor_title_above_body_vlm", + "screenshot": "structure_editor_title_above_body_vlm.png", + "assertion": "In this note editor, is the single-line 'Title' input field positioned ABOVE the larger multi-line 'Body' input area?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_editor_title_above_body", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_editor_toolbar_row_vlm", + "screenshot": "structure_editor_toolbar_row_vlm.png", + "assertion": "Is there a single horizontal row of exactly four icon buttons located along the BOTTOM edge of this note editor screen?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "structure_editor_toolbar_row", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_reading_mode_fullscreen_vlm", + "screenshot": "structure_reading_mode_fullscreen_vlm.png", + "assertion": "Does this screen show note text laid out as a large, mostly empty full-screen reading page with minimal toolbar chrome (no title/body text-input boxes)?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "structure_reading_mode_fullscreen", + "rigor": { + "jump_kind": "none", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_folder_label_row_vlm", + "screenshot": "structure_folder_label_row_vlm.png", + "assertion": "Directly beneath the folder's title/subtitle, is there a horizontal row containing a small pill/chip labelled 'All' next to a small add (+) button?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "structure_folder_label_row", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_newfolder_swatches_vlm", + "screenshot": "structure_newfolder_swatches_vlm.png", + "assertion": "In this 'New folder' dialog, under a 'Color' label, is there a row of several small circular color swatches in different colors?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "structure_newfolder_swatches", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_settings_vlm", + "screenshot": "nav_reach_settings_vlm.png", + "assertion": "Is a settings screen showing a vertical list of labelled rows, each row with a small leading icon on its left?", + "form": "question", + "expected": true, + "aspect": "layout", + "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_more_menu_vlm", + "screenshot": "nav_reach_more_menu_vlm.png", + "assertion": "Is a small menu sheet showing a short vertical list of text entries (vault / archive / settings), overlaying the screen near the bottom?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "nav_reach_more_menu", + "rigor": { + "jump_kind": "reach", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_notes_view_vlm", + "screenshot": "nav_reach_notes_view_vlm.png", + "assertion": "Is a bottom sheet dialog anchored to the lower portion of the screen, overlaying a dimmed screen behind it?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_reach_notes_view", + "rigor": { + "jump_kind": "reach", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_chain_editor_vlm", + "screenshot": "nav_chain_editor_vlm.png", + "assertion": "Is there a back-arrow icon at the very top-left of the screen, next to the folder title in the toolbar?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_chain_editor", + "rigor": { + "jump_kind": "reach", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_chain_reading_mode_vlm", + "screenshot": "nav_chain_reading_mode_vlm.png", + "assertion": "Does the screen show note text with left/right paging arrows near the bottom and a circular Edit button at the bottom-right?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "nav_chain_reading_mode", + "rigor": { + "jump_kind": "reach", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_folder_bottom_bar_vlm", + "screenshot": "nav_folder_bottom_bar_vlm.png", + "assertion": "Is there a horizontal row of action icons along the bottom of the screen (a menu/hamburger, a plus/add, and search), forming a bottom app bar?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "nav_folder_bottom_bar", + "rigor": { + "jump_kind": "reach", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_duplicate_note_vlm", + "screenshot": "interaction_duplicate_note_vlm.png", + "assertion": "Are there two note cards with the same title text positioned immediately one above the other (adjacent) in the note list?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "interaction_duplicate_note", + "rigor": { + "jump_kind": "value", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_selection_highlight_vlm", + "screenshot": "interaction_selection_highlight_vlm.png", + "assertion": "Exactly one note row is currently selected: does that selected row have a visibly different (tinted/highlighted) background colour compared to the other unselected row?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "interaction_selection_highlight", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "interaction_selection_check_badge_vlm", + "screenshot": "interaction_selection_check_badge_vlm.png", + "assertion": "Does the selected note row show a filled circular check/tick badge marking it as selected?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "interaction_selection_check_badge", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_selection_action_bar_vlm", + "screenshot": "interaction_selection_action_bar_vlm.png", + "assertion": "Is a bottom action bar with several selection action icons (reminder, pin, share, archive and a more-options button) rendered along the bottom of the screen?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "interaction_selection_action_bar", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_pinned_section_vlm", + "screenshot": "interaction_pinned_section_vlm.png", + "assertion": "Is there a 'Pinned' section heading near the top of the note list with a note shown directly beneath it, positioned above the rest of the notes?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "interaction_pinned_section", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_note_options_grid_vlm", + "screenshot": "interaction_note_options_grid_vlm.png", + "assertion": "Does this bottom sheet titled 'Note options' show a grid/list of several labeled action tiles such as Add reminder, Reading Mode, Pin, Share, Archive, Duplicate, Copy, Move to and Delete?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "interaction_note_options_grid", + "rigor": { + "jump_kind": "value", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_created_note_card_vlm", + "screenshot": "interaction_created_note_card_vlm.png", + "assertion": "In the note card, is the title line ('CardTitle') rendered in a LARGER or bolder font than, and positioned above, the body-preview line ('card body preview')?", + "form": "question", + "expected": true, + "aspect": "size", + "modality": null, + "links_to": "interaction_created_note_card", + "rigor": { + "jump_kind": "value", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_selection_check_dark_vlm", + "screenshot": "interaction_selection_check_dark_vlm.png", + "assertion": "The selected note row shows a small circular check/tick badge in its corner: is that badge a SOLID DARK/BLACK filled circle (not a hollow outline)?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "interaction_selection_check_dark", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_wc_four_vlm", + "screenshot": "computation_wc_four_vlm.png", + "assertion": "In this note editor screen, is the text '4 Words' displayed in the header row near the top (next to the folder title)?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "computation_wc_four", + "rigor": { + "jump_kind": "value", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_home_cards_count_vlm", + "screenshot": "computation_home_cards_count_vlm.png", + "assertion": "On this home screen, does the 'All' library card show the number 2 as its note count?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "computation_home_cards_count", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_reading_paging_vlm", + "screenshot": "computation_reading_paging_vlm.png", + "assertion": "In this full-screen reading view, is the paging indicator '1 / 1 Note' displayed (showing you are on note 1 of 1)?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "computation_reading_paging", + "rigor": { + "jump_kind": "value", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_selection_on_vlm", + "screenshot": "states_selection_on_vlm.png", + "assertion": "Does exactly one note row show a solid, filled circular check/selection badge (a coloured circle with a checkmark) on it?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_selection_on", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_selection_bar_vlm", + "screenshot": "states_selection_bar_vlm.png", + "assertion": "Is a horizontal action bar of icon buttons (reminder, pin, share, archive) shown along the bottom of the screen?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "states_selection_bar", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_all_chip_active_vlm", + "screenshot": "states_all_chip_active_vlm.png", + "assertion": "Near the top of the note list, is the 'All' chip drawn as a FILLED (solid dark/coloured) pill while the neighbouring add-label (+) button is an outlined/unfilled circle?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_all_chip_active", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_empty_folder_placeholder_vlm", + "screenshot": "text_empty_folder_placeholder_vlm.png", + "assertion": "Is a short single-line message like 'Folder is empty.' shown roughly centered in the middle of an otherwise blank note list (not at the top or bottom)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "text_empty_folder_placeholder", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_new_note_created_timestamp_vlm", + "screenshot": "text_new_note_created_timestamp_vlm.png", + "assertion": "Near the BOTTOM of the note-editing area, below the text fields, are two small timestamp lines beginning with 'Created' and 'Accessed' shown one under the other?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "text_new_note_created_timestamp", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_reading_mode_paging_label_vlm", + "screenshot": "text_reading_mode_paging_label_vlm.png", + "assertion": "Does this read-only note view display the title 'ReadMeNote' and the body text 'the quick brown fox jumps'?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "text_reading_mode_paging_label", + "rigor": { + "jump_kind": "none", + "depth": 4 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_undo_disabled_vlm", + "screenshot": "states_undo_disabled_vlm.png", + "assertion": "In the bottom toolbar of this note editor, does the Undo (left curved arrow) icon look greyed-out / dimmed compared with the other toolbar icons?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_undo_disabled", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_theme_light_vlm", + "screenshot": "states_theme_light_vlm.png", + "assertion": "Is the overall app background LIGHT (white / very pale) with dark text, rather than a dark/black background?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_theme_light", + "rigor": { + "jump_kind": "transition", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_theme_selected_mark_vlm", + "screenshot": "states_theme_selected_mark_vlm.png", + "assertion": "In this Theme option list, is the 'Light' option visibly marked as the current selection (a filled radio dot or a highlighted row) while the other options are not?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_theme_selected_mark", + "rigor": { + "jump_kind": "value", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_theme_persists_vlm", + "screenshot": "states_theme_persists_vlm.png", + "assertion": "Is the overall app background still LIGHT (white / very pale) with dark text after the app was restarted?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_theme_persists", + "rigor": { + "jump_kind": "transition", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_theme_dark_vlm", + "screenshot": "states_theme_dark_vlm.png", + "assertion": "Is the overall app background now DARK (near-black / very dark) with light-coloured text?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_theme_dark", + "rigor": { + "jump_kind": "transition", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_show_count_thumb_vlm", + "screenshot": "states_show_count_thumb_vlm.png", + "assertion": "On the 'Show notes count' settings row, is there a switch whose thumb is toward the RIGHT / in the ON position (the track filled/coloured)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "states_show_count_thumb", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_reading_paging_vlm", + "screenshot": "states_reading_paging_vlm.png", + "assertion": "In this full-screen reading view, is a page-position indicator (showing something like '1 / 1' or '1 / 2') rendered near the bottom/header, between a previous and a next arrow?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "states_reading_paging", + "rigor": { + "jump_kind": "value", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_home_cards_vlm", + "screenshot": "states_home_cards_vlm.png", + "assertion": "Near the top of this screen are four library cards. Do they have FOUR DISTINCT accent colours (for example blue, amber/yellow, red, and purple) rather than all being the same colour?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_home_cards", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + } + ], + "merged_from_files": 1, + "source_shapes": { + "list": 1 + } +} \ No newline at end of file diff --git a/android/andreynovikov-trekarta/LICENSE b/android/andreynovikov-trekarta/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..733c072369ca77331f392c40da7404c85c36542c --- /dev/null +++ b/android/andreynovikov-trekarta/LICENSE @@ -0,0 +1,675 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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 for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know 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 License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of 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 of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification 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 of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. 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 work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a 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 visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation 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 to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients 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 to +produce it from the Program, in the form of source code under the +terms 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 independent +works, 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 not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-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 excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the 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 install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional 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 you +add to a covered work, you may (if authorized by the copyright holders of +that 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 "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form 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 expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered 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 automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent 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 anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain 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 limiting +any implied license or other defenses to infringement that may +otherwise 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 or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License 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 have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License 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 the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES 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 OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy 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 greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + 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 . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + 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 appropriate +parts of the General Public License. Of course, your program's commands +might 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 +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + diff --git a/android/andreynovikov-trekarta/instance.json b/android/andreynovikov-trekarta/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..36b130c9fef21d65a224ede29aeaaa3b8f162ee8 --- /dev/null +++ b/android/andreynovikov-trekarta/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "android/andreynovikov-trekarta", + "platform": "android", + "repo": "https://github.com/andreynovikov/trekarta", + "commit": "5a305d56fa6330cb435de7d871c6eac440597c64", + "patches": [], + "package": "mobi.maptrek", + "license": null +} diff --git a/android/andreynovikov-trekarta/reference/launch.sh b/android/andreynovikov-trekarta/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8 --- /dev/null +++ b/android/andreynovikov-trekarta/reference/launch.sh @@ -0,0 +1,9 @@ +#!/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 1 diff --git a/android/andreynovikov-trekarta/tests/android_computation_eval.json b/android/andreynovikov-trekarta/tests/android_computation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..3d356e8950a3d71363fb5120bba1db28c593183b --- /dev/null +++ b/android/andreynovikov-trekarta/tests/android_computation_eval.json @@ -0,0 +1,113 @@ +{ + "module": "computation", + "total": 9, + "passed": 9, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 9, + "passed": 9, + "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": 9, + "depth_ge1": 9, + "depth_ge2": 9, + "value": 9, + "vlm_fine": 0 + }, + "results": [ + { + "test": "computation_coord_positive_pair", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "coordinates row shows '48.858000 2.294500'" + }, + { + "test": "computation_coord_negative_pair", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "coordinates row shows '-19.500000 -11.999999'" + }, + { + "test": "computation_coord_mixed_sign", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "coordinates row shows '37.774900 -122.419400'" + }, + { + "test": "computation_coord_decimal_pair", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "coordinates row shows '10.100000 20.200000'" + }, + { + "test": "computation_coord_zero_pair", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "coordinates row shows '0.000000 0.000000'" + }, + { + "test": "computation_coord_short_decimals", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "coordinates row shows '45.500000 3.250000'" + }, + { + "test": "computation_coord_distinct_outputs", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "two distinct inputs -> '12.345678 65.432100' and '-33.868800 151.209300'" + }, + { + "test": "computation_coord_invalid_no_place", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "dialog stays open, 0 places created" + }, + { + "test": "computation_coord_empty_no_place", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "dialog closes, 0 places created" + } + ] +} \ No newline at end of file diff --git a/android/andreynovikov-trekarta/tests/android_interaction_eval.json b/android/andreynovikov-trekarta/tests/android_interaction_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..7382f739a60e9d7b87e4261d8a51680386fa254c --- /dev/null +++ b/android/andreynovikov-trekarta/tests/android_interaction_eval.json @@ -0,0 +1,320 @@ +{ + "module": "interaction", + "total": 31, + "passed": 31, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 22, + "passed": 22, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 9, + "passed": 9, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.4091, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 31, + "depth_ge1": 30, + "depth_ge2": 15, + "value": 0, + "vlm_fine": 7 + }, + "results": [ + { + "test": "interaction_place_saved_snackbar_vlm", + "passed": true, + "message": "VLM: Q='Is a dark snackbar/toast shown near the bottom of the screen containing the text 'Place saved'?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is a dark snackbar/toast shown near the bottom of the screen containing the text 'Place saved'?", + "tag": "content" + }, + { + "test": "interaction_create_place_marker_vlm", + "passed": true, + "message": "VLM: Q='Is a map pin/marker drawn near the centre of the map, with the text label 'Place #1' next to it?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is a map pin/marker drawn near the centre of the map, with the text label 'Place #1' next to it?", + "tag": "position" + }, + { + "test": "interaction_create_place_longpress", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "empty-state before; row 'Place #1' + count 1 after" + }, + { + "test": "interaction_two_markers_vlm", + "passed": true, + "message": "VLM: Q='Is a map pin/marker drawn near the vertical centre of the map with the text label 'Place #2' shown directly above it?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is a map pin/marker drawn near the vertical centre of the map with the text label 'Place #2' shown directly above it?", + "tag": "position" + }, + { + "test": "interaction_create_two_places", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "rows ['Place #1','Place #2'] both present" + }, + { + "test": "interaction_multi_record_integrity", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "3 rows: 'Place #1','Place #3','kit_mid_B' present, 'Place #2' absent" + }, + { + "test": "interaction_rename_map_label_vlm", + "passed": true, + "message": "VLM: Q='Is the text label 'kit_rec_A' drawn on the map next to a pin/marker?' A=YES expect=YES", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is the text label 'kit_rec_A' drawn on the map next to a pin/marker?", + "tag": "content" + }, + { + "test": "interaction_rename_place", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "row 'kit_rec_A' present, 'Place #1' absent" + }, + { + "test": "interaction_rename_persists", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "row 'kit_persist_C' present after relaunch" + }, + { + "test": "interaction_create_persists", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "row 'Place #1' present after relaunch" + }, + { + "test": "interaction_multi_record_persists", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "rows ['Place #1','Place #2'] after relaunch" + }, + { + "test": "interaction_create_coordinate_dialog", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "place count 0->1 via coords" + }, + { + "test": "interaction_delete_marker_gone_vlm", + "passed": true, + "message": "VLM: Q='Near the vertical centre of the map, is there NO pin/marker and NO text label reading 'Place #1' (the marker has been removed)?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Near the vertical centre of the map, is there NO pin/marker and NO text label reading 'Place #1' (the marker has been removed)?", + "tag": "position" + }, + { + "test": "interaction_delete_place", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "place count 1->0" + }, + { + "test": "interaction_delete_one_of_two", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "delete #1 -> only 'Place #2' remains" + }, + { + "test": "interaction_rename_reopen_shows_new_name", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "reopened sheet name == 'kit_reopen_D', source 'My places'" + }, + { + "test": "interaction_map_menu_marker_vlm", + "passed": true, + "message": "VLM: Q='Is a map pin/marker drawn on the map (a place was just added via the context menu)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is a map pin/marker drawn on the map (a place was just added via the context menu)?", + "tag": "position" + }, + { + "test": "interaction_add_place_map_menu", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "place count 0->1 via map menu" + }, + { + "test": "interaction_map_context_menu", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "context menu with Share/Add/Navigate/Remember" + }, + { + "test": "interaction_place_info_actions", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "edit+share+delete+navigate controls on sheet" + }, + { + "test": "interaction_place_info_fab_vlm", + "passed": true, + "message": "VLM: Q='In the place-information panel, is there a round ORANGE floating action button positioned at the upper-right of the panel?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In the place-information panel, is there a round ORANGE floating action button positioned at the upper-right of the panel?", + "tag": "position" + }, + { + "test": "interaction_edit_color_swatch_vlm", + "passed": true, + "message": "VLM: Q='In this place-edit form, is there a small filled COLOURED circle (a colour swatch) shown to the right, near the Description field?' A=YES expect=YES", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In this place-edit form, is there a small filled COLOURED circle (a colour swatch) shown to the right, near the Description field?", + "tag": "color" + }, + { + "test": "interaction_import_markers_vlm", + "passed": true, + "message": "VLM: Q='Are one or more map pins/markers now drawn on the map (imported places)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Are one or more map pins/markers now drawn on the map (imported places)?", + "tag": "position" + }, + { + "test": "interaction_import_places", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "data-source row 'Sample Places' after import" + }, + { + "test": "interaction_longpress_vs_tap_semantics", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "tap -> 0 places, long-press -> 1 place" + }, + { + "test": "interaction_three_records_persist", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "rows {'Place #1','Place #2','Place #3'} after relaunch" + }, + { + "test": "interaction_edit_description_persists", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "place-info description == 'kit_desc_E' after reopen" + }, + { + "test": "interaction_rename_last_write_wins", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "single row 'kit_second_G', earlier names absent" + }, + { + "test": "interaction_create_delete_roundtrip", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "count 0->1->0" + }, + { + "test": "interaction_import_persists", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "data-source row 'Sample Places' after relaunch" + }, + { + "test": "interaction_coord_place_has_info", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "info sheet 'My places' + non-empty coordinates row" + } + ] +} \ No newline at end of file diff --git a/android/andreynovikov-trekarta/tests/android_navigation_eval.json b/android/andreynovikov-trekarta/tests/android_navigation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..69271a5ad6d730327a484b0d6e1d15b86471a602 --- /dev/null +++ b/android/andreynovikov-trekarta/tests/android_navigation_eval.json @@ -0,0 +1,300 @@ +{ + "module": "navigation", + "total": 29, + "passed": 29, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 22, + "passed": 22, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 7, + "passed": 7, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.3182, + "audit": { + "kit_api_version": 1, + "existence": 7, + "liveness": 0, + "interactive": 22, + "depth_ge1": 22, + "depth_ge2": 14, + "value": 0, + "vlm_fine": 6 + }, + "results": [ + { + "test": "nav_reach_more", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "more-menu items (Settings, Ruler) appeared over the map after tapping moreButton" + }, + { + "test": "nav_reach_more_vlm", + "passed": true, + "message": "VLM: Q='Is a vertical text menu panel overlaying the RIGHT side of the screen while a map is still visible on the LEFT side?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a vertical text menu panel overlaying the RIGHT side of the screen while a map is still visible on the LEFT side?", + "tag": "position" + }, + { + "test": "nav_reach_places", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Places panel FAB (listActionButton) appeared after tapping placesButton" + }, + { + "test": "nav_reach_tracks", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Tracks empty-state 'Your recorded tracks will appear here.' appeared after tapping tracksButton" + }, + { + "test": "nav_reach_maps", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Maps empty-state 'Your installed custom tile maps will appear here.' appeared after tapping mapsButton" + }, + { + "test": "nav_reach_settings", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Settings category 'General' appeared and more-menu 'Import' left, after more->Settings" + }, + { + "test": "nav_reach_settings_vlm", + "passed": true, + "message": "VLM: Q='Is a bottom sheet slid up over the lower part of the screen showing a vertical list of at least four text menu rows?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a bottom sheet slid up over the lower part of the screen showing a vertical list of at least four text menu rows?", + "tag": "position" + }, + { + "test": "nav_reach_units", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "Units row 'Speed' + summary 'miles per hour' appeared and category 'About' left" + }, + { + "test": "nav_reach_units_vlm", + "passed": true, + "message": "VLM: Q='Does this settings sub-page list rows each with a bold label on the left and a smaller grey value line beneath it?' A=YES expect=YES", + "depth": 3, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does this settings sub-page list rows each with a bold label on the left and a smaller grey value line beneath it?", + "tag": "position" + }, + { + "test": "nav_reach_about", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "About page 'Version: 107' appeared and Settings category 'Advanced' left" + }, + { + "test": "nav_reach_search", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Search query field 'Name or coordinates' appeared and more-menu 'Import' left" + }, + { + "test": "nav_reach_ruler", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Ruler readout '0 segments' appeared and more-menu 'Settings' left" + }, + { + "test": "nav_reach_create_route", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Route editor readout '0 legs' appeared and more-menu 'Settings' left" + }, + { + "test": "nav_reach_activity", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Activity dialog options (Hiking/None/Cycling) appeared and more-menu 'Import' left" + }, + { + "test": "nav_reach_activity_vlm", + "passed": true, + "message": "VLM: Q='Is a dialog titled 'Activity' showing a vertical list of radio options, exactly one of which has a filled/selected radio button?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a dialog titled 'Activity' showing a vertical list of radio options, exactly one of which has a filled/selected radio button?", + "tag": "shape" + }, + { + "test": "nav_reach_map_menu", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "context-menu items 'Add place' and 'Navigate here' appeared over the map on long-press" + }, + { + "test": "nav_reach_map_menu_vlm", + "passed": true, + "message": "VLM: Q='Is a small popup menu of four stacked text options (Share coordinates / Add place / Navigate here / Remember zoom) shown on top of the map?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a small popup menu of four stacked text options (Share coordinates / Add place / Navigate here / Remember zoom) shown on top of the map?", + "tag": "content" + }, + { + "test": "nav_reach_coord_dialog", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "dialog title 'Enter coordinates' + coordinatesEdit appeared and the FAB left" + }, + { + "test": "nav_reach_coord_dialog_vlm", + "passed": true, + "message": "VLM: Q='Is a dialog with a single text input field shown, with the on-screen keyboard raised at the bottom of the screen?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a dialog with a single text input field shown, with the on-screen keyboard raised at the bottom of the screen?", + "tag": "position" + }, + { + "test": "nav_reach_place_info", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "place-info bottomSheetPanel with source 'My places' appeared and the list FAB left" + }, + { + "test": "nav_reach_place_info_vlm", + "passed": true, + "message": "VLM: Q='Is a bottom sheet showing place details with a round ORANGE circular action button (a floating action button) at its right edge?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a bottom sheet showing place details with a round ORANGE circular action button (a floating action button) at its right edge?", + "tag": "color" + }, + { + "test": "nav_reach_place_edit", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "edit fragment with the Description EditText + nameEdit appeared after editButton" + }, + { + "test": "nav_back_more_home", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "more-menu 'Settings' gone, extendPanel gone, mapView + 5 bottom buttons restored after one BACK" + }, + { + "test": "nav_back_info_places", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "place-info 'My places' gone, Places list FAB + place row restored after one BACK" + }, + { + "test": "nav_back_units_categories", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Units 'Speed' gone, Settings categories 'General'/'About' restored after one BACK" + }, + { + "test": "nav_backstack_unwind_3hop", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "BACK1: Units->categories (Speed gone, General back); BACK2: categories->map home (contentPanel gone)" + }, + { + "test": "nav_switch_places_tracks", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Tracks empty-state 'Your recorded tracks will appear here.' appeared after tracksButton from Places" + }, + { + "test": "nav_reach_import_picker", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "external document-picker activity resumed (foreground left the app under test) after Import" + }, + { + "test": "nav_reach_manage_maps", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Manage-maps readout '0 items selected' appeared and more-menu 'Settings' left" + } + ] +} \ No newline at end of file diff --git a/android/andreynovikov-trekarta/tests/android_states_eval.json b/android/andreynovikov-trekarta/tests/android_states_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..10bb0a3c71c639bf98d13d7fb856780f850c4df6 --- /dev/null +++ b/android/andreynovikov-trekarta/tests/android_states_eval.json @@ -0,0 +1,190 @@ +{ + "module": "states", + "total": 17, + "passed": 17, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 12, + "passed": 12, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 5, + "passed": 5, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.4167, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 17, + "depth_ge1": 14, + "depth_ge2": 7, + "value": 6, + "vlm_fine": 4 + }, + "results": [ + { + "test": "states_distance_unit_transition", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Distance summary 'miles/feet' -> 'kilometers/meters'" + }, + { + "test": "states_distance_unit_persists", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "miles/yards" + }, + { + "test": "states_speed_unit_transition", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Speed summary 'miles per hour' -> 'kilometers per hour'" + }, + { + "test": "states_speed_unit_persists", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "knots" + }, + { + "test": "states_elevation_unit_persists", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "meters" + }, + { + "test": "states_extra_precision_toggle", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Extra precision checked false->true; Units sheet still shown" + }, + { + "test": "states_extra_precision_persists", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "checked=false" + }, + { + "test": "states_fullscreen_toggle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Fullscreen checked false->on; system immersive cling 'Viewing full screen' appears" + }, + { + "test": "states_fullscreen_toggle_vlm", + "passed": true, + "message": "VLM: Q='Is the top system status bar (clock, wifi and battery icons) hidden, with the app/map content extending all the way to the very top edge of the screen (fullscreen immersive mode)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is the top system status bar (clock, wifi and battery icons) hidden, with the app/map content extending all the way to the very top edge of the screen (fullscreen immersive mode)?", + "tag": "layout" + }, + { + "test": "states_location_follow_gauge", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "gaugePanel absent->present (with gaugeValue/gaugeUnit) after entering follow mode" + }, + { + "test": "states_location_follow_gauge_vlm", + "passed": true, + "message": "VLM: Q='Look at the row of navigation buttons at the bottom. Is the leftmost button (a navigation arrow) highlighted in a bright orange/red accent colour, distinctly different from the other grey buttons?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Look at the row of navigation buttons at the bottom. Is the leftmost button (a navigation arrow) highlighted in a bright orange/red accent colour, distinctly different from the other grey buttons?", + "tag": "color" + }, + { + "test": "states_location_recenter_vlm", + "passed": true, + "message": "VLM: Q='Is there a solid RED arrow-shaped location/heading cursor drawn on the map, indicating the current GPS position?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is there a solid RED arrow-shaped location/heading cursor drawn on the map, indicating the current GPS position?", + "tag": "position" + }, + { + "test": "states_track_recording_start", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "idle->recording: 'Current track' row + pause_action + stop_action controls appear" + }, + { + "test": "states_track_recording_start_vlm", + "passed": true, + "message": "VLM: Q='Look at the bottom navigation buttons. Is the second button (a squiggle/track-shaped icon) highlighted in a bright orange/red accent colour, indicating active track recording?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Look at the bottom navigation buttons. Is the second button (a squiggle/track-shaped icon) highlighted in a bright orange/red accent colour, indicating active track recording?", + "tag": "color" + }, + { + "test": "states_track_recording_pause", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "paused: resume_action present, pause_action gone" + }, + { + "test": "states_activity_radio_select", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Hiking selected" + }, + { + "test": "states_activity_radio_select_vlm", + "passed": true, + "message": "VLM: Q='Look at the 'Activity' dialog radio list. Is exactly ONE radio button filled/dotted with a bright orange accent colour while the others are empty grey circles?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Look at the 'Activity' dialog radio list. Is exactly ONE radio button filled/dotted with a bright orange accent colour while the others are empty grey circles?", + "tag": "color" + } + ] +} \ No newline at end of file diff --git a/android/andreynovikov-trekarta/tests/android_structure_eval.json b/android/andreynovikov-trekarta/tests/android_structure_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..5426df9fd64cf3f4ec85187afe2f99dfdaa07a95 --- /dev/null +++ b/android/andreynovikov-trekarta/tests/android_structure_eval.json @@ -0,0 +1,172 @@ +{ + "module": "structure", + "total": 15, + "passed": 15, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 10, + "passed": 10, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 5, + "passed": 5, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.5, + "audit": { + "kit_api_version": 1, + "existence": 6, + "liveness": 0, + "interactive": 9, + "depth_ge1": 8, + "depth_ge2": 3, + "value": 0, + "vlm_fine": 5 + }, + "results": [ + { + "test": "structure_gate_launch", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_gate_launch_vlm", + "passed": true, + "message": "VLM: Q='Is there a horizontal row of exactly 5 evenly spaced icon buttons across the very bottom edge of the screen?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is there a horizontal row of exactly 5 evenly spaced icon buttons across the very bottom edge of the screen?", + "tag": "shape" + }, + { + "test": "structure_more_panel", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "extendPanel appears (more menu overlays map) after tapping moreButton" + }, + { + "test": "structure_more_panel_vlm", + "passed": true, + "message": "VLM: Q='Is a vertical menu panel overlaying the right side of the screen while a map is still visible on the left side?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a vertical menu panel overlaying the right side of the screen while a map is still visible on the left side?", + "tag": "position" + }, + { + "test": "structure_places_panel", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "places panel container appears after tapping placesButton" + }, + { + "test": "structure_places_panel_vlm", + "passed": true, + "message": "VLM: Q='Does a map still fill the upper part of the screen above a bottom panel area?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does a map still fill the upper part of the screen above a bottom panel area?", + "tag": "position" + }, + { + "test": "structure_tracks_panel", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "tracks panel container appears after tapping tracksButton" + }, + { + "test": "structure_maps_panel", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "maps panel container appears after tapping mapsButton" + }, + { + "test": "structure_settings_sheet", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Settings bottom sheet with a RecyclerView of category rows appears" + }, + { + "test": "structure_settings_sheet_vlm", + "passed": true, + "message": "VLM: Q='Is a bottom sheet showing a vertical list of at least four text menu rows stacked one above another?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a bottom sheet showing a vertical list of at least four text menu rows stacked one above another?", + "tag": "shape" + }, + { + "test": "structure_map_contextmenu", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "context-menu popup adds >=3 new menu rows over the map on long-press" + }, + { + "test": "structure_place_bottomsheet", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "bottomSheetPanel (place-info sheet) appears after tapping the created place row" + }, + { + "test": "structure_coord_dialog", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "AlertDialog with a coordinate EditText appears from the places FAB" + }, + { + "test": "structure_panel_returns", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "places panel container gone and the 5-button map surface restored after BACK" + }, + { + "test": "structure_place_marker_vlm", + "passed": true, + "message": "VLM: Q='Is a single map pin / location marker icon drawn on the map near the centre of the screen?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a single map pin / location marker icon drawn on the map near the centre of the screen?", + "tag": "shape" + } + ] +} \ No newline at end of file diff --git a/android/andreynovikov-trekarta/tests/android_testgen_kit.py b/android/andreynovikov-trekarta/tests/android_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6 --- /dev/null +++ b/android/andreynovikov-trekarta/tests/android_testgen_kit.py @@ -0,0 +1,1910 @@ +#!/usr/bin/env python3 +"""Android TestGen Kit — the single source of every test helper, so a test's +NAVIGATION 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 package +name differs): always use the module-level PACKAGE (argv[1]). Never write a package +name, an .apk path, a /data/data path, or a pixel coordinate as a literal. + python3 android_testgen_kit.py lint_sources # flags all of those + +SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery): + python3 android_testgen_kit.py audit + python3 android_testgen_kit.py lint + python3 android_testgen_kit.py lint_sources + python3 android_testgen_kit.py audit_depth [results_dir] +""" +from __future__ import annotations + +import ast +import base64 +import functools +import glob +import hashlib +import json +import math +import os +import re +import shlex +import subprocess +import sys +import time +import urllib.error +import 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.0 +SETTLE = { + "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 /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 " list[dict]: + """XML -> list of attribute dicts, each with _bounds and _center.""" + nodes = [] + for m in re.finditer(r"]+?)/?>", 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} \n" + " android_testgen_kit.py audit_depth [results_dir]\n" + " android_testgen_kit.py score [manifest_dir]") diff --git a/android/andreynovikov-trekarta/tests/android_text_eval.json b/android/andreynovikov-trekarta/tests/android_text_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..730aa45dc2f9a59e9425c85df7dfb3fa685d555a --- /dev/null +++ b/android/andreynovikov-trekarta/tests/android_text_eval.json @@ -0,0 +1,240 @@ +{ + "module": "text", + "total": 23, + "passed": 23, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 22, + "passed": 22, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 1, + "passed": 1, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.0455, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 23, + "depth_ge1": 20, + "depth_ge2": 13, + "value": 16, + "vlm_fine": 0 + }, + "results": [ + { + "test": "text_places_empty", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Your places will appear here. You can create place by entering its coordinates or by long pressing Places button." + }, + { + "test": "text_tracks_empty", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Your recorded tracks will appear here." + }, + { + "test": "text_maps_empty", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Your installed custom tile maps will appear here." + }, + { + "test": "text_places_import_footer", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "You can also import GPX and KML files." + }, + { + "test": "text_snackbar_place_saved", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "snackbar reads 'Place saved'" + }, + { + "test": "text_snackbar_customize", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "snackbar action reads 'CUSTOMIZE'" + }, + { + "test": "text_units_speed_default", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "Speed summary 'miles per hour'" + }, + { + "test": "text_units_distance_default", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "Distance summary 'miles/feet'" + }, + { + "test": "text_units_elevation_default", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "Elevation summary 'feet'" + }, + { + "test": "text_units_angle_default", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "Angle summary 'degrees'" + }, + { + "test": "text_distance_dialog_options", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "options kilometers/meters, miles/yards, miles/feet, nautical miles" + }, + { + "test": "text_more_menu_labels", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Fullscreen, Settings, Import, Manage maps, Ruler, Create route, Activity, Search" + }, + { + "test": "text_settings_categories", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "General, Units, Location, Places, tracks, routes, Advanced, About" + }, + { + "test": "text_activity_dialog_options", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "None, Hiking, Cycling, Skiing" + }, + { + "test": "text_map_context_menu", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Share coordinates, Add place, Navigate here, Remember zoom" + }, + { + "test": "text_place_info_source", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "place-info source reads 'My places'" + }, + { + "test": "text_place_info_date_present", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "place-info date row is populated" + }, + { + "test": "text_place_row_name", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Places panel row reads 'Place #1'" + }, + { + "test": "text_about_appname", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "About screen shows app name 'Trekarta'" + }, + { + "test": "text_about_version_label", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "About screen shows a 'Version:' label" + }, + { + "test": "text_about_description", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "description begins 'Trekarta is designed for hiking, geocaching, off-roading, cycling, boating...'" + }, + { + "test": "text_about_copyright_header", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "About screen shows a 'COPYRIGHT' header" + }, + { + "test": "text_map_marker_label_vlm", + "passed": true, + "message": "VLM: Q='Is the text label 'Place #1' drawn on the map next to a pin/marker icon?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Is the text label 'Place #1' drawn on the map next to a pin/marker icon?", + "tag": "content" + } + ] +} \ No newline at end of file diff --git a/android/andreynovikov-trekarta/tests/conftest.py b/android/andreynovikov-trekarta/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27 --- /dev/null +++ b/android/andreynovikov-trekarta/tests/conftest.py @@ -0,0 +1 @@ +pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"] diff --git a/android/andreynovikov-trekarta/tests/requirements.txt b/android/andreynovikov-trekarta/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c --- /dev/null +++ b/android/andreynovikov-trekarta/tests/requirements.txt @@ -0,0 +1,2 @@ +pytest +pillow diff --git a/android/andreynovikov-trekarta/tests/test_android_computation.py b/android/andreynovikov-trekarta/tests/test_android_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..e1c16112e697badee9f809d366afe8403de8dd75 --- /dev/null +++ b/android/andreynovikov-trekarta/tests/test_android_computation.py @@ -0,0 +1,347 @@ +#!/usr/bin/env python3 +"""COMPUTATION lane — Trekarta (mobi.maptrek). + +The app's core input->output surface is the "Enter coordinates" dialog: the user +types a "lat lon" string, the app parses it, creates a place AT those coordinates, +and the place-information sheet renders the resulting coordinates formatted to six +decimal places (StringFormatter format 0, "latlon"). Every value below was +OBSERVED on the running original — e.g. entering "48.858000 2.294500" makes the +place-info coordinates row read exactly "48.858000 2.294500". + +Everything asserted here is dump-readable (the TextView id `coordinates`), so this +file spends ZERO VLM budget — the whole point of this lane is the exact numeric +round-trip. +""" +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403 + + +# ── first-run gate + clean slate ──────────────────────────────────────────────── +def _wait_home_ready(timeout=12): + """Block past the Trekarta splash: wait_for_foreground() returns while the + logo is up and uiautomator then hands back a STALE tree. Poll until the + bottom-bar placesButton or the first-run dialog button2 is present.""" + import time as _t + deadline = _t.time() + timeout + while _t.time() < deadline: + n = ui() + if (node_by_id(n, "placesButton") is not None + or node_by_id(n, "button2") is not None): + return n + settle("key") + return ui() + + +def _skip_first_run(): + """Dismiss the base-map download dialog that appears on EVERY launch. Never + taps DOWNLOAD (network).""" + _wait_home_ready() + n = ui() + b = find_node(n, text="SKIP") or node_by_id(n, "button2") + if b: + tap_node(b) + settle("tap") + + +def clean_start(): + """Wipe app data so the place we create is the ONLY place row (the app + persists previously-created places), then get past the first-run dialog. Data + reset only — never mid-assertion, never a destructive UI control.""" + clear_data() + launch_app() + wait_for_foreground() + _skip_first_run() + + +# ── navigation helpers that BACK the declared depth ───────────────────────────── +def and_enter_places(): + """home -> Places panel (surface 1). Backs depth>=1.""" + btn = node_by_id(ui(), "placesButton") + if not btn: + return False + ok = tap_node(btn) + settle("tap") + if ok: + and_enter("places") + return ok + + +def and_enter_coord_dialog(): + """Places panel -> "Enter coordinates" dialog (surface 2) via the FAB. Backs + depth>=2. Returns the coordinatesEdit node (or None).""" + fab = node_by_id(ui(), "listActionButton") + if not fab: + return None + tap_node(fab) + settle("tap") + edit = node_by_id(ui(), "coordinatesEdit") + if edit is not None and (node_by_id(ui(), "alertTitle") or edit): + and_enter("coord_dialog") + return edit + + +def and_reach_place_info(name): + """Places panel -> place-information bottom sheet for the row titled `name` + (a new surface). Proves the jump (the `source` "My places" row appears). Backs + one surface. Returns True on a proven reach.""" + ns = ui() + row = None + for n in ns: + if (n.get("resource-id", "").rsplit("/", 1)[-1] == "name" + and n.get("text", "").strip() == name): + row = n + break + if row is None: + return False + before = and_showing(ns) + tap_node(row) + settle("tap") + after = and_showing() + ok = and_reach(before, after, "My places") or node_by_id(ui(), "coordinates") is not None + if ok: + and_enter("place_info") + return ok + + +# ── primitives ────────────────────────────────────────────────────────────────── +def enter_coordinate(text): + """Type `text` into coordinatesEdit (via type_text so the SPACE survives) and + press OK. Assumes the coord dialog is already open. Returns True if typed+OK.""" + edit = node_by_id(ui(), "coordinatesEdit") + if edit is None: + return False + if not type_text(edit, text): + return False + settle("text") + ok = node_by_id(ui(), "button1") or find_node_ci(ui(), "OK") + if ok is None: + return False + tap_node(ok) + settle("tap") + return True + + +def place_rows(nodes=None): + ns = nodes if nodes is not None else ui() + return [n.get("text", "").strip() for n in ns + if n.get("resource-id", "").rsplit("/", 1)[-1] == "name" + and n.get("text", "").strip()] + + +def read_created_coordinates(): + """After a create, open the single place row and read its `coordinates` row.""" + rows = place_rows() + if not rows: + return None, "no place row created" + if not and_reach_place_info(rows[0]): + return None, f"could not open place info for {rows[0]!r}" + c = node_by_id(ui(), "coordinates") + if c is None: + return None, "no coordinates node in place info" + return c.get("text", "").strip(), "" + + +def _norm_pair(s): + """Normalise a 'lat lon' string to a tuple of floats for tolerant comparison. + Returns None if it does not parse into two numbers.""" + if not s: + return None + parts = s.replace(",", " ").split() + nums = [] + for p in parts: + try: + nums.append(float(p)) + except ValueError: + return None + return tuple(nums) if len(nums) == 2 else None + + +def _pairs_equal(a, b, tol=5e-6): + pa, pb = _norm_pair(a), _norm_pair(b) + if pa is None or pb is None: + return False + return len(pa) == len(pb) and all(abs(x - y) <= tol for x, y in zip(pa, pb)) + + +# ── the shared value-test body ────────────────────────────────────────────────── +def _coord_case(name, entered, expected_display): + """Enter `entered`, then assert the created place's coordinates row EQUALS + `expected_display` (the value observed on the original). Positive/negative + pairing: the coordinates are ABSENT (no place row) before OK and PRESENT after. + depth=2: home -> Places -> dialog, then the place-info sheet.""" + clean_start() + if not and_enter_places(): + record(name, False, "setup_failed: Places panel did not open", + depth=1, jump_kind="value", expect=f"coordinates row shows {expected_display!r}") + return + # negative half of the pair: no place exists yet + absent_before = len(place_rows()) == 0 + edit = and_enter_coord_dialog() + if edit is None: + record(name, False, "setup_failed: 'Enter coordinates' dialog did not open", + depth=2, jump_kind="value", expect=f"coordinates row shows {expected_display!r}") + return + if not enter_coordinate(entered): + record(name, False, f"setup_failed: could not type {entered!r} and press OK", + depth=2, jump_kind="value", expect=f"coordinates row shows {expected_display!r}") + return + got, err = read_created_coordinates() + if got is None: + record(name, False, f"behavior_wrong: {err} for input {entered!r}", + depth=2, jump_kind="value", expect=f"coordinates row shows {expected_display!r}") + return + ok = absent_before and _pairs_equal(got, expected_display) + msg = ("" if ok else + f"behavior_wrong: entered {entered!r} -> coordinates row {got!r}, " + f"expected {expected_display!r} (absent_before={absent_before})") + record(name, ok, msg, depth=2, jump_kind="value", + expect=f"coordinates row shows {expected_display!r}") + + +# ══════════════════════════════════════════════════════════════════════════════ +# VALUE TESTS: coordinate string -> place created at those coordinates, read back +# from the place-info `coordinates` row (6-dp "lat lon"). All observed on original. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_coord_positive_pair",)) +def test_coord_positive_pair(): + # Eiffel Tower-ish; both positive. + _coord_case("computation_coord_positive_pair", + "48.858000 2.294500", "48.858000 2.294500") + + +@and_test(expects=("computation_coord_negative_pair",)) +def test_coord_negative_pair(): + # Both negative — sign must be preserved. + _coord_case("computation_coord_negative_pair", + "-19.500000 -11.999999", "-19.500000 -11.999999") + + +@and_test(expects=("computation_coord_mixed_sign",)) +def test_coord_mixed_sign(): + # Positive lat, negative lon (San Francisco) — real-world discriminating value. + _coord_case("computation_coord_mixed_sign", + "37.774900 -122.419400", "37.774900 -122.419400") + + +@and_test(expects=("computation_coord_decimal_pair",)) +def test_coord_decimal_pair(): + # A plain decimal pair distinct from the others. + _coord_case("computation_coord_decimal_pair", + "10.100000 20.200000", "10.100000 20.200000") + + +@and_test(expects=("computation_coord_zero_pair",)) +def test_coord_zero_pair(): + # Edge: 0,0 (equator/prime-meridian) renders as "0.000000 0.000000". + _coord_case("computation_coord_zero_pair", + "0.000000 0.000000", "0.000000 0.000000") + + +@and_test(expects=("computation_coord_short_decimals",)) +def test_coord_short_decimals(): + # Input with FEWER than 6 decimals must be PADDED to 6dp by the formatter: + # observed "45.5 3.25" -> "45.500000 3.250000". + _coord_case("computation_coord_short_decimals", + "45.5 3.25", "45.500000 3.250000") + + +@and_test(expects=("computation_coord_distinct_outputs",)) +def test_coord_distinct_outputs(): + """Discrimination: two DIFFERENT inputs must yield two DIFFERENT displayed + coordinates. A stubbed dialog that ignores its input (always the map-center + default) would produce identical rows and fail here. depth=2.""" + clean_start() + got_a = None + if and_enter_places() and and_enter_coord_dialog() is not None \ + and enter_coordinate("12.345678 65.432100"): + got_a, _ = read_created_coordinates() + got_b = None + clean_start() + if and_enter_places() and and_enter_coord_dialog() is not None \ + and enter_coordinate("-33.868800 151.209300"): + got_b, _ = read_created_coordinates() + ok = (got_a is not None and got_b is not None + and _pairs_equal(got_a, "12.345678 65.432100") + and _pairs_equal(got_b, "-33.868800 151.209300") + and not _pairs_equal(got_a, got_b)) + msg = ("" if ok else + f"behavior_wrong: expected two distinct rows " + f"'12.345678 65.432100' and '-33.868800 151.209300', got {got_a!r} / {got_b!r}") + record("computation_coord_distinct_outputs", ok, msg, + depth=2, jump_kind="value", + expect="two distinct inputs -> '12.345678 65.432100' and '-33.868800 151.209300'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# EDGE / ROBUSTNESS: what the parser does with junk and empty input (observed). +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_coord_invalid_no_place",)) +def test_coord_invalid_no_place(): + """Invalid text ("abc") + OK: OBSERVED the dialog STAYS OPEN (title 'Enter + coordinates' + coordinatesEdit still present) and NO place is created. depth=2.""" + clean_start() + opened = and_enter_places() and and_enter_coord_dialog() is not None + if not opened: + record("computation_coord_invalid_no_place", False, + "setup_failed: could not open the coordinates dialog", + depth=2, jump_kind="value", expect="dialog stays open, 0 places created") + return + typed = enter_coordinate("abc") + ns = ui() + dialog_still_open = (node_by_id(ns, "alertTitle") is not None + or node_by_id(ns, "coordinatesEdit") is not None) + no_place = len(place_rows(ns)) == 0 + ok = typed and dialog_still_open and no_place + msg = ("" if ok else + f"behavior_wrong: invalid 'abc' -> dialog_open={dialog_still_open}, " + f"places={place_rows(ns)} (expected dialog stays open, 0 places)") + record("computation_coord_invalid_no_place", ok, msg, + depth=2, jump_kind="value", expect="dialog stays open, 0 places created") + + +@and_test(expects=("computation_coord_empty_no_place",)) +def test_coord_empty_no_place(): + """Empty input + OK: OBSERVED the dialog CLOSES and NO place is created (the + empty string yields no coordinate). depth=2.""" + clean_start() + opened = and_enter_places() and and_enter_coord_dialog() is not None + if not opened: + record("computation_coord_empty_no_place", False, + "setup_failed: could not open the coordinates dialog", + depth=2, jump_kind="value", expect="dialog closes, 0 places created") + return + ok_btn = node_by_id(ui(), "button1") or find_node_ci(ui(), "OK") + tapped = tap_node(ok_btn) if ok_btn else False + settle("tap") + ns = ui() + dialog_closed = (node_by_id(ns, "alertTitle") is None + and node_by_id(ns, "coordinatesEdit") is None) + no_place = len(place_rows(ns)) == 0 + ok = tapped and dialog_closed and no_place + msg = ("" if ok else + f"behavior_wrong: empty OK -> dialog_closed={dialog_closed}, " + f"places={place_rows(ns)} (expected dialog closes, 0 places)") + record("computation_coord_empty_no_place", ok, msg, + depth=2, jump_kind="value", expect="dialog closes, 0 places created") + + +TESTS = [ + test_coord_positive_pair, + test_coord_negative_pair, + test_coord_mixed_sign, + test_coord_decimal_pair, + test_coord_zero_pair, + test_coord_short_decimals, + test_coord_distinct_outputs, + test_coord_invalid_no_place, + test_coord_empty_no_place, +] + +if __name__ == "__main__": + if not device_online(): + print("device offline — cannot run computation suite") + sys.exit(2) + run_suite(TESTS, "computation") diff --git a/android/andreynovikov-trekarta/tests/test_android_interaction.py b/android/andreynovikov-trekarta/tests/test_android_interaction.py new file mode 100644 index 0000000000000000000000000000000000000000..de28abd8d567b316a9e16c82e13fbbafe753c643 --- /dev/null +++ b/android/andreynovikov-trekarta/tests/test_android_interaction.py @@ -0,0 +1,1285 @@ +#!/usr/bin/env python3 +"""INTERACTION module for Trekarta (mobi.maptrek). + +Lane: EFFECT-BY-CONSEQUENCE on user DATA. The core data object is a PLACE. Every +test drives the app to a real surface via the user path, mutates the place store, +then READS THE CONSEQUENCE back out of a fresh ui() and asserts it against what was +observed on the original. This module is the SOLE owner of: + * CRUD lifecycle — create / read-back / rename(edit) / delete + * multi-record integrity — 3 rows added, one edited, the rest intact & ordered + * DATA persistence across PROCESS DEATH — force_stop + relaunch, place survives + * long-press / context menus — long-press placesButton (create), long-press the + custom mapView (context menu -> Add place) + +GROUND TRUTH (every path below was performed successfully on the running original): + - Long-press placesButton creates "Place #N" at map centre; snackbar "Place saved" + (+ CUSTOMIZE); a new row (id `name`, text "Place #N") appears in the Places panel + (extendPanel) where the empty state had "Your places will appear here...". + - Tapping placesButton TOGGLES the Places panel open/closed, so a read-back always + re-opens it explicitly (open_places()). + - Tapping a place row opens the place-info bottom sheet (bottomSheetPanel): + name / source "My places" / coordinates / date, and editButton, shareButton, + deleteButton, actionButton (orange navigate FAB). + - editButton -> edit fragment: nameEdit (EditText, prefilled but its `text=` attr + is NOT exposed in the dump), descriptionEdit, colorSwatch/color_picker_swatch, + actionButton (orange check = SAVE), deleteButton. Because the name field hides + its text, the rename is asserted on the resulting LIST ROW, never on the field. + - After type_text the soft keyboard is up and shifts the FAB, so hide_keyboard() + precedes the save tap and the FAB is re-found on a fresh dump. + - deleteButton deletes the place (snackbar "Place deleted"); count returns to 0. + Only ever used on a place THIS test created (app-authored + snackbar-undoable). + - Coordinate create: Places FAB listActionButton -> dialog "Enter coordinates" + (coordinatesEdit) -> type "lat lon" -> OK -> a place is created. + - Map context menu: long-press mapView -> Share coordinates / Add place / + Navigate here / Remember zoom; "Add place" creates a place at that point. + - Import: more -> Import -> SAF picker (com.google.android.documentsui). The + reliably-indexed places fixture on this emulator is places_sample.kml + (source "Sample KML Places", 2 places); places_sample.gpx ("Sample Places", 3) + is tried first when the picker offers it. Selecting it -> DataImportActivity + ("Trekarta import", OK id `action`) -> Places panel gains the data-source row. + +The base-map download AlertDialog reappears on EVERY launch; dismiss_first_run() +SKIPs it (never DOWNLOAD) at the start of every test, including after a restart. +""" +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403 + +RESULTS_DIR = os.path.dirname(os.path.abspath(__file__)) + + +# ── App-specific entry point ───────────────────────────────────────────────── +def _wait_for_home(timeout=12): + """Block past the splash screen: after a cold launch (esp. right after + clear_data, which forces a slow first-run rebuild + Trekarta splash), the + process is 'foreground' while the logo is still up and uiautomator returns a + STALE tree. Poll until the bottom-bar `placesButton` is actually present, so + the first real ui() read is the settled map, not the splash.""" + import time as _t + deadline = _t.time() + timeout + while _t.time() < deadline: + n = ui() + if node_by_id(n, "placesButton") is not None: + return n + settle("key") + return ui() + + +def dismiss_first_run(): + """Launch fresh, wait for the real home (past the splash), SKIP the recurring + base-map dialog. Returns the settled home tree (post-SKIP).""" + restart_app() + wait_for_foreground() + n = _wait_for_home() + b = find_node(n, text="SKIP") or node_by_id(n, "button2") + if b: + tap_node(b) + settle("tap") + return ui() + + +def virgin_home(): + """A guaranteed 0-place database + dismissed dialog. Used by every test that + asserts a deterministic place count.""" + clear_data() + return dismiss_first_run() + + +def relaunch_and_skip(): + """A PROCESS DEATH probe that keeps the data: force_stop + relaunch (NOT + clear_data), then SKIP the dialog that reappears. Returns the home tree.""" + force_stop_and_relaunch() + wait_for_foreground() + n = _wait_for_home() + b = find_node(n, text="SKIP") or node_by_id(n, "button2") + if b: + tap_node(b) + settle("tap") + return ui() + + +# ── Place-store primitives ─────────────────────────────────────────────────── +# The Places LIST is EXPANDED iff `extendPanel` is in the tree; the place-info +# sheet is `bottomSheetPanel`. (listActionButton persists in the actionPanel layer +# even when everything is collapsed, so it is NOT an open/closed signal — verified.) +# After a rename+save BOTH panels are shown at once (the sheet re-appears over the +# list), so a clean row count must first dismiss the sheet. +def places_panel_open(nodes=None): + """True iff the Places LIST panel (extendPanel) is currently EXPANDED.""" + nodes = ui() if nodes is None else nodes + return node_by_id(nodes, "extendPanel") is not None + + +def _any_panel_open(nodes=None): + nodes = ui() if nodes is None else nodes + return (node_by_id(nodes, "extendPanel") is not None + or node_by_id(nodes, "bottomSheetPanel") is not None) + + +def _tap_places_button(): + btn = node_by_id(ui(), "placesButton") + return tap_node(btn) if btn else False + + +def dismiss_all_panels(): + """Collapse everything (list + place-info sheet) back to the bare map. + + Uses BACK to peel surfaces one at a time (sheet, then list), which is + deterministic, rather than tapping placesButton — from the post-save state + where BOTH the list AND the sheet are shown, a placesButton toggle leaves the + store in a broken state whose list then reads EMPTY (observed root cause of the + rename-reopen []-readback failures).""" + for _ in range(6): + if not _any_panel_open(ui()): + return + back() + settle("tap") + # Fallback: if BACK left something, one placesButton toggle as a last resort. + if _any_panel_open(ui()): + _tap_places_button() + settle("tap") + + +def open_places(): + """Return a CLEAN Places LIST tree: list panel (extendPanel) EXPANDED with no + place-info sheet (bottomSheetPanel) overlaying it. + + Converges deterministically instead of counting placesButton toggles (which is + fragile from the post-save state where BOTH the list AND the sheet are shown): + * a lingering sheet is closed with BACK (closes the sheet, keeps the list + underneath) — NOT by tapping placesButton, which would toggle the LIST shut; + * the list is opened with a single placesButton tap only when it is absent; + * done when extendPanel is present, no sheet, and the list has SETTLED + (a place row or the empty-state string is actually rendered — guards the + transitional empty frame that produced the []-readback failures).""" + for _ in range(6): + n = ui() + has_list = node_by_id(n, "extendPanel") is not None + has_sheet = node_by_id(n, "bottomSheetPanel") is not None + if has_sheet: + back() # drop the sheet, keep the list + settle("tap") + continue + if not has_list: + if not _tap_places_button(): # open the list + return n + settle("tap") + continue + # list open, no sheet — require it to have settled before returning + settled = (any("appear here" in x.get("text", "") for x in n) + or len(place_row_names(n)) > 0 + or node_by_id(n, "listActionButton") is not None) + if settled: + return n + settle("tap") + return ui() + + +def close_panel_if_open(): + """Collapse everything back to the bare map (so a subsequent create happens from + a closed panel, and a fresh re-expand picks up the new place).""" + dismiss_all_panels() + + +def and_enter_places(): + """Home -> Places LIST (EXPANDED, no sheet). Backs a depth>=1 claim. Returns + (ok, panel_nodes).""" + before = and_showing(ui()) + panel = open_places() + ok = surface_changed(before, and_showing(panel)) and places_panel_open(panel) + if ok: + and_enter("places") + return ok, panel + + +def place_row_names(panel_nodes=None): + """The place-row names currently in the OPEN Places panel, top->bottom. + + On the plain Places panel each `name` node is exactly one place/data-source + row (the place-info sheet, which reuses the `name` id, is NOT open here). Rows + are returned in vertical order, which is what a multi-record ordering check + asserts against.""" + panel_nodes = ui() if panel_nodes is None else panel_nodes + rows = [] + for n in panel_nodes: + rid = n.get("resource-id", "") + if rid.rsplit("/", 1)[-1] == "name" and n.get("text", "").strip(): + y = n.get("_bounds", (0, 0, 0, 0))[1] + rows.append((y, n["text"].strip())) + rows.sort(key=lambda t: t[0]) + return [t[1] for t in rows] + + +def place_count(panel_nodes=None): + """Number of place rows in the OPEN Places panel.""" + return len(place_row_names(panel_nodes)) + + +def long_press_places_button(): + """Long-press the Places bottom-bar button -> creates a place at map centre. + Returns True if the button was found and long-pressed.""" + btn = node_by_id(ui(), "placesButton") + if btn is None: + return False + return long_press(btn, ms=900) + + +def _sheet_title(sheet_nodes): + """The place-info sheet's TITLE `name` — the one INSIDE bottomSheetPanel, not + the list row that may still be visible behind it. The sheet title sits at or + below the editButton row's top; pick the `name` node with the LARGEST y (the + list rows are always above the sheet).""" + sp = node_by_id(sheet_nodes, "bottomSheetPanel") + if sp is None: + return None + names = [x for x in sheet_nodes + if x.get("resource-id", "").rsplit("/", 1)[-1] == "name"] + if not names: + return None + # sheet title is the lowest name node (list rows are higher on screen) + return max(names, key=lambda x: x.get("_bounds", (0, 0, 0, 0))[1]) + + +def and_enter_place_info(name): + """Places panel -> the place-info bottom sheet for the row `name`. Backs a + depth step. Returns (ok, sheet_nodes) where the sheet's TITLE has SETTLED to a + non-empty value (re-tapping the row if the first open bound an empty title — + observed after a rename+save+reopen, where the list/sheet rebind is async).""" + for attempt in range(3): + n = open_places() + row = None + for cand in n: + if (cand.get("resource-id", "").rsplit("/", 1)[-1] == "name" + and cand.get("text", "").strip() == name): + row = cand + break + if row is None: + row = find_node_ci(n, name) + if row is None or not tap_node(row): + if attempt < 2: + continue + return False, n + settle("tap") + # Wait for the sheet to open AND its title to bind to non-empty text. + sheet = ui() + for _ in range(5): + title = _sheet_title(sheet) + if (node_by_id(sheet, "bottomSheetPanel") is not None + and node_by_id(sheet, "editButton") is not None + and title is not None and title.get("text", "").strip()): + and_enter("place_info") + return True, sheet + settle("tap") + sheet = ui() + # Title never populated on this attempt -> dismiss the sheet and retry. + if node_by_id(sheet, "bottomSheetPanel") is not None: + back() + settle("tap") + return (node_by_id(ui(), "bottomSheetPanel") is not None), ui() + + +def and_enter_place_edit(): + """place-info sheet -> edit fragment (nameEdit present). Backs a depth step. + Returns (ok, edit_nodes).""" + btn = node_by_id(ui(), "editButton") + if btn is None or not tap_node(btn): + return False, ui() + settle("tap") + e = ui() + ok = node_by_id(e, "nameEdit") is not None + if ok: + and_enter("place_edit") + return ok, e + + +def set_name_field(marker): + """Replace the edit fragment's nameEdit content with `marker`, robustly. + + The field never exposes its `text=` attribute, so emptiness can't be read back. + The field is re-found on a FRESH dump (the keyboard may have shifted it since the + fragment opened) and focus is verified, then it is cleared in BOTH directions — + MOVE_END + backspaces AND MOVE_HOME + forward-deletes — because MOVE_END on this + custom EditText does not reliably reach the true end, so a one-directional clear + leaves a tail (observed: a stray "…gadgjlg" survived plain backspacing). With the + field truly empty, the marker is typed. Asserted downstream on the list row.""" + fld = node_by_id(ui(), "nameEdit") + if fld is None: + return False + for _ in range(2): + if not tap_node(fld): + return False + settle("keyboard") + fresh = node_by_id(ui(), "nameEdit") + if fresh is not None and fresh.get("focused") == "true": + fld = fresh + break + fld = fresh or fld + press_key("KEYCODE_MOVE_END") + for _ in range(50): + press_key("KEYCODE_DEL") + press_key("KEYCODE_MOVE_HOME") + for _ in range(50): + press_key("KEYCODE_FORWARD_DEL") + # Field is now empty; type the marker (the re-tap lands at position 0). + type_text(node_by_id(ui(), "nameEdit") or fld, marker, verify_focus=False) + return True + + +def save_place_edit(): + """Save from the edit fragment via the orange check actionButton (SAVE). + + The FAB sits ABOVE the soft keyboard, so it is tapped directly on a fresh dump + WITHOUT hide_keyboard() — hide_keyboard()'s BACK fallback can pop the edit + fragment instead of just lowering the IME. If a first tap does not leave the + edit surface (nameEdit still present), the IME is lowered by tapping an inert + map region (never BACK) and the FAB is tapped again.""" + btn = node_by_id(ui(), "actionButton") + if btn is None: + return False + tap_node(btn) + settle("tap") + if node_by_id(ui(), "nameEdit") is None: + return True # left the edit fragment -> saved + # Still in edit: lower the IME by tapping high on the map (inert), retry the FAB. + s_info = get_screen_info() + tap(s_info["center_x"], int(s_info["height"] * 0.12)) + settle("keyboard") + btn2 = node_by_id(ui(), "actionButton") + if btn2 is not None: + tap_node(btn2) + settle("tap") + return node_by_id(ui(), "nameEdit") is None + + +def delete_from_sheet(): + """Delete the place from its info sheet. The trash `deleteButton` is + long-clickable and only fires on a LONG-PRESS (a plain tap is ignored, to guard + against accidental deletion). Verified on the original. Returns True if the + long-press was dispatched to the button.""" + btn = node_by_id(ui(), "deleteButton") + if btn is None: + return False + return long_press(btn, ms=900) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1. CREATE (long-press placesButton) — count 0 -> 1 +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_create_place_longpress", + "interaction_create_place_marker_vlm", + "interaction_place_saved_snackbar_vlm")) +def test_create_place_longpress(): + virgin_home() + ok_p, panel = and_enter_places() + if not ok_p: + record("interaction_create_place_longpress", False, + "setup_failed: could not open the Places panel", + depth=1, jump_kind="transition", expect="place count 0->1") + vlm_assert("interaction_create_place_marker", "setup skipped", RESULTS_DIR, + expect="YES", depth=1, jump_kind="transition", tag="position") + vlm_assert("interaction_place_saved_snackbar", "setup skipped", RESULTS_DIR, + expect="YES", depth=0, jump_kind="transition", tag="content") + return + # A virgin (clear_data) DB shows the empty-state string and has no real rows. + # Reading the empty-state is stale-node proof: a lingering `name` node from a + # prior test's place-info sheet would NOT bring the "appear here" text back. + empty_before = any("appear here" in x.get("text", "") for x in panel) + before = place_count(panel) # expected 0 on a virgin DB + close_panel_if_open() + + created = long_press_places_button() + # The "Place saved" snackbar is transient and canvas-adjacent -> capture NOW. + vlm_assert("interaction_place_saved_snackbar", + "Is a dark snackbar/toast shown near the bottom of the screen " + "containing the text 'Place saved'?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="transition", + tag="content") + # A pin marker labelled 'Place #1' is CANVAS-drawn on the map (never in the tree). + vlm_assert("interaction_create_place_marker", + "Is a map pin/marker drawn near the centre of the map, with the " + "text label 'Place #1' next to it?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", + tag="position") + + panel2 = open_places() + after = place_count(panel2) + has_row = find_node_ci(panel2, "Place #1") is not None + empty_after = any("appear here" in x.get("text", "") for x in panel2) + # 0 -> 1: virgin empty-state before; exactly the 'Place #1' row (and no empty + # state) after. empty_before is the stale-node-proof 0 signal. + ok = (created and empty_before and before == 0 + and has_row and after == 1 and not empty_after) + record("interaction_create_place_longpress", ok, + "" if ok else "behavior_wrong: long-press did not add a 'Place #1' row " + f"(empty_before={empty_before}, before={before}, after={after}, " + f"row={has_row}, empty_after={empty_after})", + depth=1, jump_kind="transition", + expect="empty-state before; row 'Place #1' + count 1 after") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2. CREATE a 2nd place — multi-record, BOTH rows present +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_create_two_places", + "interaction_two_markers_vlm")) +def test_create_two_places(): + virgin_home() + long_press_places_button() # Place #1 + close_panel_if_open() + long_press_places_button() # Place #2 (same map centre) + close_panel_if_open() # bare map so the pin is visible + # Both places are created at the unchanged map centre, so their pins COINCIDE + # into one marker whose label shows the latest name -> assert that exact render. + vlm_assert("interaction_two_markers", + "Is a map pin/marker drawn near the vertical centre of the map with " + "the text label 'Place #2' shown directly above it?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", + tag="position") + ok_p, panel = and_enter_places() + names = place_row_names(panel) + has1 = any("Place #1" == x for x in names) + has2 = any("Place #2" == x for x in names) + ok = ok_p and has1 and has2 and len(names) == 2 + record("interaction_create_two_places", ok, + "" if ok else "behavior_wrong: expected rows 'Place #1' and 'Place #2' " + f"(got {names})", + depth=1, jump_kind="transition", + expect="rows ['Place #1','Place #2'] both present") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3. MULTI-RECORD INTEGRITY — add 3, rename the 2nd, 1st & 3rd intact & ordered +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_multi_record_integrity",)) +def test_multi_record_integrity(): + virgin_home() + for _ in range(3): + long_press_places_button() # Place #1, #2, #3 + close_panel_if_open() + + ok_p, panel = and_enter_places() + names0 = place_row_names(panel) + # The Places list is ordered by distance-to-reference / name, NOT by insertion + # order (PlaceDbDataSource.getCursor), so assert the SET of three rows, not their + # sequence — an ordering assertion here would be brittle by construction. + if not (ok_p and set(names0) == {"Place #1", "Place #2", "Place #3"} + and len(names0) == 3): + record("interaction_multi_record_integrity", False, + f"setup_failed: expected 3 rows {{#1,#2,#3}}, got {names0}", + depth=1, jump_kind="transition", + expect="rows {'Place #1','Place #2','Place #3'} before edit") + return + + # Rename the SECOND row -> a distinctive marker the read-back cannot alias. + MARK = "kit_mid_B" + ok_info, _ = and_enter_place_info("Place #2") + ok_edit, edit = and_enter_place_edit() + if not (ok_info and ok_edit): + record("interaction_multi_record_integrity", False, + "setup_failed: could not open the edit fragment for 'Place #2'", + depth=3, jump_kind="transition", expect="row 2 renamed, 1&3 intact") + return + set_name_field(MARK) + save_place_edit() + + panel2 = open_places() + names = place_row_names(panel2) + # Integrity (order-independent): still exactly 3 records; rows 1 & 3 keep their + # EXACT original names (a single-row recreation cannot show both), the edited + # record now reads MARK, and the old "Place #2" name is gone. + ok = (len(names) == 3 and names.count("Place #1") == 1 + and names.count("Place #3") == 1 and MARK in names + and "Place #2" not in names) + record("interaction_multi_record_integrity", ok, + "" if ok else "behavior_wrong: editing row 2 must keep rows 1 & 3 intact " + f"with 3 total and #2 renamed to '{MARK}'; got {names}", + depth=3, jump_kind="transition", + expect=f"3 rows: 'Place #1','Place #3','{MARK}' present, 'Place #2' absent") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4. RENAME a place (edit -> save) — the row now reads the new name, old is gone +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_rename_place", + "interaction_rename_map_label_vlm")) +def test_rename_place(): + MARK = "kit_rec_A" + virgin_home() + long_press_places_button() # Place #1 + close_panel_if_open() + + ok_info, _ = and_enter_place_info("Place #1") + ok_edit, edit = and_enter_place_edit() + if not (ok_info and ok_edit): + record("interaction_rename_place", False, + "setup_failed: could not reach the edit fragment", + depth=3, jump_kind="transition", + expect=f"row '{MARK}' replaces 'Place #1'") + vlm_assert("interaction_rename_map_label", "setup skipped", RESULTS_DIR, + expect="YES", depth=3, jump_kind="transition", tag="content") + return + absent_before = find_node_ci(ui(), MARK) is None + set_name_field(MARK) + save_place_edit() + + # The map LABEL beside the pin also re-renders to the new name (canvas-drawn). + vlm_assert("interaction_rename_map_label", + f"Is the text label '{MARK}' drawn on the map next to a pin/marker?", + RESULTS_DIR, expect="YES", depth=3, jump_kind="transition", + tag="content") + + panel = open_places() + names = place_row_names(panel) + ok = (absent_before and MARK in names and "Place #1" not in names) + record("interaction_rename_place", ok, + "" if ok else "behavior_wrong: rename did not replace 'Place #1' with " + f"'{MARK}' (names={names})", + depth=3, jump_kind="transition", + expect=f"row '{MARK}' present, 'Place #1' absent") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5. RENAME survives PROCESS DEATH — the renamed row is still there after restart +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_rename_persists",)) +def test_rename_persists(): + MARK = "kit_persist_C" + virgin_home() + long_press_places_button() + close_panel_if_open() + ok_info, _ = and_enter_place_info("Place #1") + ok_edit, edit = and_enter_place_edit() + if not (ok_info and ok_edit): + record("interaction_rename_persists", False, + "setup_failed: could not reach the edit fragment", + depth=1, jump_kind="transition", + expect=f"row '{MARK}' present after relaunch") + return + set_name_field(MARK) + save_place_edit() + + relaunch_and_skip() # PROCESS DEATH, data kept + panel = open_places() + names = place_row_names(panel) + ok = MARK in names and "Place #1" not in names + record("interaction_rename_persists", ok, + "" if ok else "behavior_wrong: renamed place did not survive process " + f"death (names={names})", + depth=1, jump_kind="transition", + expect=f"row '{MARK}' present after relaunch") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 6. CREATE survives PROCESS DEATH — highest-value test (in-memory recreation fails) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_create_persists",)) +def test_create_survives_process_death(): + virgin_home() + ok_p, panel = and_enter_places() + absent_before = ok_p and find_node_ci(panel, "Place #1") is None + close_panel_if_open() + long_press_places_button() # create Place #1 + + relaunch_and_skip() # kill process, relaunch, SKIP + panel2 = open_places() + present_after = find_node_ci(panel2, "Place #1") is not None + ok = absent_before and present_after + record("interaction_create_persists", ok, + "" if ok else "behavior_wrong: 'Place #1' did not survive process death " + f"(absent_before={absent_before}, present_after={present_after})", + depth=1, jump_kind="transition", + expect="row 'Place #1' present after relaunch") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 7. MULTI-RECORD count survives PROCESS DEATH — both places persist +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_multi_record_persists",)) +def test_multi_record_persists(): + virgin_home() + long_press_places_button() # Place #1 + close_panel_if_open() + long_press_places_button() # Place #2 + + relaunch_and_skip() + panel = open_places() + names = place_row_names(panel) + ok = ("Place #1" in names and "Place #2" in names and len(names) == 2) + record("interaction_multi_record_persists", ok, + "" if ok else "behavior_wrong: both places must survive process death " + f"(names={names})", + depth=1, jump_kind="transition", + expect="rows ['Place #1','Place #2'] after relaunch") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 8. CREATE via coordinate dialog — Places FAB -> Enter coordinates -> OK +# ══════════════════════════════════════════════════════════════════════════════ +def and_enter_coord_dialog(): + """Places panel -> the FAB -> 'Enter coordinates' dialog. Backs a depth step. + Returns (ok, dialog_nodes).""" + n = open_places() + fab = node_by_id(n, "listActionButton") + if fab is None or not tap_node(fab): + return False, n + settle("tap") + d = ui() + ok = (node_by_id(d, "coordinatesEdit") is not None + or find_node_ci(d, "Enter coordinates") is not None) + if ok: + and_enter("coord_dialog") + return ok, d + + +@and_test(expects=("interaction_create_coordinate_dialog",)) +def test_create_coordinate_dialog(): + virgin_home() + ok_open, panel = and_enter_places() + before = place_count(panel) if ok_open else -1 + + ok_d, dlg = and_enter_coord_dialog() + edit = node_by_id(dlg, "coordinatesEdit") + if not (ok_d and edit is not None): + record("interaction_create_coordinate_dialog", False, + "feature_missing: no 'Enter coordinates' dialog / coordinatesEdit", + depth=2, jump_kind="transition", expect="place count 0->1 via coords") + return + # coordinatesEdit hides its text attr; type_text still focuses+enters it, and a + # valid "lat lon" then produces a place (verified on the original). + type_text(node_by_id(ui(), "coordinatesEdit"), "48.8583 2.2945") + # OK sits ABOVE the soft keyboard; tap it directly. hide_keyboard() must NOT be + # used here — its BACK fallback would CANCEL the dialog. + okbtn = find_node(ui(), text="OK") or find_node_ci(ui(), "OK") + tapped = tap_node(okbtn) if okbtn else False + settle("tap") + + panel2 = open_places() + after = place_count(panel2) + ok = tapped and before == 0 and after == 1 + record("interaction_create_coordinate_dialog", ok, + "" if ok else "behavior_wrong: entering coordinates + OK did not create a " + f"place (before={before}, after={after}, ok_tapped={tapped})", + depth=2, jump_kind="transition", expect="place count 0->1 via coords") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 9. DELETE a place — count returns to 0, marker gone (app-authored + undoable) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_delete_place", + "interaction_delete_marker_gone_vlm")) +def test_delete_place(): + virgin_home() + long_press_places_button() # Place #1 + close_panel_if_open() + + ok_p, panel = and_enter_places() + before = place_count(panel) + ok_info, sheet = and_enter_place_info("Place #1") + delbtn = node_by_id(sheet, "deleteButton") + if not (ok_p and ok_info and delbtn is not None): + record("interaction_delete_place", False, + "setup_failed: could not reach the place-info deleteButton", + depth=2, jump_kind="transition", expect="place count 1->0") + vlm_assert("interaction_delete_marker_gone", "setup skipped", RESULTS_DIR, + expect="YES", depth=2, jump_kind="transition", tag="position") + return + # deleteButton is only ever pressed on a place THIS test created; it is + # snackbar-undoable, so this is a safe, reversible destructive op in our lane. + # The trash is long-clickable (a tap is ignored), so delete_from_sheet() presses. + delete_from_sheet() + # Wait out the "Place deleted / UNDO" window so the pin + label are fully removed + # from the canvas before the screenshot and the count read-back. + for _ in range(4): + settle("tap") + + # The pin at the map centre is now gone (canvas) — no 'Place #1' label left. + vlm_assert("interaction_delete_marker_gone", + "Near the vertical centre of the map, is there NO pin/marker and NO " + "text label reading 'Place #1' (the marker has been removed)?", + RESULTS_DIR, expect="YES", depth=2, jump_kind="transition", + tag="position") + + panel2 = open_places() + after = place_count(panel2) + still = find_node_ci(panel2, "Place #1") is not None + ok = before == 1 and after == 0 and not still + record("interaction_delete_place", ok, + "" if ok else "behavior_wrong: delete did not remove 'Place #1' " + f"(before={before}, after={after}, still={still})", + depth=2, jump_kind="transition", expect="place count 1->0") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 10. DELETE one of two — the OTHER place must remain (multi-record delete) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_delete_one_of_two",)) +def test_delete_one_of_two(): + virgin_home() + long_press_places_button() # Place #1 + close_panel_if_open() + long_press_places_button() # Place #2 + + ok_p, panel = and_enter_places() + before = place_count(panel) + ok_info, sheet = and_enter_place_info("Place #1") + delbtn = node_by_id(sheet, "deleteButton") + if not (ok_p and ok_info and delbtn is not None and before == 2): + record("interaction_delete_one_of_two", False, + f"setup_failed: need 2 places + deleteButton (before={before})", + depth=2, jump_kind="transition", + expect="delete #1 -> only 'Place #2' remains") + return + delete_from_sheet() # long-press deletes Place #1 + for _ in range(4): # wait out the UNDO window + settle("tap") + + panel2 = open_places() + names = place_row_names(panel2) + ok = (names == ["Place #2"]) + record("interaction_delete_one_of_two", ok, + "" if ok else "behavior_wrong: deleting 'Place #1' must leave exactly " + f"'Place #2' (names={names})", + depth=2, jump_kind="transition", + expect="delete #1 -> only 'Place #2' remains") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 11. RENAME then REOPEN — multi-step: rename, close sheet, reopen from panel +# (each step depends on the last; a dead shell that echoes the first fails) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_rename_reopen_shows_new_name",)) +def test_rename_reopen_shows_new_name(): + MARK = "kit_reopen_D" + virgin_home() + long_press_places_button() + close_panel_if_open() + ok_info, _ = and_enter_place_info("Place #1") + ok_edit, edit = and_enter_place_edit() + if not (ok_info and ok_edit): + record("interaction_rename_reopen_shows_new_name", False, + "setup_failed: could not reach the edit fragment", + depth=2, jump_kind="transition", + expect=f"reopened sheet name == '{MARK}'") + return + set_name_field(MARK) + save_place_edit() + close_panel_if_open() # fully leave the panel/sheet + + # Reopen the place-info sheet from the panel and read the sheet TITLE back. + ok_reopen, sheet = and_enter_place_info(MARK) + title = _sheet_title(sheet) + src = node_by_id(sheet, "source") + got = title.get("text", "") if title else "" + ok = (ok_reopen and got == MARK + and src is not None and src.get("text", "") == "My places") + record("interaction_rename_reopen_shows_new_name", ok, + "" if ok else "behavior_wrong: reopened place-info sheet did not show the " + f"renamed title (got name={got!r})", + depth=2, jump_kind="transition", + expect=f"reopened sheet name == '{MARK}', source 'My places'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 12. ADD PLACE via MAP long-press context menu (exclusive lane) +# ══════════════════════════════════════════════════════════════════════════════ +def long_press_map(): + """Long-press the custom mapView -> its context menu. The map drops a + zero-distance long_press, so use a tiny-displacement timed swipe at its centre + and confirm the menu appeared, escalating the duration.""" + n = ui() + mv = node_by_id(n, "mapView") + if mv is None or "_bounds" not in mv: + return False + b = mv["_bounds"] + x = (b[0] + b[2]) // 2 + y = (b[1] + b[3]) // 2 + for ms in (1200, 1800, 2400): + before = and_showing(ui()) + swipe(x, y, x + 3, y + 3, ms) + settle("tap") + after = ui() + if find_node_ci(after, "Add place") is not None: + return True + if not surface_changed(before, and_showing(after)): + continue + return find_node_ci(ui(), "Add place") is not None + + +@and_test(expects=("interaction_add_place_map_menu", + "interaction_map_menu_marker_vlm")) +def test_add_place_map_menu(): + virgin_home() + ok_p, panel = and_enter_places() + before = place_count(panel) if ok_p else -1 + close_panel_if_open() + + if not long_press_map(): + record("interaction_add_place_map_menu", False, + "feature_missing: map long-press did not raise a context menu with " + "'Add place'", + depth=1, jump_kind="transition", + expect="place count 0->1 via map menu") + vlm_assert("interaction_map_menu_marker", "setup skipped", RESULTS_DIR, + expect="YES", depth=1, jump_kind="transition", tag="position") + return + add = find_node_ci(ui(), "Add place") + tapped = safe_tap(add) if add else False + settle("tap") + + # A pin is drawn at the long-pressed point (canvas). + vlm_assert("interaction_map_menu_marker", + "Is a map pin/marker drawn on the map (a place was just added via the " + "context menu)?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", + tag="position") + + panel2 = open_places() + after = place_count(panel2) + ok = tapped and before == 0 and after == 1 + record("interaction_add_place_map_menu", ok, + "" if ok else "behavior_wrong: 'Add place' from the map menu did not " + f"create a place (before={before}, after={after}, tapped={tapped})", + depth=1, jump_kind="transition", expect="place count 0->1 via map menu") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 13. MAP CONTEXT MENU appears on long-press (exclusive lane; menu labels present) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_map_context_menu",)) +def test_map_context_menu(): + virgin_home() + raised = long_press_map() + n = ui() + labels = ["Share coordinates", "Add place", "Navigate here", "Remember zoom"] + present = [lbl for lbl in labels if find_node_ci(n, lbl) is not None] + ok = raised and len(present) == 4 + record("interaction_map_context_menu", ok, + "" if ok else "behavior_wrong: long-press map did not show the 4-item " + f"context menu (present={present})", + depth=1, jump_kind="transition", + expect="context menu with Share/Add/Navigate/Remember") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 14. PLACE-INFO sheet shows the navigate FAB + edit/share/delete icon row (VLM) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_place_info_actions", + "interaction_place_info_fab_vlm", + "interaction_edit_color_swatch_vlm")) +def test_place_info_actions(): + virgin_home() + long_press_places_button() + close_panel_if_open() + ok_info, sheet = and_enter_place_info("Place #1") + have = {rid: node_by_id(sheet, rid) is not None + for rid in ("editButton", "shareButton", "deleteButton", "actionButton")} + ok = ok_info and all(have.values()) + record("interaction_place_info_actions", ok, + "" if ok else "behavior_wrong: place-info sheet missing action controls " + f"({have})", + depth=2, jump_kind="transition", + expect="edit+share+delete+navigate controls on sheet") + + # The orange circular navigate FAB sits at the sheet's upper-right (position). + vlm_assert("interaction_place_info_fab", + "In the place-information panel, is there a round ORANGE floating " + "action button positioned at the upper-right of the panel?", + RESULTS_DIR, expect="YES", depth=2, jump_kind="transition", + tag="position") + + # Go one deeper into the edit form and check the colour swatch is drawn. + ok_edit, _ = and_enter_place_edit() + if ok_edit: + vlm_assert("interaction_edit_color_swatch", + "In this place-edit form, is there a small filled COLOURED circle " + "(a colour swatch) shown to the right, near the Description field?", + RESULTS_DIR, expect="YES", depth=3, jump_kind="transition", + tag="color") + else: + vlm_assert("interaction_edit_color_swatch", + "setup skipped", RESULTS_DIR, expect="YES", + depth=3, jump_kind="transition", tag="color") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 15. IMPORT a places file (GPX/KML) — a new data-source row appears in Places +# (ONE import test; SAF picker is version-dependent, so it is defensive) +# ══════════════════════════════════════════════════════════════════════════════ +# The reliably-indexed places fixture -> its expected data-source row name. +IMPORT_CANDIDATES = [ + ("places_sample.gpx", "Sample Places"), + ("places_sample.kml", "Sample KML Places"), +] + + +def _tap_picker_file(fname): + """Locate `fname` anywhere in the SAF picker (scrolling if needed) and tap the + row. Returns True if a matching row was tapped.""" + for _ in range(4): + n = ui() + row = find_node(n, text=fname) + if row is None: + # some pickers expose the name only via a Preview content-desc sibling + for cand in n: + if fname in cand.get("content-desc", ""): + row = cand + break + if row is not None: + return tap_node(row) + scroll_down(0.5) + return False + + +def _open_import_picker(): + """Home -> more -> Import -> SAF picker. Returns True if the picker is up.""" + more = node_by_id(ui(), "moreButton") + if more is None or not tap_node(more): + return False + settle("tap") + imp = find_node_ci(ui(), "Import") + if imp is None or not tap_node(imp): + return False + settle("launch") + return True + + +def _do_import(): + """Drive the whole import from the picker onward. Returns (fname, source) on + success (OK confirmed), else None.""" + chosen = None + for fname, source in IMPORT_CANDIDATES: + if _tap_picker_file(fname): + chosen = (fname, source) + break + if chosen is None: + return None + settle("launch") + okbtn = node_by_id(ui(), "action") or find_node_ci(ui(), "OK") + if okbtn is not None: + tap_node(okbtn) + settle("launch") + return chosen + + +@and_test(expects=("interaction_import_places", + "interaction_import_markers_vlm")) +def test_import_places(): + push_fixtures() + virgin_home() + if not _open_import_picker(): + record("interaction_import_places", False, + "feature_missing: could not open more -> Import", + depth=1, jump_kind="transition", expect="data-source row after import") + vlm_assert("interaction_import_markers", "setup skipped", RESULTS_DIR, + expect="YES", depth=1, jump_kind="transition", tag="position") + return + chosen = _do_import() + if chosen is None: + record("interaction_import_places", False, + "setup_failed: no places fixture visible in the SAF picker " + "(picker layout/indexing differs)", + depth=1, jump_kind="transition", expect="data-source row after import") + vlm_assert("interaction_import_markers", "setup skipped", RESULTS_DIR, + expect="YES", depth=1, jump_kind="transition", tag="position") + return + + # Imported markers are drawn on the map (canvas). + vlm_assert("interaction_import_markers", + "Are one or more map pins/markers now drawn on the map (imported " + "places)?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", + tag="position") + + _fname, source = chosen + panel = open_places() + names = place_row_names(panel) + ok = any(source == x for x in names) + record("interaction_import_places", ok, + "" if ok else f"behavior_wrong: imported '{_fname}' but no data-source row " + f"'{source}' appeared (names={names})", + depth=1, jump_kind="transition", + expect=f"data-source row '{source}' after import") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 16. LONG-PRESS placesButton is the CREATE gesture (context/long-press owner): +# a plain TAP opens the panel (no create); a LONG-PRESS creates. Asserts the +# gesture SEMANTICS differ — a shell that treats both the same fails here. +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_longpress_vs_tap_semantics",)) +def test_longpress_vs_tap_semantics(): + virgin_home() + # A plain TAP must NOT create anything: panel opens on the empty state. + ok_p, panel = and_enter_places() + tap_count = place_count(panel) if ok_p else -1 + close_panel_if_open() + # A LONG-PRESS then DOES create exactly one place. + long_press_places_button() + panel2 = open_places() + lp_count = place_count(panel2) + ok = ok_p and tap_count == 0 and lp_count == 1 + record("interaction_longpress_vs_tap_semantics", ok, + "" if ok else "behavior_wrong: tap should open empty panel (0) and " + f"long-press should create 1 (tap={tap_count}, longpress={lp_count})", + depth=1, jump_kind="transition", + expect="tap -> 0 places, long-press -> 1 place") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 17. THREE creates then persistence — full multi-record set survives restart +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_three_records_persist",)) +def test_three_records_persist(): + virgin_home() + for _ in range(3): + long_press_places_button() + close_panel_if_open() + + relaunch_and_skip() + panel = open_places() + names = place_row_names(panel) + # Order-independent: the Places list sorts by distance/name, not insertion, so + # assert the SET of three survives process death (not their sequence). + ok = (len(names) == 3 + and set(names) == {"Place #1", "Place #2", "Place #3"}) + record("interaction_three_records_persist", ok, + "" if ok else "behavior_wrong: all three places must survive " + f"process death (names={names})", + depth=1, jump_kind="transition", + expect="rows {'Place #1','Place #2','Place #3'} after relaunch") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 18. EDIT the DESCRIPTION then reopen — a second editable field round-trips +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_edit_description_persists",)) +def test_edit_description_persists(): + DESC = "kit_desc_E" + virgin_home() + long_press_places_button() + close_panel_if_open() + ok_info, _ = and_enter_place_info("Place #1") + ok_edit, edit = and_enter_place_edit() + if not (ok_info and ok_edit): + record("interaction_edit_description_persists", False, + "setup_failed: could not reach the edit fragment", + depth=3, jump_kind="transition", + expect=f"description '{DESC}' shown after reopening the edit form") + return + desc = node_by_id(edit, "descriptionEdit") + if desc is None: + record("interaction_edit_description_persists", False, + "feature_missing: no descriptionEdit field", + depth=3, jump_kind="transition", + expect=f"description '{DESC}' shown after reopening the edit form") + return + type_text(desc, DESC) + save_place_edit() + close_panel_if_open() + + # Reopen the place-info sheet; the saved description is shown there in the + # `description` TextView (the edit EditText hides its text, the sheet does not). + ok_info2, sheet2 = and_enter_place_info("Place #1") + got = "" + if ok_info2: + for _ in range(5): # description may bind late + d = node_by_id(ui(), "description") + if d is not None and d.get("text", "").strip(): + got = d.get("text", "") + break + settle("tap") + ok = ok_info2 and got == DESC + record("interaction_edit_description_persists", ok, + "" if ok else "behavior_wrong: saved description did not round-trip on the " + f"place-info sheet (got {got!r})", + depth=2, jump_kind="transition", + expect=f"place-info description == '{DESC}' after reopen") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 19. RENAME to a NEW value twice — the edit is idempotent & the last write wins +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_rename_last_write_wins",)) +def test_rename_last_write_wins(): + FIRST, SECOND = "kit_first_F", "kit_second_G" + virgin_home() + long_press_places_button() + close_panel_if_open() + + # First rename Place #1 -> FIRST. + ok_i1, _ = and_enter_place_info("Place #1") + ok_e1, e1 = and_enter_place_edit() + if not (ok_i1 and ok_e1): + record("interaction_rename_last_write_wins", False, + "setup_failed: could not reach the edit fragment (first rename)", + depth=3, jump_kind="transition", + expect=f"single row '{SECOND}', earlier names absent") + return + set_name_field(FIRST) + save_place_edit() + close_panel_if_open() + + # Second rename FIRST -> SECOND. + ok_i2, _ = and_enter_place_info(FIRST) + ok_e2, e2 = and_enter_place_edit() + if not (ok_i2 and ok_e2): + record("interaction_rename_last_write_wins", False, + "setup_failed: could not reopen the edit fragment (second rename)", + depth=3, jump_kind="transition", + expect=f"single row '{SECOND}', earlier names absent") + return + set_name_field(SECOND) + save_place_edit() + + panel = open_places() + names = place_row_names(panel) + ok = (SECOND in names and FIRST not in names and "Place #1" not in names + and len(names) == 1) + record("interaction_rename_last_write_wins", ok, + "" if ok else "behavior_wrong: last rename must win with a single row " + f"'{SECOND}' (names={names})", + depth=3, jump_kind="transition", + expect=f"single row '{SECOND}', earlier names absent") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 20. CREATE-then-DELETE round-trip in one session — count 0 -> 1 -> 0 +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_create_delete_roundtrip",)) +def test_create_delete_roundtrip(): + virgin_home() + ok_p0, panel0 = and_enter_places() + c0 = place_count(panel0) if ok_p0 else -1 + close_panel_if_open() + + long_press_places_button() # 0 -> 1 + panel1 = open_places() + c1 = place_count(panel1) + + ok_info, sheet = and_enter_place_info("Place #1") + delbtn = node_by_id(sheet, "deleteButton") + if not (ok_info and delbtn is not None): + record("interaction_create_delete_roundtrip", False, + "setup_failed: could not reach the deleteButton", + depth=2, jump_kind="transition", expect="count 0->1->0") + return + delete_from_sheet() # long-press: 1 -> 0 + for _ in range(4): # wait out the UNDO window + settle("tap") + panel2 = open_places() + c2 = place_count(panel2) + ok = (c0 == 0 and c1 == 1 and c2 == 0) + record("interaction_create_delete_roundtrip", ok, + "" if ok else "behavior_wrong: create/delete round-trip broke the count " + f"(c0={c0}, c1={c1}, c2={c2})", + depth=2, jump_kind="transition", expect="count 0->1->0") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 21. IMPORTED places persist across PROCESS DEATH — data-source survives restart +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_import_persists",)) +def test_import_persists(): + push_fixtures() + virgin_home() + if not _open_import_picker(): + record("interaction_import_persists", False, + "feature_missing: could not open more -> Import", + depth=1, jump_kind="transition", + expect="imported data-source row after relaunch") + return + chosen = _do_import() + if chosen is None: + record("interaction_import_persists", False, + "setup_failed: no places fixture visible in the SAF picker", + depth=1, jump_kind="transition", + expect="imported data-source row after relaunch") + return + + _fname, source = chosen + relaunch_and_skip() # PROCESS DEATH, data kept + panel = open_places() + names = place_row_names(panel) + ok = any(source == x for x in names) + record("interaction_import_persists", ok, + "" if ok else "behavior_wrong: imported data-source did not survive " + f"process death (source '{source}', names={names})", + depth=1, jump_kind="transition", + expect=f"data-source row '{source}' after relaunch") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 22. COORDINATE-created place carries the entered location into its info sheet +# (multi-step: coord dialog -> create -> open info -> coordinates row present) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_coord_place_has_info",)) +def test_coord_place_has_info(): + virgin_home() + ok_open, _ = and_enter_places() + ok_d, dlg = and_enter_coord_dialog() + edit = node_by_id(dlg, "coordinatesEdit") if ok_d else None + if not (ok_open and edit is not None): + record("interaction_coord_place_has_info", False, + "feature_missing: no coordinate dialog to create from", + depth=2, jump_kind="transition", + expect="coord place -> info sheet with a coordinates row") + return + type_text(node_by_id(ui(), "coordinatesEdit"), "51.5007 -0.1246") + # OK is above the keyboard; tap directly (BACK would cancel the dialog). + okbtn = find_node(ui(), text="OK") or find_node_ci(ui(), "OK") + if okbtn: + tap_node(okbtn) + settle("tap") + + # The coordinate create names it 'Place #1'; open its info sheet and confirm the + # coordinates row is populated (a real data record, not just a transient pin). + panel = open_places() + if find_node_ci(panel, "Place #1") is None: + record("interaction_coord_place_has_info", False, + "behavior_wrong: coordinate entry did not create a 'Place #1' row", + depth=2, jump_kind="transition", + expect="coord place -> info sheet with a coordinates row") + return + ok_info, sheet = and_enter_place_info("Place #1") + coords = node_by_id(sheet, "coordinates") + src = node_by_id(sheet, "source") + coord_txt = coords.get("text", "") if coords else "" + ok = (ok_info and coords is not None and coord_txt.strip() != "" + and src is not None and src.get("text", "") == "My places") + record("interaction_coord_place_has_info", ok, + "" if ok else "behavior_wrong: coord-created place has no populated " + f"coordinates row on its info sheet (coords={coord_txt!r})", + depth=2, jump_kind="transition", + expect="info sheet 'My places' + non-empty coordinates row") + + +TESTS = [ + test_create_place_longpress, + test_create_two_places, + test_multi_record_integrity, + test_rename_place, + test_rename_persists, + test_create_survives_process_death, + test_multi_record_persists, + test_create_coordinate_dialog, + test_delete_place, + test_delete_one_of_two, + test_rename_reopen_shows_new_name, + test_add_place_map_menu, + test_map_context_menu, + test_place_info_actions, + test_import_places, + test_longpress_vs_tap_semantics, + test_three_records_persist, + test_edit_description_persists, + test_rename_last_write_wins, + test_create_delete_roundtrip, + test_import_persists, + test_coord_place_has_info, +] + + +if __name__ == "__main__": + if not device_online(): + print("Device not reachable — the adb tunnel may be down.") + run_suite(TESTS, "interaction") diff --git a/android/andreynovikov-trekarta/tests/test_android_navigation.py b/android/andreynovikov-trekarta/tests/test_android_navigation.py new file mode 100644 index 0000000000000000000000000000000000000000..f758165d8dc225096fb7270b059e456b3c3c893d --- /dev/null +++ b/android/andreynovikov-trekarta/tests/test_android_navigation.py @@ -0,0 +1,783 @@ +#!/usr/bin/env python3 +"""NAVIGATION module for Trekarta (mobi.maptrek). + +Lane: surface REACHABILITY + back-stack integrity. This module is the SOLE owner +of jump_kind="reach" and of depth>=2 chains. Every forward jump is PROVEN with +and_reach(before, after, target, source): the TARGET surface's discriminating +element APPEARED and (where the source surface truly leaves the tree) the SOURCE +element DISAPPEARED. A screen that was in the dump all along is never "reached". + +Trekarta's panels/menus are ADDITIVE overlays over the persistent map + bottom bar +(mapView, the 5 bottom ImageButtons and the "© OpenStreetMap contributors" label +stay in the tree). So the first hop from HOME uses a target-only reach — the panel +target genuinely appears where it was absent on home, which cannot be faked. The +DEEP hops (more->Settings, Settings->Units, panel->dialog, list->detail) replace +their prior surface's items, so those carry a real source-disappeared proof too. + +A BACK to a SUBSET surface (a panel closing back to the map) has no newly-appearing +element — the map was there all along — so those back-stack cases assert the deep +surface's key DISAPPEARED plus the home/parent predicate, recorded as a state +transition (surface popped), never a fake "reach". + +Reaching a surface by relaunching is NOT navigation — every jump starts from a real +prior surface. Each test owns its entry via dismiss_first_run() (the base-map +download AlertDialog reappears on EVERY launch and must be SKIPped; never DOWNLOAD). +""" +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403 + + +# ── App-specific entry point ───────────────────────────────────────────────── +def dismiss_first_run(): + """Launch fresh, wait for the real home (past the splash), and SKIP the + recurring base-map dialog. Returns the settled home tree (post-SKIP).""" + restart_app() + wait_for_foreground() + _wait_home_ready() + n = ui() + b = find_node(n, text="SKIP") or node_by_id(n, "button2") + if b: + tap_node(b) + settle("tap") + return ui() + + +HOME_BUTTONS = ("locationButton", "tracksButton", "placesButton", + "mapsButton", "moreButton") + + +def home_ready(nodes): + """True iff the map surface is present: mapView + all 5 bottom buttons.""" + return (node_by_id(nodes, "mapView") is not None + and all(node_by_id(nodes, b) for b in HOME_BUTTONS)) + + +def _wait_home_ready(timeout=12): + """Block past the Trekarta splash: wait_for_foreground() returns while the + logo is up and uiautomator then hands back a STALE tree. Poll until + home_ready() or the first-run dialog button2 is present.""" + import time as _t + deadline = _t.time() + timeout + while _t.time() < deadline: + n = ui() + if home_ready(n) or node_by_id(n, "button2") is not None: + return n + settle("key") + return ui() + + +def _gone(nodes, needle): + """True iff no on-screen key contains `needle` (case-insensitive) — i.e. the + surface that owned `needle` has left.""" + n = needle.strip().lower() + return not any(n in k.lower() for k in and_showing(nodes)) + + +# ══════════════════════════════════════════════════════════════════════════════ +# depth-family helpers. The and_enter_*/and_reach_* NAME is what the depth audit +# looks for to back a declared depth; the implementation is ours. Each returns a +# bool (or (bool, nodes)) and counts one surface via the kit on success. +# ══════════════════════════════════════════════════════════════════════════════ + +def and_reach_panel(nodes, rid, target, source=None): + """Home -> a bottom-bar panel/menu (moreButton / placesButton / ...). The + panel overlays the map additively, so `source` is usually None: the proof is + that `target` appeared where it was absent on home. Returns (ok, panel_nodes).""" + btn = node_by_id(nodes, rid) + if not btn: + return False, nodes + before = and_showing(nodes) + if not tap_node(btn): + return False, nodes + after_nodes = ui() + ok = and_reach(before, and_showing(after_nodes), target, source) + if ok: + and_enter(rid) + return ok, after_nodes + + +def and_enter_more(nodes): + """Open the more-menu extendPanel. Returns (ok, panel_nodes).""" + return and_reach_panel(nodes, "moreButton", "Settings") + + +def and_reach_from_more(item_text, target, source): + """Home -> more -> `item_text`. Two surfaces crossed. The more-menu items + (Settings/Import/Ruler/...) leave the tree on the destination, so this is a + full target-appeared + source-disappeared reach. Returns (ok, dest_nodes, note).""" + home = dismiss_first_run() + ok_more, panel = and_enter_more(home) + if not ok_more: + return False, panel, "setup_failed: more-menu did not open" + row = find_node(panel, text=item_text) or find_node_ci(panel, item_text) + if not row: + return False, panel, f"feature_missing: '{item_text}' row absent on more-menu" + before = and_showing(panel) + if not tap_node(row): + return False, panel, "setup_failed: more-menu item not tappable" + dest = ui() + ok = and_reach(before, and_showing(dest), target, source) + if ok: + and_enter(item_text) + return ok, dest, "" + + +def and_reach_settings(): + """Home -> more -> Settings. Category list (General/Units/About) appears; the + more-menu items (Import/Ruler/...) leave. Returns (ok, settings_nodes).""" + ok, dest, _ = and_reach_from_more("Settings", "General", "Import") + return ok, dest + + +def and_reach_units(settings_nodes): + """Settings categories -> Units sub-page. Unit rows (Speed/Distance/...) and + their summaries appear; the sibling categories (About/Advanced) leave. Returns + (ok, units_nodes).""" + row = find_node(settings_nodes, text="Units") + if not row: + return False, settings_nodes + before = and_showing(settings_nodes) + if not tap_node(row): + return False, settings_nodes + units = ui() + ok = and_reach(before, and_showing(units), "Speed", "About") + if ok: + and_enter("units") + return ok, units + + +def ensure_one_place(): + """From home, long-press placesButton to create a place at map centre so a + place row exists to navigate to. (Bottom-bar buttons long-press fine with the + kit helper.) Returns the home tree with the place created.""" + home = dismiss_first_run() + pb = node_by_id(home, "placesButton") + if pb: + long_press(pb, ms=900) + settle("tap") + return ui() + + +def and_reach_places_panel(nodes): + """Open the Places panel. FAB (listActionButton) appears; absent on home. + Returns (ok, panel_nodes).""" + return and_reach_panel(nodes, "placesButton", "listActionButton") + + +def and_reach_place_info(panel_nodes): + """Places panel -> tap a place row -> place-info bottom sheet. The sheet's + source field ("My places") appears; the list FAB (listActionButton) leaves. + Returns (ok, info_nodes).""" + row = find_node(panel_nodes, text="Place #1") or node_by_id(panel_nodes, "name") + if not row or not is_safe(row): + return False, panel_nodes + before = and_showing(panel_nodes) + if not tap_node(row): + return False, panel_nodes + info = ui() + ok = and_reach(before, and_showing(info), "My places", "listActionButton") + if ok: + and_enter("place_info") + return ok, info + + +def and_reach_place_edit(info_nodes): + """Place-info sheet -> editButton -> edit fragment (nameEdit / Description / + colorSwatch). The Description EditText appears. Returns (ok, edit_nodes).""" + eb = node_by_id(info_nodes, "editButton") + if not eb: + return False, info_nodes + before = and_showing(info_nodes) + if not tap_node(eb): + return False, info_nodes + edit = ui() + # The description EditText (hint "Description") is unique to the edit fragment. + ok = and_reach(before, and_showing(edit), "Description") + if ok: + and_enter("place_edit") + return ok, edit + + +def long_press_map(): + """Genuine long-press at map centre until the context menu opens. The kit's + long_press is a ZERO-distance swipe that this custom android.view.View ignores, + so retry with a tiny displacement and increasing hold until the surface grows. + Coordinates are DERIVED from screen geometry, never literals. Returns (ok, + new_keys).""" + s = get_screen_info() + x, y = s["center_x"], s["center_y"] + dx = max(2, s["width"] // 500) + before = and_showing() + for i in range(4): + adb_shell("input", "swipe", int(x), int(y), + int(x + dx), int(y + dx), 1200 + i * 400) + settle("tap") + after = and_showing() + if surface_changed(before, after, min_delta=3): + return True, (after - before) + return False, set() + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1. HOME -> MORE menu (depth 1) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("nav_reach_more", "nav_reach_more_vlm")) +def test_reach_more(): + home = dismiss_first_run() + ok, panel = and_reach_panel(home, "moreButton", "Settings") + # Corroborate with the panel container + a second labelled item. + ok = ok and node_by_id(panel, "extendPanel") is not None \ + and find_node(panel, text="Ruler") is not None + record("nav_reach_more", bool(ok), + "" if ok else "feature_missing: more-menu (extendPanel with Settings/Ruler) not reached", + depth=1, jump_kind="reach", + expect="more-menu items (Settings, Ruler) appeared over the map after tapping moreButton") + + vlm_assert("nav_reach_more", + "Is a vertical text menu panel overlaying the RIGHT side of the " + "screen while a map is still visible on the LEFT side?", + RESULTS_DIR, tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2. HOME -> PLACES panel (depth 1) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("nav_reach_places",)) +def test_reach_places(): + home = dismiss_first_run() + ok, panel = and_reach_places_panel(home) + ok = ok and (node_by_id(panel, "extendPanel") + or node_by_id(panel, "contentPanel")) is not None + record("nav_reach_places", bool(ok), + "" if ok else "feature_missing: Places panel (listActionButton FAB) not reached", + depth=1, jump_kind="reach", + expect="Places panel FAB (listActionButton) appeared after tapping placesButton") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3. HOME -> TRACKS panel (depth 1) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("nav_reach_tracks",)) +def test_reach_tracks(): + home = dismiss_first_run() + ok, panel = and_reach_panel(home, "tracksButton", + "Your recorded tracks will appear here.") + record("nav_reach_tracks", bool(ok), + "" if ok else "feature_missing: Tracks panel empty-state not reached", + depth=1, jump_kind="reach", + expect="Tracks empty-state 'Your recorded tracks will appear here.' appeared after tapping tracksButton") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4. HOME -> MAPS panel (depth 1) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("nav_reach_maps",)) +def test_reach_maps(): + home = dismiss_first_run() + ok, panel = and_reach_panel(home, "mapsButton", + "Your installed custom tile maps will appear here.") + record("nav_reach_maps", bool(ok), + "" if ok else "feature_missing: Maps panel empty-state not reached", + depth=1, jump_kind="reach", + expect="Maps empty-state 'Your installed custom tile maps will appear here.' appeared after tapping mapsButton") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5. HOME -> MORE -> SETTINGS (depth 2) — source (more items) disappears +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("nav_reach_settings", "nav_reach_settings_vlm")) +def test_reach_settings(): + ok, s = and_reach_settings() + ok = ok and (node_by_id(s, "recycler_view") + or find_by_class(s, "RecyclerView")) is not None + record("nav_reach_settings", bool(ok), + "" if ok else "feature_missing: Settings category list not reached from more-menu", + depth=2, jump_kind="reach", + expect="Settings category 'General' appeared and more-menu 'Import' left, after more->Settings") + + vlm_assert("nav_reach_settings", + "Is a bottom sheet slid up over the lower part of the screen " + "showing a vertical list of at least four text menu rows?", + RESULTS_DIR, tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 6. SETTINGS -> UNITS sub-page (depth 3) — a real deep chain +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("nav_reach_units", "nav_reach_units_vlm")) +def test_reach_units(): + ok_s, s = and_reach_settings() + if not ok_s: + record("nav_reach_units", False, + "setup_failed: could not reach Settings before opening Units", + depth=3, jump_kind="reach", + expect="Units row 'Speed' appeared and category 'About' left, after Settings->Units") + else: + ok_u, u = and_reach_units(s) + ok_u = ok_u and find_node(u, text="miles per hour") is not None + record("nav_reach_units", bool(ok_u), + "" if ok_u else "behavior_wrong: Units sub-page (Speed/Distance rows) not reached from Settings", + depth=3, jump_kind="reach", + expect="Units row 'Speed' + summary 'miles per hour' appeared and category 'About' left") + + vlm_assert("nav_reach_units", + "Does this settings sub-page list rows each with a bold label on " + "the left and a smaller grey value line beneath it?", + RESULTS_DIR, tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 7. SETTINGS -> ABOUT (depth 3) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("nav_reach_about",)) +def test_reach_about(): + # About is a category on the Settings sheet; reach Settings, then About. + # Source key = "Advanced" (NOT "General": the About copyright text contains + # "GNU General Public License", so "General" would survive as a substring and + # break the source-disappeared clause). + ok_s, s = and_reach_settings() + if not ok_s: + record("nav_reach_about", False, + "setup_failed: could not reach Settings before opening About", + depth=3, jump_kind="reach", + expect="About page 'Version: N' appeared and category 'Advanced' left") + return + row = find_node(s, text="About") + if not row: + record("nav_reach_about", False, + "feature_missing: About row absent on Settings sheet", + depth=3, jump_kind="reach", + expect="About page 'Version: N' appeared and category 'Advanced' left") + return + before = and_showing(s) + tap_node(row) + about = ui() + ver = any(n.get("text", "").startswith("Version:") for n in about) + ok = and_reach(before, and_showing(about), "Version:", "Advanced") and ver + if ok: + and_enter("about") + record("nav_reach_about", bool(ok), + "" if ok else "behavior_wrong: About page (Version:) not reached from Settings", + depth=3, jump_kind="reach", + expect="About page 'Version: 107' appeared and Settings category 'Advanced' left") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 8. HOME -> MORE -> SEARCH (depth 2) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("nav_reach_search",)) +def test_reach_search(): + ok, dest, note = and_reach_from_more("Search", "Name or coordinates", "Import") + ok = ok and bool(find_by_class(dest, "EditText")) + record("nav_reach_search", bool(ok), + "" if ok else (note or "feature_missing: Search fragment (query EditText) not reached"), + depth=2, jump_kind="reach", + expect="Search query field 'Name or coordinates' appeared and more-menu 'Import' left") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 9. HOME -> MORE -> RULER (depth 2) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("nav_reach_ruler",)) +def test_reach_ruler(): + ok, dest, note = and_reach_from_more("Ruler", "0 segments", "Settings") + record("nav_reach_ruler", bool(ok), + "" if ok else (note or "feature_missing: Ruler overlay ('0 segments') not reached"), + depth=2, jump_kind="reach", + expect="Ruler readout '0 segments' appeared and more-menu 'Settings' left") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 10. HOME -> MORE -> CREATE ROUTE (depth 2) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("nav_reach_create_route",)) +def test_reach_create_route(): + ok, dest, note = and_reach_from_more("Create route", "0 legs", "Settings") + record("nav_reach_create_route", bool(ok), + "" if ok else (note or "feature_missing: Create-route editor ('0 legs') not reached"), + depth=2, jump_kind="reach", + expect="Route editor readout '0 legs' appeared and more-menu 'Settings' left") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 11. HOME -> MORE -> ACTIVITY dialog (depth 2) — modal replaces the map surface +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("nav_reach_activity", "nav_reach_activity_vlm")) +def test_reach_activity(): + ok, dest, note = and_reach_from_more("Activity", "Hiking", "Import") + # The Activity radio dialog also carries None / Cycling / Skiing. + ok = ok and find_node(dest, text="None") is not None \ + and find_node(dest, text="Cycling") is not None + record("nav_reach_activity", bool(ok), + "" if ok else (note or "feature_missing: Activity radio dialog not reached"), + depth=2, jump_kind="reach", + expect="Activity dialog options (Hiking/None/Cycling) appeared and more-menu 'Import' left") + + vlm_assert("nav_reach_activity", + "Is a dialog titled 'Activity' showing a vertical list of radio " + "options, exactly one of which has a filled/selected radio button?", + RESULTS_DIR, tag="shape") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 12. MAP long-press -> context menu popup (depth 1) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("nav_reach_map_menu", "nav_reach_map_menu_vlm")) +def test_reach_map_menu(): + home = dismiss_first_run() + if not node_by_id(home, "mapView"): + record("nav_reach_map_menu", False, + "setup_failed: mapView not found on home surface", + depth=1, jump_kind="reach", + expect="map context-menu items appeared on long-press") + else: + before = and_showing() + ok_lp, new_keys = long_press_map() + after = and_showing() + ok = ok_lp and and_reach(before, after, "Add place") \ + and and_reach(before, after, "Navigate here") + if ok: + and_enter("map_menu") + record("nav_reach_map_menu", bool(ok), + "" if ok else "behavior_wrong: long-press map did not open the 4-item context menu", + depth=1, jump_kind="reach", + expect="context-menu items 'Add place' and 'Navigate here' appeared over the map on long-press") + + vlm_assert("nav_reach_map_menu", + "Is a small popup menu of four stacked text options " + "(Share coordinates / Add place / Navigate here / Remember zoom) " + "shown on top of the map?", + RESULTS_DIR, tag="content") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 13. PLACES panel -> coordinate-entry dialog via FAB (depth 2) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("nav_reach_coord_dialog", "nav_reach_coord_dialog_vlm")) +def test_reach_coord_dialog(): + home = dismiss_first_run() + ok_p, panel = and_reach_places_panel(home) + if not ok_p: + record("nav_reach_coord_dialog", False, + "setup_failed: Places panel did not open before the FAB", + depth=2, jump_kind="reach", + expect="coordinate dialog 'Enter coordinates' appeared and the FAB left") + else: + fab = node_by_id(panel, "listActionButton") + if not fab or not is_safe(fab): + record("nav_reach_coord_dialog", False, + "feature_missing: places FAB (listActionButton) absent", + depth=2, jump_kind="reach", + expect="coordinate dialog 'Enter coordinates' appeared and the FAB left") + else: + before = and_showing(panel) + tap_node(fab) + dlg = ui() + ok = and_reach(before, and_showing(dlg), + "Enter coordinates", "listActionButton") \ + and node_by_id(dlg, "coordinatesEdit") is not None + if ok: + and_enter("coord_dialog") + record("nav_reach_coord_dialog", bool(ok), + "" if ok else "behavior_wrong: FAB did not open the 'Enter coordinates' dialog", + depth=2, jump_kind="reach", + expect="dialog title 'Enter coordinates' + coordinatesEdit appeared and the FAB left") + + # The coordinate dialog raises the soft keyboard; focus the field first. + n = ui() + edit = node_by_id(n, "coordinatesEdit") + if edit: + tap_node(edit) + settle("keyboard") + vlm_assert("nav_reach_coord_dialog", + "Is a dialog with a single text input field shown, with the " + "on-screen keyboard raised at the bottom of the screen?", + RESULTS_DIR, tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 14. PLACES panel -> PLACE INFO bottom sheet (depth 2) — list -> detail +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("nav_reach_place_info", "nav_reach_place_info_vlm")) +def test_reach_place_info(): + ensure_one_place() + ok_p, panel = and_reach_places_panel(ui()) + if not ok_p: + record("nav_reach_place_info", False, + "setup_failed: Places panel did not open after creating a place", + depth=2, jump_kind="reach", + expect="place-info sheet source 'My places' appeared and the FAB left") + else: + ok_i, info = and_reach_place_info(panel) + ok_i = ok_i and node_by_id(info, "bottomSheetPanel") is not None \ + and node_by_id(info, "coordinatesRow") is not None + record("nav_reach_place_info", bool(ok_i), + "" if ok_i else "behavior_wrong: tapping a place row did not open the info bottom sheet", + depth=2, jump_kind="reach", + expect="place-info bottomSheetPanel with source 'My places' appeared and the list FAB left") + + vlm_assert("nav_reach_place_info", + "Is a bottom sheet showing place details with a round ORANGE " + "circular action button (a floating action button) at its right edge?", + RESULTS_DIR, tag="color") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 15. PLACE INFO -> EDIT fragment (depth 3) — list -> detail -> edit +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("nav_reach_place_edit",)) +def test_reach_place_edit(): + ensure_one_place() + ok_p, panel = and_reach_places_panel(ui()) + if not ok_p: + record("nav_reach_place_edit", False, + "setup_failed: Places panel did not open", + depth=3, jump_kind="reach", + expect="edit fragment (name EditText + Description field) appeared") + return + ok_i, info = and_reach_place_info(panel) + if not ok_i: + record("nav_reach_place_edit", False, + "setup_failed: place-info sheet did not open before edit", + depth=3, jump_kind="reach", + expect="edit fragment (name EditText + Description field) appeared") + return + ok_e, edit = and_reach_place_edit(info) + ok_e = ok_e and node_by_id(edit, "nameEdit") is not None \ + and bool(find_by_class(edit, "EditText")) + record("nav_reach_place_edit", bool(ok_e), + "" if ok_e else "behavior_wrong: editButton did not open the place-edit fragment", + depth=3, jump_kind="reach", + expect="edit fragment with the Description EditText + nameEdit appeared after editButton") + + +# ══════════════════════════════════════════════════════════════════════════════ +# BACK-STACK INTEGRITY +# ══════════════════════════════════════════════════════════════════════════════ + +# 16. more-menu -> BACK restores the map home (depth 1 -> 0) +@and_test(expects=("nav_back_more_home",)) +def test_back_more_to_home(): + home = dismiss_first_run() + ok_more, panel = and_enter_more(home) + if not ok_more: + record("nav_back_more_home", False, + "setup_failed: more-menu did not open, cannot test its BACK", + depth=1, jump_kind="transition", + expect="more-menu gone and map home restored after one BACK") + return + on_panel = find_node(panel, text="Settings") is not None # more showing + and_back() + after_nodes = ui() + # Popping to a SUBSET surface: no new element appears (the map was always + # present), so assert the more-menu key LEFT and the map home is restored. + ok = on_panel and _gone(after_nodes, "Settings") \ + and node_by_id(after_nodes, "extendPanel") is None \ + and home_ready(after_nodes) + record("nav_back_more_home", bool(ok), + "" if ok else "behavior_wrong: BACK from more-menu did not restore the map home", + depth=1, jump_kind="transition", + expect="more-menu 'Settings' gone, extendPanel gone, mapView + 5 bottom buttons restored after one BACK") + + +# 17. place-info -> BACK restores the Places panel (depth 2 -> 1) +@and_test(expects=("nav_back_info_places",)) +def test_back_info_to_places(): + ensure_one_place() + ok_p, panel = and_reach_places_panel(ui()) + if not ok_p: + record("nav_back_info_places", False, + "setup_failed: Places panel did not open", + depth=2, jump_kind="transition", + expect="place-info sheet gone and Places panel FAB restored after one BACK") + return + ok_i, info = and_reach_place_info(panel) + if not ok_i: + record("nav_back_info_places", False, + "setup_failed: place-info sheet did not open, cannot test its BACK", + depth=2, jump_kind="transition", + expect="place-info sheet gone and Places panel FAB restored after one BACK") + return + before = and_showing(info) # sheet showing ("My places") + and_back() + restored = ui() + # BACK: sheet's 'My places' gone AND the list FAB is back — a genuine reach + # back to the panel (the FAB re-appears where the sheet had hidden it). + ok = and_reach(before, and_showing(restored), "listActionButton", "My places") \ + and find_node(restored, text="Place #1") is not None + record("nav_back_info_places", bool(ok), + "" if ok else "behavior_wrong: BACK from place-info did not restore the Places panel", + depth=1, jump_kind="transition", + expect="place-info 'My places' gone, Places list FAB + place row restored after one BACK") + + +# 18. Settings -> Units -> BACK restores the category list (depth 3 -> 2) +@and_test(expects=("nav_back_units_categories",)) +def test_back_units_to_categories(): + ok_s, s = and_reach_settings() + if not ok_s: + record("nav_back_units_categories", False, + "setup_failed: could not reach Settings", + depth=3, jump_kind="transition", + expect="Units page gone and Settings categories restored after one BACK") + return + ok_u, u = and_reach_units(s) + if not ok_u: + record("nav_back_units_categories", False, + "setup_failed: Units sub-page did not open, cannot test its BACK", + depth=3, jump_kind="transition", + expect="Units page gone and Settings categories restored after one BACK") + return + before = and_showing(u) # Units showing ("Speed") + and_back() + restored = ui() + # BACK: 'Speed' gone AND the categories ('General', 'About') are back — a real + # reach back to the category list (General re-appears where Units had hidden it). + ok = and_reach(before, and_showing(restored), "General", "Speed") \ + and find_node(restored, text="About") is not None + record("nav_back_units_categories", bool(ok), + "" if ok else "behavior_wrong: BACK from Units did not restore the Settings categories", + depth=2, jump_kind="transition", + expect="Units 'Speed' gone, Settings categories 'General'/'About' restored after one BACK") + + +# 19. FULL back-stack unwind: home->more->Settings->Units, then BACK x2 hop-by-hop +@and_test(expects=("nav_backstack_unwind_3hop",)) +def test_backstack_unwind_3hop(): + ok_s, s = and_reach_settings() # depth 2 (more, settings) + ok_u, u = (and_reach_units(s) if ok_s else (False, s)) # depth 3 + if not (ok_s and ok_u): + record("nav_backstack_unwind_3hop", False, + "setup_failed: could not build the home->more->Settings->Units chain", + depth=3, jump_kind="transition", + expect="each BACK pops exactly one surface: Units->categories->map home") + return + # Pop 1: Units -> categories (General re-appears, Speed leaves). + before = and_showing(u) + and_back() + cats = ui() + pop1 = and_reach(before, and_showing(cats), "General", "Speed") \ + and find_node(cats, text="About") is not None + # Pop 2: categories -> map home. The Settings sheet closes back to the map + # (a SUBSET surface — nothing new appears), so assert the categories LEFT and + # the map home is restored, rather than a fake appearing element. + and_back() + h = ui() + pop2 = _gone(h, "General") and node_by_id(h, "contentPanel") is None \ + and home_ready(h) + ok = pop1 and pop2 + record("nav_backstack_unwind_3hop", bool(ok), + "" if ok else "behavior_wrong: BACK did not unwind the chain one surface at a time", + depth=3, jump_kind="transition", + expect="BACK1: Units->categories (Speed gone, General back); BACK2: categories->map home (contentPanel gone)") + + +# 20. panel switch: Places panel -> tap tracksButton -> Tracks panel (depth 1) +@and_test(expects=("nav_switch_places_tracks",)) +def test_switch_places_to_tracks(): + home = dismiss_first_run() + ok_p, panel = and_reach_places_panel(home) + if not ok_p: + record("nav_switch_places_tracks", False, + "setup_failed: Places panel did not open", + depth=1, jump_kind="reach", + expect="Tracks empty-state appeared after tapping tracksButton from Places") + return + tb = node_by_id(panel, "tracksButton") + if not tb: + record("nav_switch_places_tracks", False, + "setup_failed: tracksButton not found on Places panel", + depth=1, jump_kind="reach", + expect="Tracks empty-state appeared after tapping tracksButton from Places") + return + before = and_showing(panel) + tap_node(tb) + tracks = ui() + ok = and_reach(before, and_showing(tracks), + "Your recorded tracks will appear here.") + if ok: + and_enter("tracks_from_places") + record("nav_switch_places_tracks", bool(ok), + "" if ok else "behavior_wrong: tracksButton from the Places panel did not switch to Tracks", + depth=1, jump_kind="reach", + expect="Tracks empty-state 'Your recorded tracks will appear here.' appeared after tracksButton from Places") + + +# 21. HOME -> MORE -> IMPORT launches the system document picker (depth 2) +@and_test(expects=("nav_reach_import_picker",)) +def test_reach_import_picker(): + home = dismiss_first_run() + ok_more, panel = and_enter_more(home) + if not ok_more: + record("nav_reach_import_picker", False, + "setup_failed: more-menu did not open before Import", + depth=2, jump_kind="reach", + expect="a document picker (non-Trekarta package) came to the foreground after Import") + return + row = find_node(panel, text="Import") + if not row: + record("nav_reach_import_picker", False, + "feature_missing: Import row absent on more-menu", + depth=2, jump_kind="reach", + expect="a document picker (non-Trekarta package) came to the foreground after Import") + return + tap_node(row) + settle("tap") + settle("tap") + # The SAF picker is a DIFFERENT app; Trekarta leaves the foreground. That is + # the reach proof (a system-picker activity is now resumed, not mobi.maptrek). + fg = get_current_activity() + left_app = PACKAGE not in fg and fg != "" + if left_app: + and_enter("import_picker") + record("nav_reach_import_picker", bool(left_app), + "" if left_app else f"behavior_wrong: Import did not launch an external picker (fg={fg})", + depth=2, jump_kind="reach", + expect="external document-picker activity resumed (foreground left the app under test) after Import") + # Return to our app for hygiene (does not affect the record). + back() + settle("tap") + + +# 22. HOME -> MORE -> MANAGE MAPS reaches the maps-management surface (depth 2) +@and_test(expects=("nav_reach_manage_maps",)) +def test_reach_manage_maps(): + # "Manage maps" opens a maps-management surface ("N items selected"), launched + # from the more-menu. more items leave -> the selection readout appears. + ok, dest, note = and_reach_from_more("Manage maps", "items selected", "Settings") + ok = ok and node_by_id(dest, "contentPanel") is not None + record("nav_reach_manage_maps", bool(ok), + "" if ok else (note or "feature_missing: Manage maps surface not reached"), + depth=2, jump_kind="reach", + expect="Manage-maps readout '0 items selected' appeared and more-menu 'Settings' left") + + +TESTS = [ + test_reach_more, + test_reach_places, + test_reach_tracks, + test_reach_maps, + test_reach_settings, + test_reach_units, + test_reach_about, + test_reach_search, + test_reach_ruler, + test_reach_create_route, + test_reach_activity, + test_reach_map_menu, + test_reach_coord_dialog, + test_reach_place_info, + test_reach_place_edit, + test_back_more_to_home, + test_back_info_to_places, + test_back_units_to_categories, + test_backstack_unwind_3hop, + test_switch_places_to_tracks, + test_reach_import_picker, + test_reach_manage_maps, +] + + +if __name__ == "__main__": + run_suite(TESTS, "navigation") diff --git a/android/andreynovikov-trekarta/tests/test_android_states.py b/android/andreynovikov-trekarta/tests/test_android_states.py new file mode 100644 index 0000000000000000000000000000000000000000..b02ac86442303b26cb3698ea9bc6684447707349 --- /dev/null +++ b/android/andreynovikov-trekarta/tests/test_android_states.py @@ -0,0 +1,820 @@ +#!/usr/bin/env python3 +"""STATES lane — Trekarta (mobi.maptrek). + +Widget state transitions PAIRED with their app-authored consequence, page-level +state machines (track recording), conditional controls, and SETTINGS/mode +PERSISTENCE across process death. Sole owner of CHECKED / SELECTED / FOCUS. + +Every observation below was verified against the RUNNING original before being +asserted. Package comes from sys.argv[1]; never a literal. +""" +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 + + +# ── Shared helpers ────────────────────────────────────────────────────────── +def dismiss_first_run(): + """EVERY test starts here: relaunch and clear the recurring first-run + 'download world map' AlertDialog (SKIP == android:id/button2). Never tap + DOWNLOAD (network).""" + restart_app() + wait_for_foreground() + _wait_home_ready() + n = ui() + b = find_node(n, text="SKIP") or node_by_id(n, "button2") + if b: + tap_node(b) + settle("tap") + + +def _wait_home_ready(timeout=12): + """Block past the Trekarta splash: wait_for_foreground() returns while the + logo is up and uiautomator then hands back a STALE tree. Poll until the + bottom-bar placesButton or the first-run dialog button2 is present.""" + import time as _t + deadline = _t.time() + timeout + while _t.time() < deadline: + n = ui() + if (node_by_id(n, "placesButton") is not None + or node_by_id(n, "button2") is not None): + return n + settle("key") + return ui() + + +def open_more(): + """Open the more-menu extendPanel. Returns the fresh tree (may be empty on + failure).""" + tap_node(node_by_id(ui(), "moreButton")) + settle("tap") + return ui() + + +def and_enter_settings(): + """Depth surface 1: more-menu -> Settings categories bottom-sheet.""" + nodes = open_more() + s = find_node(nodes, text="Settings") or find_node_ci(nodes, "Settings") + if not s or not tap_node(s): + return False + settle("tap") + and_enter("settings") + return find_node(ui(), text="Units") is not None or find_node(ui(), text="General") is not None + + +def and_reach_units(): + """Depth surface 2: Settings -> Units sub-page (rows Speed/Distance/...). + Backs a declared depth==2 for every unit-preference test.""" + if not and_enter_settings(): + return False + u = find_node(ui(), text="Units") or find_node_ci(ui(), "Units") + if not u or not tap_node(u): + return False + settle("tap") + and_enter("units") + return find_node(ui(), text="Speed") is not None + + +def summary_of(nodes, title): + """The `android:id/summary` text of the preference row whose + `android:id/title` == title (matched by x-alignment + y-below).""" + trow = None + for n in nodes: + if n.get("resource-id", "").rsplit("/", 1)[-1] == "title" and n.get("text", "") == title: + trow = n + break + if not trow or "_bounds" not in trow: + return None + tb = trow["_bounds"] + for n in nodes: + if n.get("resource-id", "").rsplit("/", 1)[-1] == "summary": + sb = n.get("_bounds") + if sb and abs(sb[0] - tb[0]) < 40 and sb[1] >= tb[1]: + return n.get("text", "") + return None + + +def checked_option(nodes): + """The text of the currently-checked CheckedTextView in a choice dialog.""" + for n in nodes: + if n.get("resource-id", "").rsplit("/", 1)[-1] == "text1" and n.get("checked") == "true": + return n.get("text", "") + return None + + +def clear_transient_dialogs(rounds=8): + """After starting a background service the app chains: location permission, + a notification-permission app dialog (GRANT), the system notification dialog + (Allow), and sometimes the first-run map dialog again. Grant/dismiss each in + order until the map is clear. All buttons here are non-destructive.""" + for _ in range(rounds): + nodes = ui() + b = None + for label in ("While using the app", "Only this time", "Allow", + "GRANT", "SKIP", "Got it"): + b = find_node(nodes, text=label) + if b: + break + if not b: + return + tap_node(b) + settle("tap") + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1) SETTINGS PERSISTENCE — the highest-value states here (an in-memory +# recreation fails these). Each is its own transition + a process-death probe. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_distance_unit_transition",)) +def test_distance_unit_transition(): + """Distance list-preference: pick a DIFFERENT option -> the Units summary + changes to that option (the app-authored consequence of the choice).""" + dismiss_first_run() + if not and_reach_units(): + record("states_distance_unit_transition", False, + "setup_failed: could not reach Units sub-page", + depth=2, jump_kind="transition", + expect="Distance summary changes to a newly-selected option") + return + nodes = ui() + before = summary_of(nodes, "Distance") + row = find_node(nodes, text="Distance") + if before is None or row is None: + record("states_distance_unit_transition", False, + "feature_missing: no 'Distance' unit row/summary", + depth=2, jump_kind="transition", + expect="Distance summary changes to a newly-selected option") + return + tap_node(row) + settle("tap") + dlg = ui() + # pick an option different from the current checked one + cur = checked_option(dlg) + target = None + for opt in ("kilometers/meters", "miles/yards", "miles/feet", "nautical miles"): + n = find_node(dlg, text=opt) + if n and opt != cur: + target = n + break + if target is None: + record("states_distance_unit_transition", False, + "setup_failed: Distance choice dialog had no alternate option", + depth=2, jump_kind="transition", + expect="Distance summary changes to a newly-selected option") + return + chosen = target.get("text", "") + tap_node(target) + settle("tap") + after = summary_of(ui(), "Distance") + ok = after == chosen and after != before + record("states_distance_unit_transition", ok, + "" if ok else f"behavior_wrong: summary {before!r}->{after!r}, expected {chosen!r}", + depth=2, jump_kind="transition", + expect=f"Distance summary '{before}' -> '{chosen}'") + + +@and_test(expects=("states_distance_unit_persists",)) +def test_distance_unit_persists(): + """Set Distance to a chosen non-default option, kill the process, relaunch, + re-navigate to Units, assert the summary SURVIVED (SharedPreferences).""" + dismiss_first_run() + if not and_reach_units(): + record("states_distance_unit_persists", False, + "setup_failed: could not reach Units sub-page", + depth=2, jump_kind="transition", + expect="Distance summary persists across process death") + return + nodes = ui() + before = summary_of(nodes, "Distance") + tap_node(find_node(nodes, text="Distance")) + settle("tap") + dlg = ui() + cur = checked_option(dlg) + target = None + for opt in ("kilometers/meters", "miles/yards", "nautical miles", "miles/feet"): + n = find_node(dlg, text=opt) + if n and opt != cur: + target = n + break + if target is None: + record("states_distance_unit_persists", False, + "setup_failed: no alternate Distance option to select", + depth=2, jump_kind="transition", + expect="Distance summary persists across process death") + return + chosen = target.get("text", "") + tap_node(target) + settle("tap") + if summary_of(ui(), "Distance") != chosen: + record("states_distance_unit_persists", False, + f"behavior_wrong: summary did not update to {chosen!r} before restart", + depth=2, jump_kind="transition", + expect="Distance summary persists across process death") + return + # process death + relaunch, then re-navigate + force_stop_and_relaunch() + wait_for_foreground() + b = find_node(ui(), text="SKIP") or node_by_id(ui(), "button2") + if b: + tap_node(b) + settle("tap") + if not and_reach_units(): + record("states_distance_unit_persists", False, + "setup_failed: could not re-reach Units after relaunch", + depth=2, jump_kind="transition", + expect="Distance summary persists across process death") + return + after = summary_of(ui(), "Distance") + ok = after == chosen + record("states_distance_unit_persists", ok, + "" if ok else f"behavior_wrong: after relaunch summary is {after!r}, not {chosen!r}", + depth=2, jump_kind="value", + expect=f"{chosen}") + + +@and_test(expects=("states_speed_unit_transition",)) +def test_speed_unit_transition(): + """Speed list-preference: pick a different option -> Speed summary changes.""" + dismiss_first_run() + if not and_reach_units(): + record("states_speed_unit_transition", False, + "setup_failed: could not reach Units sub-page", + depth=2, jump_kind="transition", + expect="Speed summary changes to a newly-selected option") + return + nodes = ui() + before = summary_of(nodes, "Speed") + row = find_node(nodes, text="Speed") + if before is None or row is None: + record("states_speed_unit_transition", False, + "feature_missing: no 'Speed' unit row/summary", + depth=2, jump_kind="transition", + expect="Speed summary changes to a newly-selected option") + return + tap_node(row) + settle("tap") + dlg = ui() + cur = checked_option(dlg) + target = None + for opt in ("kilometers per hour", "knots", "meters per second", "miles per hour"): + n = find_node(dlg, text=opt) + if n and opt != cur: + target = n + break + if target is None: + record("states_speed_unit_transition", False, + "setup_failed: Speed choice dialog had no alternate option", + depth=2, jump_kind="transition", + expect="Speed summary changes to a newly-selected option") + return + chosen = target.get("text", "") + tap_node(target) + settle("tap") + after = summary_of(ui(), "Speed") + ok = after == chosen and after != before + record("states_speed_unit_transition", ok, + "" if ok else f"behavior_wrong: summary {before!r}->{after!r}, expected {chosen!r}", + depth=2, jump_kind="transition", + expect=f"Speed summary '{before}' -> '{chosen}'") + + +@and_test(expects=("states_speed_unit_persists",)) +def test_speed_unit_persists(): + """Speed choice survives process death (SharedPreferences).""" + dismiss_first_run() + if not and_reach_units(): + record("states_speed_unit_persists", False, + "setup_failed: could not reach Units sub-page", + depth=2, jump_kind="transition", + expect="Speed summary persists across process death") + return + tap_node(find_node(ui(), text="Speed")) + settle("tap") + dlg = ui() + cur = checked_option(dlg) + target = None + for opt in ("knots", "meters per second", "kilometers per hour", "miles per hour"): + n = find_node(dlg, text=opt) + if n and opt != cur: + target = n + break + if target is None: + record("states_speed_unit_persists", False, + "setup_failed: no alternate Speed option to select", + depth=2, jump_kind="transition", + expect="Speed summary persists across process death") + return + chosen = target.get("text", "") + tap_node(target) + settle("tap") + if summary_of(ui(), "Speed") != chosen: + record("states_speed_unit_persists", False, + f"behavior_wrong: summary did not update to {chosen!r} before restart", + depth=2, jump_kind="transition", + expect="Speed summary persists across process death") + return + force_stop_and_relaunch() + wait_for_foreground() + b = find_node(ui(), text="SKIP") or node_by_id(ui(), "button2") + if b: + tap_node(b) + settle("tap") + if not and_reach_units(): + record("states_speed_unit_persists", False, + "setup_failed: could not re-reach Units after relaunch", + depth=2, jump_kind="transition", + expect="Speed summary persists across process death") + return + after = summary_of(ui(), "Speed") + ok = after == chosen + record("states_speed_unit_persists", ok, + "" if ok else f"behavior_wrong: after relaunch summary is {after!r}, not {chosen!r}", + depth=2, jump_kind="value", + expect=f"{chosen}") + + +@and_test(expects=("states_elevation_unit_persists",)) +def test_elevation_unit_persists(): + """Elevation is a two-option list-pref (meters/feet). Flip to the other + option, confirm the summary changed, kill the process and assert it stuck.""" + dismiss_first_run() + if not and_reach_units(): + record("states_elevation_unit_persists", False, + "setup_failed: could not reach Units sub-page", + depth=2, jump_kind="transition", + expect="Elevation summary persists across process death") + return + before = summary_of(ui(), "Elevation") + row = find_node(ui(), text="Elevation") + if before is None or row is None: + record("states_elevation_unit_persists", False, + "feature_missing: no 'Elevation' unit row/summary", + depth=2, jump_kind="transition", + expect="Elevation summary persists across process death") + return + tap_node(row) + settle("tap") + dlg = ui() + cur = checked_option(dlg) + target = None + for opt in ("meters", "feet"): + n = find_node(dlg, text=opt) + if n and opt != cur: + target = n + break + if target is None: + record("states_elevation_unit_persists", False, + "setup_failed: Elevation dialog had no alternate option", + depth=2, jump_kind="transition", + expect="Elevation summary persists across process death") + return + chosen = target.get("text", "") + tap_node(target) + settle("tap") + if summary_of(ui(), "Elevation") != chosen: + record("states_elevation_unit_persists", False, + f"behavior_wrong: summary did not update to {chosen!r} before restart", + depth=2, jump_kind="transition", + expect="Elevation summary persists across process death") + return + force_stop_and_relaunch() + wait_for_foreground() + b = find_node(ui(), text="SKIP") or node_by_id(ui(), "button2") + if b: + tap_node(b) + settle("tap") + if not and_reach_units(): + record("states_elevation_unit_persists", False, + "setup_failed: could not re-reach Units after relaunch", + depth=2, jump_kind="transition", + expect="Elevation summary persists across process death") + return + after = summary_of(ui(), "Elevation") + ok = after == chosen + record("states_elevation_unit_persists", ok, + "" if ok else f"behavior_wrong: after relaunch summary is {after!r}, not {chosen!r}", + depth=2, jump_kind="value", + expect=f"{chosen}") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2) SWITCH (CHECKED) transitions — I own `checked`. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_extra_precision_toggle",)) +def test_extra_precision_toggle(): + """Extra precision Switch (`switchWidget`) on the Units sheet: checked flips + false->true AND the Units sheet stays open (the row is an in-place toggle, + unlike the more-menu Fullscreen switch which closes its panel).""" + dismiss_first_run() + if not and_reach_units(): + record("states_extra_precision_toggle", False, + "setup_failed: could not reach Units sub-page", + depth=2, jump_kind="transition", + expect="Extra precision checked false->true; Units sheet stays open") + return + nodes = ui() + sw = node_by_id(nodes, "switchWidget") + if sw is None: + record("states_extra_precision_toggle", False, + "feature_missing: no 'Extra precision' switchWidget", + depth=2, jump_kind="transition", + expect="Extra precision checked false->true; Units sheet stays open") + return + before = sw.get("checked") + tap_node(sw) + settle("tap") + fresh = ui() + sw2 = node_by_id(fresh, "switchWidget") or find_closest_match(fresh, sw) + after = sw2.get("checked") if sw2 else None + sheet_open = find_node(fresh, text="Speed") is not None + ok = after is not None and after != before and sheet_open + record("states_extra_precision_toggle", ok, + "" if ok else f"behavior_wrong: checked {before!r}->{after!r}, sheet_open={sheet_open}", + depth=2, jump_kind="transition", + expect=f"Extra precision checked {before}->{'true' if before=='false' else 'false'}; Units sheet still shown") + + +@and_test(expects=("states_extra_precision_persists",)) +def test_extra_precision_persists(): + """Flip Extra precision, kill the process, re-navigate and assert the new + checked-state SURVIVED (a CHECKED persistence probe).""" + dismiss_first_run() + if not and_reach_units(): + record("states_extra_precision_persists", False, + "setup_failed: could not reach Units sub-page", + depth=2, jump_kind="transition", + expect="Extra precision checked-state persists across process death") + return + sw = node_by_id(ui(), "switchWidget") + if sw is None: + record("states_extra_precision_persists", False, + "feature_missing: no 'Extra precision' switchWidget", + depth=2, jump_kind="transition", + expect="Extra precision checked-state persists across process death") + return + before = sw.get("checked") + tap_node(sw) + settle("tap") + sw2 = node_by_id(ui(), "switchWidget") + flipped = sw2.get("checked") if sw2 else None + if flipped is None or flipped == before: + record("states_extra_precision_persists", False, + f"behavior_wrong: switch did not flip before restart ({before!r}->{flipped!r})", + depth=2, jump_kind="transition", + expect="Extra precision checked-state persists across process death") + return + force_stop_and_relaunch() + wait_for_foreground() + b = find_node(ui(), text="SKIP") or node_by_id(ui(), "button2") + if b: + tap_node(b) + settle("tap") + if not and_reach_units(): + record("states_extra_precision_persists", False, + "setup_failed: could not re-reach Units after relaunch", + depth=2, jump_kind="transition", + expect="Extra precision checked-state persists across process death") + return + sw3 = node_by_id(ui(), "switchWidget") + after = sw3.get("checked") if sw3 else None + ok = after == flipped + record("states_extra_precision_persists", ok, + "" if ok else f"behavior_wrong: after relaunch checked is {after!r}, not {flipped!r}", + depth=2, jump_kind="value", + expect=f"checked={flipped}") + + +@and_test(expects=("states_fullscreen_toggle", "states_fullscreen_toggle_vlm")) +def test_fullscreen_toggle(): + """More-menu Fullscreen Switch (`check`): checked is false; tapping enters + immersive fullscreen. The app-authored consequence is the system immersive + cling ('Viewing full screen', android:id/immersive_cling_title) appearing AND + the status bar disappearing (VLM). Reset via clear_data at the next test.""" + dismiss_first_run() + nodes = open_more() + sw = node_by_id(nodes, "check") + if sw is None: + record("states_fullscreen_toggle", False, + "feature_missing: no Fullscreen 'check' switch in more-menu", + depth=1, jump_kind="transition", + expect="Fullscreen checked false->on; immersive cling appears") + vlm_assert("states_fullscreen_toggle", + "Is the top system status bar (clock, wifi, battery icons) hidden, " + "with the app content extending to the very top edge of the screen?", + RESULTS_DIR, jump_kind="transition", depth=1, tag="layout") + return + before = sw.get("checked") + and_enter("more") + tap_node(sw) # tapping toggles fullscreen AND closes the more-menu + settle("tap") + settle("tap") + fresh = ui() + cling = (node_by_id(fresh, "immersive_cling_title") + or node_by_id(fresh, "immersive_cling_icon") + or find_node_ci(fresh, "Viewing full screen")) + ok = before == "false" and cling is not None + record("states_fullscreen_toggle", ok, + "" if ok else (f"behavior_wrong: switch was {before!r} and immersive cling " + f"{'present' if cling else 'absent'} after toggle"), + depth=1, jump_kind="transition", + expect="Fullscreen checked false->on; system immersive cling 'Viewing full screen' appears") + vlm_assert("states_fullscreen_toggle", + "Is the top system status bar (clock, wifi and battery icons) hidden, " + "with the app/map content extending all the way to the very top edge " + "of the screen (fullscreen immersive mode)?", + RESULTS_DIR, jump_kind="transition", depth=1, tag="layout") + # leave fullscreen so it does not corrupt later dumps + clear_data() + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3) Location follow — active mode + gaugePanel consequence (dump-readable), +# plus the orange button and recentred map (VLM). +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_location_follow_gauge", + "states_location_follow_gauge_vlm", + "states_location_recenter_vlm")) +def test_location_follow_gauge(): + """Tapping locationButton enters follow mode; the app-authored consequence + is the gaugePanel (gaugeValue + gaugeUnit) APPEARING bottom/top-left. That is + dump-readable. The active-orange button colour and the recentred map with the + location cursor are canvas/colour visuals -> VLM. (locationButton.selected + stays 'false' in the tree, so the gaugePanel appearing is the rule signal.)""" + dismiss_first_run() + nodes = ui() + lb = node_by_id(nodes, "locationButton") + if lb is None: + record("states_location_follow_gauge", False, + "feature_missing: no locationButton", + depth=0, jump_kind="transition", + expect="gaugePanel absent->present after tapping locationButton") + vlm_assert("states_location_follow_gauge", + "Is the leftmost bottom navigation button highlighted in orange?", + RESULTS_DIR, jump_kind="transition", depth=0, tag="color") + vlm_assert("states_location_recenter", + "Is a red arrow-shaped location cursor drawn on the map?", + RESULTS_DIR, jump_kind="transition", depth=0, tag="position") + return + gauge_before = node_by_id(nodes, "gaugePanel") is not None + tap_node(lb) + settle("tap") + settle("tap") + # location permission may prompt after clear_data; grant via GUI if shown + fresh = ui() + allow = find_node(fresh, text="While using the app") or find_node(fresh, text="Only this time") + if allow: + tap_node(allow) + settle("tap") + settle("tap") + fresh = ui() + gp = node_by_id(fresh, "gaugePanel") + gu = node_by_id(fresh, "gaugeUnit") + gauge_after = gp is not None or gu is not None + ok = (not gauge_before) and gauge_after + record("states_location_follow_gauge", ok, + "" if ok else (f"behavior_wrong: gaugePanel before={gauge_before} after={gauge_after}"), + depth=0, jump_kind="transition", + expect="gaugePanel absent->present (with gaugeValue/gaugeUnit) after entering follow mode") + vlm_assert("states_location_follow_gauge", + "Look at the row of navigation buttons at the bottom. Is the leftmost " + "button (a navigation arrow) highlighted in a bright orange/red accent " + "colour, distinctly different from the other grey buttons?", + RESULTS_DIR, jump_kind="transition", depth=0, tag="color") + vlm_assert("states_location_recenter", + "Is there a solid RED arrow-shaped location/heading cursor drawn on the " + "map, indicating the current GPS position?", + RESULTS_DIR, jump_kind="transition", depth=0, tag="position") + # toggle follow off (tap until gaugePanel gone) so later tests start clean + for _ in range(3): + cur = ui() + if node_by_id(cur, "gaugePanel") is None: + break + b = node_by_id(cur, "locationButton") + if not b or not tap_node(b): + break + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4) Track recording STATE MACHINE — idle -> recording -> paused. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_track_recording_start", + "states_track_recording_start_vlm")) +def test_track_recording_start(): + """Tracks panel Record FAB (`listActionButton`): idle (no current track, no + pause/stop) -> recording. The app-authored consequence is a 'Current track' + row plus `pause_action` + `stop_action` controls appearing. The recording + also lights the tracksButton orange (VLM colour). Cleans up by stopping.""" + dismiss_first_run() + nodes = ui() + if not tap_node(node_by_id(nodes, "tracksButton")): + record("states_track_recording_start", False, + "setup_failed: no tracksButton", + depth=1, jump_kind="transition", + expect="idle->recording: Current track row + pause_action + stop_action appear") + vlm_assert("states_track_recording_start", + "Is the second bottom button (a squiggle/track icon) highlighted orange?", + RESULTS_DIR, jump_kind="transition", depth=1, tag="color") + return + settle("tap") + and_enter("tracks_panel") + nodes = ui() + fab = node_by_id(nodes, "listActionButton") + rec_before = node_by_id(nodes, "pause_action") is not None + if fab is None: + record("states_track_recording_start", False, + "feature_missing: no record FAB (listActionButton) in Tracks panel", + depth=1, jump_kind="transition", + expect="idle->recording: Current track row + pause_action + stop_action appear") + vlm_assert("states_track_recording_start", + "Is the second bottom button (a squiggle/track icon) highlighted orange?", + RESULTS_DIR, jump_kind="transition", depth=1, tag="color") + return + tap_node(fab) + settle("tap") + settle("tap") + clear_transient_dialogs() # location + notification perms, first-run + fresh = ui() + # the Tracks panel is normally still showing recording controls; if it closed, + # re-open it (only if pause_action is not already present). + if node_by_id(fresh, "pause_action") is None: + tap_node(node_by_id(fresh, "tracksButton")) + settle("tap") + fresh = ui() + current = find_node(fresh, text="Current track") is not None + pause = node_by_id(fresh, "pause_action") is not None + stop = node_by_id(fresh, "stop_action") is not None + ok = (not rec_before) and current and pause and stop + record("states_track_recording_start", ok, + "" if ok else (f"behavior_wrong: current_track={current} pause={pause} " + f"stop={stop} (before recording?={rec_before})"), + depth=1, jump_kind="transition", + expect="idle->recording: 'Current track' row + pause_action + stop_action controls appear") + vlm_assert("states_track_recording_start", + "Look at the bottom navigation buttons. Is the second button (a " + "squiggle/track-shaped icon) highlighted in a bright orange/red accent " + "colour, indicating active track recording?", + RESULTS_DIR, jump_kind="transition", depth=1, tag="color") + # cleanup: stop recording (0 m tracked -> discarded, no save dialog) + st = node_by_id(ui(), "stop_action") + if st: + tap_node(st) + settle("tap") + c = find_node(ui(), text="CANCEL") + if c: + tap_node(c) + settle("tap") + + +@and_test(expects=("states_track_recording_pause",)) +def test_track_recording_pause(): + """Recording sub-state: tapping `pause_action` -> `resume_action` appears and + `pause_action` disappears (a paused transition). Verified reversible.""" + dismiss_first_run() + nodes = ui() + if not tap_node(node_by_id(nodes, "tracksButton")): + record("states_track_recording_pause", False, + "setup_failed: no tracksButton", + depth=1, jump_kind="transition", + expect="pause_action present->replaced by resume_action") + return + settle("tap") + and_enter("tracks_panel") + fab = node_by_id(ui(), "listActionButton") + if fab is None: + record("states_track_recording_pause", False, + "feature_missing: no record FAB in Tracks panel", + depth=1, jump_kind="transition", + expect="pause_action present->replaced by resume_action") + return + tap_node(fab) + settle("tap") + settle("tap") + clear_transient_dialogs() + fresh = ui() + if node_by_id(fresh, "pause_action") is None: + tap_node(node_by_id(fresh, "tracksButton")) + settle("tap") + fresh = ui() + pa = node_by_id(fresh, "pause_action") + if pa is None: + record("states_track_recording_pause", False, + "setup_failed: recording did not start (no pause_action)", + depth=1, jump_kind="transition", + expect="pause_action present->replaced by resume_action") + return + tap_node(pa) + settle("tap") + paused = ui() + resume = node_by_id(paused, "resume_action") is not None + pause_gone = node_by_id(paused, "pause_action") is None + ok = resume and pause_gone + record("states_track_recording_pause", ok, + "" if ok else f"behavior_wrong: after pause resume_action={resume} pause_gone={pause_gone}", + depth=1, jump_kind="transition", + expect="paused: resume_action present, pause_action gone") + # cleanup: stop the (paused) recording + st = node_by_id(ui(), "stop_action") + if st: + tap_node(st) + settle("tap") + c = find_node(ui(), text="CANCEL") + if c: + tap_node(c) + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5) Activity radio selection — I own `selected`/`checked`. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_activity_radio_select", + "states_activity_radio_select_vlm")) +def test_activity_radio_select(): + """More-menu Activity opens a single-choice dialog (None default checked / + Hiking / Cycling / Skiing). Selecting a different option flips which radio is + checked (dump-readable). The selected radio's orange fill is a colour visual + -> VLM. Re-opening the dialog confirms the new checked state persisted.""" + dismiss_first_run() + nodes = open_more() + act = find_node(nodes, text="Activity") or find_node_ci(nodes, "Activity") + if act is None: + record("states_activity_radio_select", False, + "feature_missing: no 'Activity' entry in more-menu", + depth=1, jump_kind="transition", + expect="Activity checked radio None->a different option") + vlm_assert("states_activity_radio_select", + "Is exactly one radio button filled with an orange accent colour?", + RESULTS_DIR, jump_kind="transition", depth=1, tag="color") + return + tap_node(act) + settle("tap") + and_enter("activity_dialog") + dlg = ui() + before = checked_option(dlg) + target = None + for opt in ("Hiking", "Cycling", "Skiing", "None"): + n = find_node(dlg, text=opt) + if n and opt != before: + target = n + break + if target is None: + record("states_activity_radio_select", False, + "setup_failed: Activity dialog had no alternate option", + depth=1, jump_kind="transition", + expect="Activity checked radio None->a different option") + vlm_assert("states_activity_radio_select", + "Is exactly one radio button filled with an orange accent colour?", + RESULTS_DIR, jump_kind="transition", depth=1, tag="color") + return + chosen = target.get("text", "") + tap_node(target) # single-choice: selects and dismisses the dialog + settle("tap") + # re-open the dialog and read which option is now checked + nodes = open_more() + tap_node(find_node(nodes, text="Activity")) + settle("tap") + dlg2 = ui() + now = checked_option(dlg2) + ok = now == chosen and now != before + record("states_activity_radio_select", ok, + "" if ok else f"behavior_wrong: checked radio {before!r}->{now!r}, expected {chosen!r}", + depth=1, jump_kind="value", + expect=f"{chosen} selected") + vlm_assert("states_activity_radio_select", + "Look at the 'Activity' dialog radio list. Is exactly ONE radio button " + "filled/dotted with a bright orange accent colour while the others are " + "empty grey circles?", + RESULTS_DIR, jump_kind="value", depth=1, tag="color") + # dismiss the reopened dialog without changing the selection + back() + settle("tap") + + +# ── Registry ──────────────────────────────────────────────────────────────── +TESTS = [ + test_distance_unit_transition, + test_distance_unit_persists, + test_speed_unit_transition, + test_speed_unit_persists, + test_elevation_unit_persists, + test_extra_precision_toggle, + test_extra_precision_persists, + test_fullscreen_toggle, + test_location_follow_gauge, + test_track_recording_start, + test_track_recording_pause, + test_activity_radio_select, +] + + +if __name__ == "__main__": + if not device_online(): + print("device offline — cannot run states suite") + sys.exit(1) + run_suite(TESTS, "states") diff --git a/android/andreynovikov-trekarta/tests/test_android_structure.py b/android/andreynovikov-trekarta/tests/test_android_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..8dbde786e36c07177d5307462883d71d26ab4ac3 --- /dev/null +++ b/android/andreynovikov-trekarta/tests/test_android_structure.py @@ -0,0 +1,436 @@ +#!/usr/bin/env python3 +"""STRUCTURE module for Trekarta (mobi.maptrek). + +Lane: the launch GATE (top-level surface exists) + tree-SHAPE deltas (a panel / +dialog / sheet / context-menu opening or closing changes the view tree's SHAPE). +SHAPE ONLY — specific text, checked/selected state, reachability of a named +screen, and CRUD all belong to other lanes and are ceded. + +Every test owns its entry point via dismiss_first_run() (the base-map download +AlertDialog reappears on EVERY launch and must be SKIPped first; never DOWNLOAD). +""" +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403 + + +# ── App-specific entry point ───────────────────────────────────────────────── +def dismiss_first_run(): + """Launch fresh, wait for the real home (past the splash), and SKIP the + recurring base-map dialog. Returns the settled home tree (post-SKIP) so + callers can assert on it.""" + restart_app() + wait_for_foreground() + _wait_home_ready() + n = ui() + b = find_node(n, text="SKIP") or node_by_id(n, "button2") + if b: + tap_node(b) + settle("tap") + return ui() + + +HOME_BUTTONS = ("locationButton", "tracksButton", "placesButton", + "mapsButton", "moreButton") + + +def home_ready(nodes): + """True iff the map surface is present: mapView + all 5 bottom buttons.""" + if not node_by_id(nodes, "mapView"): + return False + return all(node_by_id(nodes, b) for b in HOME_BUTTONS) + + +def _wait_home_ready(timeout=12): + """Block past the Trekarta splash: wait_for_foreground() returns while the + logo is still up (the process IS foreground) and uiautomator then hands back + a STALE tree. Poll until home_ready() (map + 5 buttons) OR the first-run + dialog's button2 is present, so the first real ui() is the settled surface.""" + import time as _t + deadline = _t.time() + timeout + while _t.time() < deadline: + n = ui() + if home_ready(n) or node_by_id(n, "button2") is not None: + return n + settle("key") + return ui() + + +def long_press_map(): + """Genuine long-press at the map centre until the context menu opens. + + The kit's long_press is a ZERO-distance swipe, which this map's custom + android.view.View silently ignores, and even a small hold registers only + intermittently — so retry with an increasing duration until the SURFACE + changes. Coordinates are DERIVED from screen geometry, never pixel literals. + Returns (ok, new_surface_keys).""" + s = get_screen_info() + x, y = s["center_x"], s["center_y"] + dx = max(2, s["width"] // 500) # a few px, density-independent + before = and_showing() + for i in range(4): + adb_shell("input", "swipe", int(x), int(y), + int(x + dx), int(y + dx), 1200 + i * 400) + settle("tap") + after = and_showing() + if surface_changed(before, after, min_delta=3): + return True, (after - before) + return False, set() + + +# ── depth>=1 helpers (back a declared depth with a real navigation call) ────── +def and_enter_panel(nodes, rid): + """Tap a bottom-bar button by id, settle, and count one surface. Returns + (ok, after_nodes). Only counts depth when the tree actually changed shape.""" + btn = node_by_id(nodes, rid) + if not btn: + return False, nodes + before = and_showing(nodes) + if not tap_node(btn): + return False, nodes + after_nodes = ui() + if not surface_changed(before, and_showing(after_nodes)): + return False, after_nodes + and_enter(rid) + return True, after_nodes + + +def and_enter_more(nodes): + return and_enter_panel(nodes, "moreButton") + + +def and_enter_settings(): + """Home -> more -> Settings. Crosses two surfaces (extendPanel, then the + Settings bottom sheet). Returns (ok, after_nodes).""" + home = dismiss_first_run() + ok, panel = and_enter_more(home) + if not ok: + return False, panel + row = find_node(panel, text="Settings") or find_node_ci(panel, "Settings") + if not row: + return False, panel + before = and_showing(panel) + if not tap_node(row): + return False, panel + after = ui() + if not surface_changed(before, and_showing(after)): + return False, after + and_enter("settings") + return True, after + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1. LAUNCH GATE (the one existence test) — depth 0, jump_kind=none +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("structure_gate_launch", "structure_gate_launch_vlm")) +def test_gate_launch(): + if not device_online(): + record("structure_gate_launch", False, + "setup_failed: device offline / adb tunnel down", + depth=0, jump_kind="none") + return + nodes = dismiss_first_run() + fg = wait_for_foreground() + has_map = node_by_id(nodes, "mapView") is not None + present = [b for b in HOME_BUTTONS if node_by_id(nodes, b)] + ok = fg and has_map and len(present) == len(HOME_BUTTONS) + missing = [b for b in HOME_BUTTONS if b not in present] + if ok: + msg = "" + elif not fg: + msg = "setup_failed: app did not reach the foreground" + elif not has_map: + msg = "feature_missing: mapView absent on home surface" + else: + msg = f"feature_missing: bottom-bar buttons missing {missing}" + record("structure_gate_launch", bool(ok), msg, depth=0, jump_kind="none") + + # VLM: the bottom action bar renders a ROW of 5 distinct icons. + vlm_assert("structure_gate_launch", + "Is there a horizontal row of exactly 5 evenly spaced icon " + "buttons across the very bottom edge of the screen?", + RESULTS_DIR, tag="shape") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2. MORE menu — extendPanel appears (depth 1) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("structure_more_panel", "structure_more_panel_vlm")) +def test_more_panel_shape(): + home = dismiss_first_run() + before = and_showing(home) + ok, after_nodes = and_enter_more(home) + after = and_showing(after_nodes) + panel = node_by_id(after_nodes, "extendPanel") is not None + ok_all = ok and panel and surface_changed(before, after) + record("structure_more_panel", bool(ok_all), + "" if ok_all else "behavior_wrong: extendPanel did not appear after moreButton", + depth=1, jump_kind="transition", + expect="extendPanel appears (more menu overlays map) after tapping moreButton") + + # VLM: the more-menu overlays the RIGHT portion of the map, map still visible left. + vlm_assert("structure_more_panel", + "Is a vertical menu panel overlaying the right side of the screen " + "while a map is still visible on the left side?", + RESULTS_DIR, tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3. PLACES panel — panel appears (depth 1) + map fills behind it (VLM) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("structure_places_panel", "structure_places_panel_vlm")) +def test_places_panel_shape(): + home = dismiss_first_run() + before = and_showing(home) + ok, after_nodes = and_enter_panel(home, "placesButton") + after = and_showing(after_nodes) + panel = (node_by_id(after_nodes, "extendPanel") + or node_by_id(after_nodes, "contentPanel")) is not None + ok_all = ok and panel and surface_changed(before, after) + record("structure_places_panel", bool(ok_all), + "" if ok_all else "behavior_wrong: places panel did not appear after placesButton", + depth=1, jump_kind="transition", + expect="places panel container appears after tapping placesButton") + + # VLM: the map still fills the top of the screen behind the bottom panel. + vlm_assert("structure_places_panel", + "Does a map still fill the upper part of the screen above a " + "bottom panel area?", + RESULTS_DIR, tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4. TRACKS panel — panel appears (depth 1) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("structure_tracks_panel",)) +def test_tracks_panel_shape(): + home = dismiss_first_run() + before = and_showing(home) + ok, after_nodes = and_enter_panel(home, "tracksButton") + after = and_showing(after_nodes) + panel = (node_by_id(after_nodes, "extendPanel") + or node_by_id(after_nodes, "contentPanel")) is not None + ok_all = ok and panel and surface_changed(before, after) + record("structure_tracks_panel", bool(ok_all), + "" if ok_all else "behavior_wrong: tracks panel did not appear after tracksButton", + depth=1, jump_kind="transition", + expect="tracks panel container appears after tapping tracksButton") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5. MAPS panel — panel appears (depth 1) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("structure_maps_panel",)) +def test_maps_panel_shape(): + home = dismiss_first_run() + before = and_showing(home) + ok, after_nodes = and_enter_panel(home, "mapsButton") + after = and_showing(after_nodes) + panel = (node_by_id(after_nodes, "extendPanel") + or node_by_id(after_nodes, "contentPanel")) is not None + ok_all = ok and panel and surface_changed(before, after) + record("structure_maps_panel", bool(ok_all), + "" if ok_all else "behavior_wrong: maps panel did not appear after mapsButton", + depth=1, jump_kind="transition", + expect="maps panel container appears after tapping mapsButton") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 6. SETTINGS — bottom-sheet recycler of category rows appears (depth 2) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("structure_settings_sheet", "structure_settings_sheet_vlm")) +def test_settings_sheet_shape(): + ok, after_nodes = and_enter_settings() + grew = (node_by_id(after_nodes, "recycler_view") + or find_by_class(after_nodes, "RecyclerView")) is not None + ok_all = ok and grew + record("structure_settings_sheet", bool(ok_all), + "" if ok_all else "behavior_wrong: Settings did not open a recycler/list sheet", + depth=2, jump_kind="transition", + expect="Settings bottom sheet with a RecyclerView of category rows appears") + + # VLM: bottom sheet shows a vertical LIST of category rows (>=4 stacked labels). + vlm_assert("structure_settings_sheet", + "Is a bottom sheet showing a vertical list of at least four " + "text menu rows stacked one above another?", + RESULTS_DIR, tag="shape") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 7. MAP long-press — context-menu popup appears, surface changes (depth 1) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("structure_map_contextmenu",)) +def test_map_contextmenu_shape(): + home = dismiss_first_run() + if not node_by_id(home, "mapView"): + record("structure_map_contextmenu", False, + "setup_failed: mapView not found on home surface", + depth=1, jump_kind="transition", + expect="context-menu popup appears on map long-press") + return + ok_lp, new_keys = long_press_map() + # The context menu is a popup of new labelled rows over the map. + popup_rows = [k for k in new_keys if k.startswith("TextView|")] + ok = ok_lp and len(popup_rows) >= 3 + if ok: + and_enter("map_contextmenu") + record("structure_map_contextmenu", bool(ok), + "" if ok else "behavior_wrong: long-press map did not open a context-menu popup", + depth=1, jump_kind="transition", + expect="context-menu popup adds >=3 new menu rows over the map on long-press") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 8. PLACE bottom sheet — create a place, tap its row -> bottomSheetPanel (depth 2) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("structure_place_bottomsheet",)) +def test_place_bottomsheet_shape(): + home = dismiss_first_run() + placesbtn = node_by_id(home, "placesButton") + if not placesbtn: + record("structure_place_bottomsheet", False, + "setup_failed: placesButton not found", + depth=2, jump_kind="transition", + expect="bottomSheetPanel appears after tapping a place row") + return + # Create a place at map center (bottom-bar buttons ARE long-clickable, so the + # kit's long_press works here — this produces a "Place #N" row). + long_press(placesbtn, ms=900) + settle("tap") + # Open the Places panel. + ok_panel, panel_nodes = and_enter_panel(ui(), "placesButton") + if not ok_panel: + record("structure_place_bottomsheet", False, + "setup_failed: Places panel did not open after creating a place", + depth=2, jump_kind="transition", + expect="bottomSheetPanel appears after tapping a place row") + return + # Find the created row: a node with resource-id last-segment "name" in the list. + row = node_by_id(panel_nodes, "name") or find_node_ci(panel_nodes, "Place #1") + if not row or not is_safe(row): + record("structure_place_bottomsheet", False, + "feature_missing: created place row not present in Places panel", + depth=2, jump_kind="transition", + expect="bottomSheetPanel appears after tapping a place row") + return + before = and_showing(panel_nodes) + tap_node(row) + settle("tap") + after_nodes = ui() + sheet = (node_by_id(after_nodes, "bottomSheetPanel") + or node_by_id(after_nodes, "coordinatesRow") + or node_by_id(after_nodes, "actionButton")) is not None + changed = surface_changed(before, and_showing(after_nodes)) + ok = sheet and changed + if ok: + and_enter("place_info") + record("structure_place_bottomsheet", bool(ok), + "" if ok else "behavior_wrong: tapping a place row did not open the info bottom sheet", + depth=2, jump_kind="transition", + expect="bottomSheetPanel (place-info sheet) appears after tapping the created place row") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 9. COORDINATE dialog — places FAB opens an AlertDialog (depth 2) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("structure_coord_dialog",)) +def test_coord_dialog_shape(): + home = dismiss_first_run() + ok_panel, panel_nodes = and_enter_panel(home, "placesButton") + if not ok_panel: + record("structure_coord_dialog", False, + "setup_failed: Places panel did not open", + depth=2, jump_kind="transition", + expect="coordinate-input dialog (coordinatesEdit) appears from the places FAB") + return + fab = node_by_id(panel_nodes, "listActionButton") + if not fab or not is_safe(fab): + record("structure_coord_dialog", False, + "feature_missing: places FAB (listActionButton) not present", + depth=2, jump_kind="transition", + expect="coordinate-input dialog (coordinatesEdit) appears from the places FAB") + return + before = and_showing(panel_nodes) + tap_node(fab) + settle("tap") + after_nodes = ui() + dialog = (node_by_id(after_nodes, "coordinatesEdit") + or find_by_class(after_nodes, "EditText")) is not None + changed = surface_changed(before, and_showing(after_nodes)) + ok = dialog and changed + if ok: + and_enter("coord_dialog") + record("structure_coord_dialog", bool(ok), + "" if ok else "behavior_wrong: places FAB did not open a coordinate-input dialog", + depth=2, jump_kind="transition", + expect="AlertDialog with a coordinate EditText appears from the places FAB") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 10. SHAPE RETURNS — open Places panel then BACK restores the map surface (depth 0) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("structure_panel_returns",)) +def test_panel_returns_shape(): + home = dismiss_first_run() + if not home_ready(home): + record("structure_panel_returns", False, + "setup_failed: home surface not ready before opening panel", + depth=0, jump_kind="transition", + expect="panel container gone and map surface restored after BACK") + return + ok_panel, panel_nodes = and_enter_panel(home, "placesButton") + panel_present = (node_by_id(panel_nodes, "extendPanel") + or node_by_id(panel_nodes, "contentPanel")) is not None + if not (ok_panel and panel_present): + record("structure_panel_returns", False, + "setup_failed: Places panel did not open, cannot test its return", + depth=0, jump_kind="transition", + expect="panel container gone and map surface restored after BACK") + return + # Reverse the shape delta. + and_back() + restored = ui() + panel_gone = (node_by_id(restored, "extendPanel") is None + and node_by_id(restored, "contentPanel") is None) + map_back = home_ready(restored) + ok = panel_gone and map_back + record("structure_panel_returns", bool(ok), + "" if ok else "behavior_wrong: panel did not close / map surface not restored on BACK", + depth=0, jump_kind="transition", + expect="places panel container gone and the 5-button map surface restored after BACK") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 11. PLACE MARKER (canvas) — long-press placesButton draws a pin on the map (VLM) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("structure_place_marker_vlm",)) +def test_place_marker_vlm(): + home = dismiss_first_run() + placesbtn = node_by_id(home, "placesButton") + if placesbtn: + long_press(placesbtn, ms=900) + settle("tap") + # Marker + "Place #1" label are canvas-drawn (not in the tree) -> VLM only. + vlm_assert("structure_place_marker", + "Is a single map pin / location marker icon drawn on the map " + "near the centre of the screen?", + RESULTS_DIR, tag="shape") + + +TESTS = [ + test_gate_launch, + test_more_panel_shape, + test_places_panel_shape, + test_tracks_panel_shape, + test_maps_panel_shape, + test_settings_sheet_shape, + test_map_contextmenu_shape, + test_place_bottomsheet_shape, + test_coord_dialog_shape, + test_panel_returns_shape, + test_place_marker_vlm, +] + + +if __name__ == "__main__": + run_suite(TESTS, "structure") diff --git a/android/andreynovikov-trekarta/tests/test_android_text.py b/android/andreynovikov-trekarta/tests/test_android_text.py new file mode 100644 index 0000000000000000000000000000000000000000..76b3d4af797e679b6c921a65012353d53d14e954 --- /dev/null +++ b/android/andreynovikov-trekarta/tests/test_android_text.py @@ -0,0 +1,684 @@ +#!/usr/bin/env python3 +"""TEXT lane for Trekarta (mobi.maptrek) — CONTENT / OUTPUT strings. + +Sole owner of exact-string equality: empty-state messages, snackbars an action +PRODUCES, unit-summary strings, menu/dialog labels, place-info content, About +screen strings, and the canvas-only map marker label (the one opaque core -> VLM). + +Every string asserted here was OBSERVED on the RUNNING original app, never read +from the source tree. Package comes from sys.argv[1] via the kit's PACKAGE — never +a literal. Every test dismisses the first-run download AlertDialog first. +""" +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403 + + +# ── shared helpers ─────────────────────────────────────────────────────────── +def _wait_home_ready(timeout=12): + """Block past the Trekarta splash: wait_for_foreground() returns while the + logo is up and uiautomator then hands back a STALE tree. Poll until the + bottom-bar placesButton or the first-run dialog button2 is present.""" + import time as _t + deadline = _t.time() + timeout + while _t.time() < deadline: + n = ui() + if (node_by_id(n, "placesButton") is not None + or node_by_id(n, "button2") is not None): + return n + settle("key") + return ui() + + +def dismiss_first_run(): + """Launch fresh and clear the recurring 'download world map' AlertDialog. + NEVER taps DOWNLOAD. Returns the home tree.""" + restart_app(); wait_for_foreground() + _wait_home_ready() + n = ui() + b = find_node(n, text="SKIP") or node_by_id(n, "button2") + if b: + tap_node(b); settle("tap") + return ui() + + +def dismiss_first_run_clean(): + """Wipe app data first (virgin empty state / default settings) then dismiss + the first-run dialog. Use where a prior mutation could taint the string.""" + clear_data() + return dismiss_first_run() + + +def all_text(nodes): + return " | ".join(n.get("text", "") for n in nodes if n.get("text")) + + +def norm(s): + return " ".join((s or "").split()).strip() + + +def summary_after_title(nodes, title): + """On a preference page, return the `summary` node that immediately follows + the row whose `title` == `title` in document order (that is how Trekarta lays + out its Units rows — verified: each summary's top == its title's bottom).""" + seen_title = False + for n in nodes: + rid = n.get("resource-id", "").rsplit("/", 1)[-1] + if rid == "title" and n.get("text", "").strip() == title: + seen_title = True + continue + if seen_title and rid == "summary": + return n + return None + + +# ── depth-backing navigation helpers (name-matched by the audit) ────────────── +def and_enter_panel(rid): + """Open a bottom action-bar panel (Places/Tracks/Maps). Depth +1 on success.""" + n = ui() + btn = node_by_id(n, rid) + if not btn: + return False + before = and_showing(n) + if not tap_node(btn): + return False + settle("tap") + if not surface_changed(before, and_showing()): + return False + and_enter(rid) + return True + + +def and_enter_more(): + """Open the more-menu (extendPanel). Depth +1 on success.""" + n = ui() + mo = node_by_id(n, "moreButton") + if not mo or not tap_node(mo): + return False + settle("tap") + and_enter("moreMenu") + return True + + +def and_enter_settings(): + """From home: more -> Settings recycler. Depth +2 on success.""" + if not and_enter_more(): + return False + n = ui() + st = find_node(n, text="Settings") or find_node_ci(n, "Settings") + if not st or not tap_node(st): + return False + settle("tap") + and_enter("settings") + return True + + +def and_enter_units(): + """From home: more -> Settings -> Units. Depth +3 on success.""" + if not and_enter_settings(): + return False + n = ui() + u = find_node(n, text="Units") or find_node_ci(n, "Units") + if not u or not tap_node(u): + return False + settle("tap") + and_enter("units") + return True + + +def and_enter_about(): + """From home: more -> Settings -> About. Depth +3 on success.""" + if not and_enter_settings(): + return False + n = ui() + ab = find_node(n, text="About") or find_node_ci(n, "About") + if not ab or not tap_node(ab): + return False + settle("tap") + and_enter("about") + return True + + +def and_enter_place_info(): + """Create a place (long-press placesButton), open Places panel, tap the row + -> place-information bottom sheet. Depth +2 on success (panel -> sheet).""" + n = ui() + pb = node_by_id(n, "placesButton") + if not pb: + return False + long_press(pb, 900) # creates 'Place #1' at map centre + settle("tap") + if not and_enter_panel("placesButton"): + return False + n = ui() + row = node_by_id(n, "name") # the 'Place #1' row + if not row or not tap_node(row): + return False + settle("tap") + and_enter("placeInfo") + return True + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1. EMPTY-STATE STRINGS (open each panel from a virgin state) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_places_empty",)) +def test_places_empty_string(): + dismiss_first_run_clean() + marker = "Your places will appear here" + absent = marker.lower() not in all_text(ui()).lower() + if not and_enter_panel("placesButton"): + record("text_places_empty", False, + "setup_failed: could not open Places panel", + depth=1, jump_kind="transition", + expect="empty text 'Your places will appear here...'") + return + n = ui() + em = node_by_id(n, "empty") + txt = norm(em.get("text")) if em else "" + # Distinctive substrings observed on the original (avoid the encoded newline + # region ' ' the dump leaves literal between the two sentences). + present = ("your places will appear here" in txt.lower() + and "long pressing places button" in txt.lower()) + ok = absent and present + record("text_places_empty", ok, + "" if ok else f"behavior_wrong: Places empty-state string wrong: {txt!r}", + depth=1, jump_kind="transition", + expect="Your places will appear here. You can create place by entering " + "its coordinates or by long pressing Places button.") + + +@and_test(expects=("text_tracks_empty",)) +def test_tracks_empty_string(): + dismiss_first_run_clean() + marker = "Your recorded tracks will appear here." + absent = marker.lower() not in all_text(ui()).lower() + if not and_enter_panel("tracksButton"): + record("text_tracks_empty", False, + "setup_failed: could not open Tracks panel", + depth=1, jump_kind="transition", expect=marker) + return + n = ui() + em = node_by_id(n, "empty") + txt = norm(em.get("text")) if em else "" + present = txt.lower() == marker.lower() + ok = absent and present + record("text_tracks_empty", ok, + "" if ok else f"behavior_wrong: Tracks empty-state string wrong: {txt!r}", + depth=1, jump_kind="transition", expect=marker) + + +@and_test(expects=("text_maps_empty",)) +def test_maps_empty_string(): + dismiss_first_run_clean() + marker = "Your installed custom tile maps will appear here." + absent = marker.lower() not in all_text(ui()).lower() + if not and_enter_panel("mapsButton"): + record("text_maps_empty", False, + "setup_failed: could not open Maps panel", + depth=1, jump_kind="transition", expect=marker) + return + n = ui() + em = node_by_id(n, "empty") + txt = norm(em.get("text")) if em else "" + present = txt.lower() == marker.lower() + ok = absent and present + record("text_maps_empty", ok, + "" if ok else f"behavior_wrong: Maps empty-state string wrong: {txt!r}", + depth=1, jump_kind="transition", expect=marker) + + +@and_test(expects=("text_places_import_footer",)) +def test_places_import_footer(): + """After a place exists the Places panel shows a data-source footer row + 'You can also import GPX and KML files.' — assert that exact footer string.""" + dismiss_first_run_clean() + footer = "You can also import GPX and KML files." + n = ui() + pb = node_by_id(n, "placesButton") + if not pb: + record("text_places_import_footer", False, + "setup_failed: placesButton missing on home", + depth=1, jump_kind="transition", expect=footer) + return + long_press(pb, 900); settle("tap") # create a place + if not and_enter_panel("placesButton"): + record("text_places_import_footer", False, + "setup_failed: could not open Places panel", + depth=1, jump_kind="transition", expect=footer) + return + n = ui() + hit = any(norm(x.get("text")).lower() == footer.lower() + for x in n if x.get("text")) + record("text_places_import_footer", hit, + "" if hit else "behavior_wrong: import footer row string not found", + depth=1, jump_kind="transition", expect=footer) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2. SNACKBAR strings an ACTION produces (before absent -> after present) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_snackbar_place_saved", "text_snackbar_customize")) +def test_place_saved_snackbar(): + dismiss_first_run_clean() + absent = "place saved" not in all_text(ui()).lower() + n = ui() + pb = node_by_id(n, "placesButton") + if not pb: + record("text_snackbar_place_saved", False, + "setup_failed: placesButton missing on home", + depth=0, jump_kind="transition", expect="snackbar 'Place saved'") + record("text_snackbar_customize", False, + "setup_failed: placesButton missing on home", + depth=0, jump_kind="transition", expect="snackbar action 'CUSTOMIZE'") + return + long_press(pb, 900) + # The snackbar auto-dismisses; grab the tree immediately (no pre-dump settle). + snap = parse_nodes(dump_xml(settle_first=False)) + st = node_by_id(snap, "snackbar_text") + act = node_by_id(snap, "snackbar_action") + saved_txt = norm(st.get("text")) if st else norm( + (find_node_ci(snap, "Place saved") or {}).get("text")) + action_txt = norm(act.get("text")) if act else norm( + (find_node_ci(snap, "CUSTOMIZE") or {}).get("text")) + + ok_saved = absent and saved_txt.lower() == "place saved" + record("text_snackbar_place_saved", ok_saved, + "" if ok_saved else + f"behavior_wrong: expected snackbar 'Place saved', got {saved_txt!r}", + depth=0, jump_kind="transition", expect="snackbar reads 'Place saved'") + + ok_action = action_txt.lower() == "customize" + record("text_snackbar_customize", ok_action, + "" if ok_action else + f"behavior_wrong: expected snackbar action 'CUSTOMIZE', got {action_txt!r}", + depth=0, jump_kind="transition", expect="snackbar action reads 'CUSTOMIZE'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3. UNIT SUMMARY DEFAULT STRINGS (Units page rows) — from a FRESH clear_data +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_units_speed_default", "text_units_distance_default")) +def test_units_speed_and_distance(): + dismiss_first_run_clean() + if not and_enter_units(): + for nm, exp in (("text_units_speed_default", "Speed = miles per hour"), + ("text_units_distance_default", "Distance = miles/feet")): + record(nm, False, "setup_failed: could not reach the Units page", + depth=3, jump_kind="value", expect=exp) + return + n = ui() + sp = summary_after_title(n, "Speed") + ds = summary_after_title(n, "Distance") + sp_txt = norm(sp.get("text")) if sp else "" + ds_txt = norm(ds.get("text")) if ds else "" + ok_sp = sp_txt.lower() == "miles per hour" + ok_ds = ds_txt.lower() == "miles/feet" + record("text_units_speed_default", ok_sp, + "" if ok_sp else f"behavior_wrong: Speed summary {sp_txt!r} != 'miles per hour'", + depth=3, jump_kind="value", expect="Speed summary 'miles per hour'") + record("text_units_distance_default", ok_ds, + "" if ok_ds else f"behavior_wrong: Distance summary {ds_txt!r} != 'miles/feet'", + depth=3, jump_kind="value", expect="Distance summary 'miles/feet'") + + +@and_test(expects=("text_units_elevation_default", "text_units_angle_default")) +def test_units_elevation_and_angle(): + dismiss_first_run_clean() + if not and_enter_units(): + for nm, exp in (("text_units_elevation_default", "Elevation = feet"), + ("text_units_angle_default", "Angle = degrees")): + record(nm, False, "setup_failed: could not reach the Units page", + depth=3, jump_kind="value", expect=exp) + return + n = ui() + el = summary_after_title(n, "Elevation") + an = summary_after_title(n, "Angle") + el_txt = norm(el.get("text")) if el else "" + an_txt = norm(an.get("text")) if an else "" + ok_el = el_txt.lower() == "feet" + ok_an = an_txt.lower() == "degrees" + record("text_units_elevation_default", ok_el, + "" if ok_el else f"behavior_wrong: Elevation summary {el_txt!r} != 'feet'", + depth=3, jump_kind="value", expect="Elevation summary 'feet'") + record("text_units_angle_default", ok_an, + "" if ok_an else f"behavior_wrong: Angle summary {an_txt!r} != 'degrees'", + depth=3, jump_kind="value", expect="Angle summary 'degrees'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4. DISTANCE DIALOG option labels (open dialog, assert labels, CANCEL out) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_distance_dialog_options",)) +def test_distance_dialog_options(): + dismiss_first_run_clean() + expected = ["kilometers/meters", "miles/yards", "miles/feet", "nautical miles"] + if not and_enter_units(): + record("text_distance_dialog_options", False, + "setup_failed: could not reach the Units page", + depth=3, jump_kind="value", expect=" / ".join(expected)) + return + n = ui() + row = find_node(n, text="Distance") + before = "kilometers/meters" not in all_text(n).lower() + if not row or not tap_node(row): + record("text_distance_dialog_options", False, + "setup_failed: Distance row not tappable", + depth=3, jump_kind="value", expect=" / ".join(expected)) + return + settle("tap") + and_enter("distanceDialog") + n = ui() + opts = [norm(x.get("text")).lower() + for x in find_by_class(n, "CheckedTextView") if x.get("text")] + present = all(e in opts for e in expected) + ok = before and present + record("text_distance_dialog_options", ok, + "" if ok else f"behavior_wrong: Distance dialog options were {opts!r}", + depth=3, jump_kind="value", + expect="options kilometers/meters, miles/yards, miles/feet, nautical miles") + # CANCEL out — do NOT change the unit. + n = ui() + c = find_node(n, text="CANCEL") or node_by_id(n, "button2") + if c: + tap_node(c); settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5. MORE-MENU labels +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_more_menu_labels",)) +def test_more_menu_labels(): + dismiss_first_run() + expected = ["Fullscreen", "Settings", "Import", "Manage maps", + "Ruler", "Create route", "Activity", "Search"] + before = "manage maps" not in all_text(ui()).lower() + if not and_enter_more(): + record("text_more_menu_labels", False, + "setup_failed: could not open the more-menu", + depth=1, jump_kind="value", expect=", ".join(expected)) + return + n = ui() + titles = {norm(x.get("text")).lower() + for x in n + if x.get("resource-id", "").rsplit("/", 1)[-1] == "title" + and x.get("text")} + missing = [e for e in expected if e.lower() not in titles] + ok = before and not missing + record("text_more_menu_labels", ok, + "" if ok else f"behavior_wrong: more-menu missing labels {missing!r}", + depth=1, jump_kind="value", + expect="Fullscreen, Settings, Import, Manage maps, Ruler, " + "Create route, Activity, Search") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 6. SETTINGS category labels +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_settings_categories",)) +def test_settings_categories(): + dismiss_first_run() + expected = ["General", "Units", "Location", "Places, tracks, routes", + "Advanced", "About"] + before = "advanced" not in all_text(ui()).lower() + if not and_enter_settings(): + record("text_settings_categories", False, + "setup_failed: could not reach the Settings list", + depth=2, jump_kind="value", expect=", ".join(expected)) + return + n = ui() + titles = {norm(x.get("text")).lower() + for x in n + if x.get("resource-id", "").rsplit("/", 1)[-1] == "title" + and x.get("text")} + missing = [e for e in expected if e.lower() not in titles] + ok = before and not missing + record("text_settings_categories", ok, + "" if ok else f"behavior_wrong: Settings missing categories {missing!r}", + depth=2, jump_kind="value", + expect="General, Units, Location, Places, tracks, routes, Advanced, About") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 7. ACTIVITY dialog labels (open, assert, back out — do NOT select) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_activity_dialog_options",)) +def test_activity_dialog_options(): + dismiss_first_run() + expected = ["None", "Hiking", "Cycling", "Skiing"] + before = "hiking" not in all_text(ui()).lower() + if not and_enter_more(): + record("text_activity_dialog_options", False, + "setup_failed: could not open the more-menu", + depth=1, jump_kind="value", expect=", ".join(expected)) + return + n = ui() + act = find_node(n, text="Activity") + if not act or not tap_node(act): + record("text_activity_dialog_options", False, + "setup_failed: Activity row not tappable", + depth=1, jump_kind="value", expect=", ".join(expected)) + return + settle("tap") + and_enter("activityDialog") + n = ui() + opts = {norm(x.get("text")).lower() + for x in find_by_class(n, "CheckedTextView") if x.get("text")} + missing = [e for e in expected if e.lower() not in opts] + ok = before and not missing + record("text_activity_dialog_options", ok, + "" if ok else f"behavior_wrong: Activity dialog missing {missing!r}", + depth=2, jump_kind="value", expect="None, Hiking, Cycling, Skiing") + back(); settle("tap") # dismiss without selecting + + +# ══════════════════════════════════════════════════════════════════════════════ +# 8. MAP long-press CONTEXT-MENU labels +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_map_context_menu",)) +def test_map_context_menu_labels(): + dismiss_first_run() + expected = ["Share coordinates", "Add place", "Navigate here", "Remember zoom"] + before = "remember zoom" not in all_text(ui()).lower() + n = ui() + mv = node_by_id(n, "mapView") + if not mv: + record("text_map_context_menu", False, + "setup_failed: mapView not present on home", + depth=1, jump_kind="value", expect=", ".join(expected)) + return + long_press(mv, 900); settle("tap") + and_enter("mapContextMenu") + n = ui() + titles = {norm(x.get("text")).lower() + for x in n + if x.get("resource-id", "").rsplit("/", 1)[-1] == "title" + and x.get("text")} + missing = [e for e in expected if e.lower() not in titles] + ok = before and not missing + record("text_map_context_menu", ok, + "" if ok else f"behavior_wrong: map context menu missing {missing!r}", + depth=1, jump_kind="value", + expect="Share coordinates, Add place, Navigate here, Remember zoom") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 9. PLACE-INFO sheet content strings (source, date, produced row name) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_place_info_source", "text_place_info_date_present")) +def test_place_info_content(): + dismiss_first_run_clean() + if not and_enter_place_info(): + for nm, exp in (("text_place_info_source", "source 'My places'"), + ("text_place_info_date_present", "a non-empty date row")): + record(nm, False, + "setup_failed: could not reach the place-information sheet", + depth=2, jump_kind="value", expect=exp) + return + n = ui() + src = node_by_id(n, "source") + date = node_by_id(n, "date") + src_txt = norm(src.get("text")) if src else "" + date_txt = norm(date.get("text")) if date else "" + ok_src = src_txt.lower() == "my places" + record("text_place_info_source", ok_src, + "" if ok_src else f"behavior_wrong: place source {src_txt!r} != 'My places'", + depth=2, jump_kind="value", expect="place-info source reads 'My places'") + # The date is locale/time-formatted (e.g. '8/6/26 9:33 PM') — too brittle to + # assert exactly, so require only that the info sheet populates a date row. + ok_date = bool(date_txt) + record("text_place_info_date_present", ok_date, + "" if ok_date else "behavior_wrong: place-info date row is empty", + depth=2, jump_kind="value", expect="place-info date row is populated") + + +@and_test(expects=("text_place_row_name",)) +def test_place_row_name_after_create(): + """The row label a create PRODUCES: long-press placesButton -> Places panel + shows a 'Place #1' row that was ABSENT before the create.""" + dismiss_first_run_clean() + n = ui() + pb = node_by_id(n, "placesButton") + if not pb: + record("text_place_row_name", False, + "setup_failed: placesButton missing on home", + depth=1, jump_kind="transition", expect="row named 'Place #1'") + return + if not and_enter_panel("placesButton"): + record("text_place_row_name", False, + "setup_failed: could not open Places panel", + depth=1, jump_kind="transition", expect="row named 'Place #1'") + return + absent = "place #1" not in all_text(ui()).lower() + back(); settle("tap") # close panel + n = ui() + pb = node_by_id(n, "placesButton") + long_press(pb, 900); settle("tap") # create + if not and_enter_panel("placesButton"): + record("text_place_row_name", False, + "setup_failed: could not reopen Places panel after create", + depth=1, jump_kind="transition", expect="row named 'Place #1'") + return + n = ui() + row = node_by_id(n, "name") + row_txt = norm(row.get("text")) if row else "" + present = row_txt.lower() == "place #1" + ok = absent and present + record("text_place_row_name", ok, + "" if ok else f"behavior_wrong: created place row {row_txt!r} != 'Place #1'", + depth=1, jump_kind="transition", expect="Places panel row reads 'Place #1'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 10. ABOUT screen strings (app name, Version label, description, section header) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_about_appname", "text_about_version_label")) +def test_about_appname_and_version(): + dismiss_first_run() + if not and_enter_about(): + record("text_about_appname", False, + "setup_failed: could not reach the About screen", + depth=3, jump_kind="value", expect="app name 'Trekarta'") + record("text_about_version_label", False, + "setup_failed: could not reach the About screen", + depth=3, jump_kind="value", expect="a 'Version:' label") + return + n = ui() + # App name renders on an ImageView with content-desc 'Trekarta'. + name_node = find_node(n, content_desc="Trekarta") or node_by_id(n, "title") + name_val = norm((name_node or {}).get("content-desc") or (name_node or {}).get("text")) + ok_name = name_val.lower() == "trekarta" + record("text_about_appname", ok_name, + "" if ok_name else f"behavior_wrong: About app name {name_val!r} != 'Trekarta'", + depth=3, jump_kind="value", expect="About screen shows app name 'Trekarta'") + + # Assert the 'Version:' LABEL prefix only — the number is a dynamic build value + # a recreation cannot know, so it is deliberately NOT part of the assertion. + ver = node_by_id(n, "version") + ver_txt = norm(ver.get("text")) if ver else "" + if not ver_txt: + ver_txt = next((norm(x.get("text")) for x in n + if x.get("text", "").strip().lower().startswith("version")), "") + ok_ver = ver_txt.lower().startswith("version") + record("text_about_version_label", ok_ver, + "" if ok_ver else f"behavior_wrong: no 'Version:' label on About (got {ver_txt!r})", + depth=3, jump_kind="value", expect="About screen shows a 'Version:' label") + + +@and_test(expects=("text_about_description", "text_about_copyright_header")) +def test_about_description_and_header(): + dismiss_first_run() + if not and_enter_about(): + record("text_about_description", False, + "setup_failed: could not reach the About screen", + depth=3, jump_kind="value", expect="description begins 'Trekarta is designed for...'") + record("text_about_copyright_header", False, + "setup_failed: could not reach the About screen", + depth=3, jump_kind="value", expect="'COPYRIGHT' section header") + return + n = ui() + blob = all_text(n).lower() + # Distinctive, app-unique substring of the long description observed verbatim. + desc_sub = ("trekarta is designed for hiking, geocaching, off-roading, " + "cycling, boating") + ok_desc = desc_sub in blob + record("text_about_description", ok_desc, + "" if ok_desc else "behavior_wrong: About description substring not found", + depth=3, jump_kind="value", + expect="description begins 'Trekarta is designed for hiking, geocaching, " + "off-roading, cycling, boating...'") + + ok_hdr = any(norm(x.get("text")).lower() == "copyright" for x in n if x.get("text")) + record("text_about_copyright_header", ok_hdr, + "" if ok_hdr else "behavior_wrong: 'COPYRIGHT' section header not found", + depth=3, jump_kind="value", expect="About screen shows a 'COPYRIGHT' header") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 11. VLM — the ONE opaque core: the map marker LABEL drawn on canvas +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_map_marker_label_vlm",)) +def test_map_marker_label_vlm(): + """The 'Place #1' label is drawn on the map Canvas and never reaches the view + tree next to the pin, so it is the one legitimate content VLM in this lane.""" + dismiss_first_run_clean() + n = ui() + pb = node_by_id(n, "placesButton") + if not pb: + record("text_map_marker_label_vlm", False, + "setup_failed: placesButton missing on home", + depth=0, jump_kind="value", tag="content") + return + long_press(pb, 900); settle("tap") # create place at map centre + settle("tap") # let the marker + label render + vlm_assert("text_map_marker_label", + "Is the text label 'Place #1' drawn on the map next to a " + "pin/marker icon?", + RESULTS_DIR, depth=0, jump_kind="value", tag="content") + + +TESTS = [ + test_places_empty_string, + test_tracks_empty_string, + test_maps_empty_string, + test_places_import_footer, + test_place_saved_snackbar, + test_units_speed_and_distance, + test_units_elevation_and_angle, + test_distance_dialog_options, + test_more_menu_labels, + test_settings_categories, + test_activity_dialog_options, + test_map_context_menu_labels, + test_place_info_content, + test_place_row_name_after_create, + test_about_appname_and_version, + test_about_description_and_header, + test_map_marker_label_vlm, +] + +if __name__ == "__main__": + if not device_online(): + print("Device offline — cannot run the TEXT suite") + sys.exit(1) + run_suite(TESTS, "text") diff --git a/android/andreynovikov-trekarta/tests/test_manifest.json b/android/andreynovikov-trekarta/tests/test_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..8535fe3914f761cafcf2cb3ba70041f916cf40a5 --- /dev/null +++ b/android/andreynovikov-trekarta/tests/test_manifest.json @@ -0,0 +1,772 @@ +{ + "manifest_version": 1, + "kit_api_version": 1, + "task_id": "trekarta", + "baseline_model": "claude-opus-4-8", + "baseline_package": "", + "total": 124, + "manifest_sha": "9d2d72565703", + "tests": [ + { + "name": "computation::computation_coord_decimal_pair", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_coord_distinct_outputs", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_coord_empty_no_place", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_coord_invalid_no_place", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_coord_mixed_sign", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_coord_negative_pair", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_coord_positive_pair", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_coord_short_decimals", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_coord_zero_pair", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_add_place_map_menu", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_coord_place_has_info", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_create_coordinate_dialog", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_create_delete_roundtrip", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_create_persists", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_create_place_longpress", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_create_place_marker_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_create_two_places", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_delete_marker_gone_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_delete_one_of_two", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_delete_place", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_edit_color_swatch_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_edit_description_persists", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_import_markers_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_import_persists", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_import_places", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_longpress_vs_tap_semantics", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_map_context_menu", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_map_menu_marker_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_multi_record_integrity", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_multi_record_persists", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_place_info_actions", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_place_info_fab_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_place_saved_snackbar_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_rename_last_write_wins", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_rename_map_label_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_rename_persists", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_rename_place", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_rename_reopen_shows_new_name", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_three_records_persist", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_two_markers_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_back_info_places", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_back_more_home", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_back_units_categories", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_unwind_3hop", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_about", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_activity", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_activity_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_coord_dialog", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_coord_dialog_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_create_route", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_import_picker", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_manage_maps", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_map_menu", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_map_menu_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_maps", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_more", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_more_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_place_edit", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_place_info", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_place_info_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_places", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_ruler", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_search", + "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_tracks", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_units", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_units_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_switch_places_tracks", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "states::states_activity_radio_select", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_activity_radio_select_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_distance_unit_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_distance_unit_transition", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_elevation_unit_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_extra_precision_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_extra_precision_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_fullscreen_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_fullscreen_toggle_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_location_follow_gauge", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_location_follow_gauge_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_location_recenter_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_speed_unit_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_speed_unit_transition", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_track_recording_pause", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_track_recording_start", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_track_recording_start_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "structure::structure_coord_dialog", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_launch", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_launch_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_map_contextmenu", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_maps_panel", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_more_panel", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_more_panel_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_panel_returns", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_place_bottomsheet", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_place_marker_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_places_panel", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_places_panel_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_sheet", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_sheet_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_tracks_panel", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "text::text_about_appname", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_about_copyright_header", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_about_description", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_about_version_label", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_activity_dialog_options", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_distance_dialog_options", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_map_context_menu", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_map_marker_label_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_maps_empty", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_more_menu_labels", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_place_info_date_present", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_place_info_source", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_place_row_name", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_places_empty", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_places_import_footer", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_categories", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_snackbar_customize", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_snackbar_place_saved", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_tracks_empty", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_units_angle_default", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_units_distance_default", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_units_elevation_default", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_units_speed_default", + "module": "text", + "baseline_status": "passed" + } + ], + "ignored": [], + "vlm_assertions": [ + { + "name": "interaction::interaction_place_saved_snackbar_vlm", + "module": "interaction", + "tag": "content" + }, + { + "name": "interaction::interaction_create_place_marker_vlm", + "module": "interaction", + "tag": "position" + }, + { + "name": "interaction::interaction_two_markers_vlm", + "module": "interaction", + "tag": "position" + }, + { + "name": "interaction::interaction_rename_map_label_vlm", + "module": "interaction", + "tag": "content" + }, + { + "name": "interaction::interaction_delete_marker_gone_vlm", + "module": "interaction", + "tag": "position" + }, + { + "name": "interaction::interaction_map_menu_marker_vlm", + "module": "interaction", + "tag": "position" + }, + { + "name": "interaction::interaction_place_info_fab_vlm", + "module": "interaction", + "tag": "position" + }, + { + "name": "interaction::interaction_edit_color_swatch_vlm", + "module": "interaction", + "tag": "color" + }, + { + "name": "interaction::interaction_import_markers_vlm", + "module": "interaction", + "tag": "position" + }, + { + "name": "navigation::nav_reach_more_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_reach_settings_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_reach_units_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_reach_activity_vlm", + "module": "navigation", + "tag": "shape" + }, + { + "name": "navigation::nav_reach_map_menu_vlm", + "module": "navigation", + "tag": "content" + }, + { + "name": "navigation::nav_reach_coord_dialog_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_reach_place_info_vlm", + "module": "navigation", + "tag": "color" + }, + { + "name": "states::states_fullscreen_toggle_vlm", + "module": "states", + "tag": "layout" + }, + { + "name": "states::states_location_follow_gauge_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_location_recenter_vlm", + "module": "states", + "tag": "position" + }, + { + "name": "states::states_track_recording_start_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_activity_radio_select_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "structure::structure_gate_launch_vlm", + "module": "structure", + "tag": "shape" + }, + { + "name": "structure::structure_more_panel_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_places_panel_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_settings_sheet_vlm", + "module": "structure", + "tag": "shape" + }, + { + "name": "structure::structure_place_marker_vlm", + "module": "structure", + "tag": "shape" + }, + { + "name": "text::text_map_marker_label_vlm", + "module": "text", + "tag": "content" + } + ], + "vlm_total": 27, + "n_vlm_unverified": 0, + "vlm_log_found": true +} \ No newline at end of file diff --git a/android/andreynovikov-trekarta/vlm_assertions.json b/android/andreynovikov-trekarta/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..01e2dd97e663d16fb533f84247729034e9b39ae6 --- /dev/null +++ b/android/andreynovikov-trekarta/vlm_assertions.json @@ -0,0 +1,563 @@ +{ + "schema_version": 2, + "instance_id": "android/andreynovikov-trekarta", + "grading": { + "mode": "inline", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 27, + "with_verdict": 27, + "calibrated": 0, + "usable": null, + "scored_records": 27, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "interaction_place_saved_snackbar_vlm", + "screenshot": "interaction_place_saved_snackbar_vlm.png", + "assertion": "Is a dark snackbar/toast shown near the bottom of the screen containing the text 'Place saved'?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "interaction_place_saved_snackbar", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_create_place_marker_vlm", + "screenshot": "interaction_create_place_marker_vlm.png", + "assertion": "Is a map pin/marker drawn near the centre of the map, with the text label 'Place #1' next to it?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "interaction_create_place_marker", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_two_markers_vlm", + "screenshot": "interaction_two_markers_vlm.png", + "assertion": "Is a map pin/marker drawn near the vertical centre of the map with the text label 'Place #2' shown directly above it?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "interaction_two_markers", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_rename_map_label_vlm", + "screenshot": "interaction_rename_map_label_vlm.png", + "assertion": "Is the text label 'kit_rec_A' drawn on the map next to a pin/marker?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "interaction_rename_map_label", + "rigor": { + "jump_kind": "transition", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_delete_marker_gone_vlm", + "screenshot": "interaction_delete_marker_gone_vlm.png", + "assertion": "Near the vertical centre of the map, is there NO pin/marker and NO text label reading 'Place #1' (the marker has been removed)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "interaction_delete_marker_gone", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_map_menu_marker_vlm", + "screenshot": "interaction_map_menu_marker_vlm.png", + "assertion": "Is a map pin/marker drawn on the map (a place was just added via the context menu)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "interaction_map_menu_marker", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_place_info_fab_vlm", + "screenshot": "interaction_place_info_fab_vlm.png", + "assertion": "In the place-information panel, is there a round ORANGE floating action button positioned at the upper-right of the panel?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "interaction_place_info_fab", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_edit_color_swatch_vlm", + "screenshot": "interaction_edit_color_swatch_vlm.png", + "assertion": "In this place-edit form, is there a small filled COLOURED circle (a colour swatch) shown to the right, near the Description field?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "interaction_edit_color_swatch", + "rigor": { + "jump_kind": "transition", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_import_markers_vlm", + "screenshot": "interaction_import_markers_vlm.png", + "assertion": "Are one or more map pins/markers now drawn on the map (imported places)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "interaction_import_markers", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_gate_launch_vlm", + "screenshot": "structure_gate_launch_vlm.png", + "assertion": "Is there a horizontal row of exactly 5 evenly spaced icon buttons across the very bottom edge of the screen?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "structure_gate_launch", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_more_panel_vlm", + "screenshot": "structure_more_panel_vlm.png", + "assertion": "Is a vertical menu panel overlaying the right side of the screen while a map is still visible on the left side?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_more_panel", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_places_panel_vlm", + "screenshot": "structure_places_panel_vlm.png", + "assertion": "Does a map still fill the upper part of the screen above a bottom panel area?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_places_panel", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_settings_sheet_vlm", + "screenshot": "structure_settings_sheet_vlm.png", + "assertion": "Is a bottom sheet showing a vertical list of at least four text menu rows stacked one above another?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "structure_settings_sheet", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_place_marker_vlm", + "screenshot": "structure_place_marker_vlm.png", + "assertion": "Is a single map pin / location marker icon drawn on the map near the centre of the screen?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "structure_place_marker", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_more_vlm", + "screenshot": "nav_reach_more_vlm.png", + "assertion": "Is a vertical text menu panel overlaying the RIGHT side of the screen while a map is still visible on the LEFT side?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_reach_more", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_settings_vlm", + "screenshot": "nav_reach_settings_vlm.png", + "assertion": "Is a bottom sheet slid up over the lower part of the screen showing a vertical list of at least four text menu rows?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_reach_settings", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_units_vlm", + "screenshot": "nav_reach_units_vlm.png", + "assertion": "Does this settings sub-page list rows each with a bold label on the left and a smaller grey value line beneath it?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_reach_units", + "rigor": { + "jump_kind": "none", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_activity_vlm", + "screenshot": "nav_reach_activity_vlm.png", + "assertion": "Is a dialog titled 'Activity' showing a vertical list of radio options, exactly one of which has a filled/selected radio button?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "nav_reach_activity", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_map_menu_vlm", + "screenshot": "nav_reach_map_menu_vlm.png", + "assertion": "Is a small popup menu of four stacked text options (Share coordinates / Add place / Navigate here / Remember zoom) shown on top of the map?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "nav_reach_map_menu", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_coord_dialog_vlm", + "screenshot": "nav_reach_coord_dialog_vlm.png", + "assertion": "Is a dialog with a single text input field shown, with the on-screen keyboard raised at the bottom of the screen?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_reach_coord_dialog", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_place_info_vlm", + "screenshot": "nav_reach_place_info_vlm.png", + "assertion": "Is a bottom sheet showing place details with a round ORANGE circular action button (a floating action button) at its right edge?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "nav_reach_place_info", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_fullscreen_toggle_vlm", + "screenshot": "states_fullscreen_toggle_vlm.png", + "assertion": "Is the top system status bar (clock, wifi and battery icons) hidden, with the app/map content extending all the way to the very top edge of the screen (fullscreen immersive mode)?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "states_fullscreen_toggle", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_location_follow_gauge_vlm", + "screenshot": "states_location_follow_gauge_vlm.png", + "assertion": "Look at the row of navigation buttons at the bottom. Is the leftmost button (a navigation arrow) highlighted in a bright orange/red accent colour, distinctly different from the other grey buttons?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_location_follow_gauge", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_location_recenter_vlm", + "screenshot": "states_location_recenter_vlm.png", + "assertion": "Is there a solid RED arrow-shaped location/heading cursor drawn on the map, indicating the current GPS position?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "states_location_recenter", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_track_recording_start_vlm", + "screenshot": "states_track_recording_start_vlm.png", + "assertion": "Look at the bottom navigation buttons. Is the second button (a squiggle/track-shaped icon) highlighted in a bright orange/red accent colour, indicating active track recording?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_track_recording_start", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_activity_radio_select_vlm", + "screenshot": "states_activity_radio_select_vlm.png", + "assertion": "Look at the 'Activity' dialog radio list. Is exactly ONE radio button filled/dotted with a bright orange accent colour while the others are empty grey circles?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_activity_radio_select", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_map_marker_label_vlm", + "screenshot": "text_map_marker_label_vlm.png", + "assertion": "Is the text label 'Place #1' drawn on the map next to a pin/marker icon?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "text_map_marker_label", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + } + ], + "merged_from_files": 1, + "source_shapes": { + "list": 1 + } +} \ No newline at end of file diff --git a/android/anilbeesetti-nextplayer/LICENSE b/android/anilbeesetti-nextplayer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f288702d2fa16d3cdf0035b15a9fcbc552cd88e7 --- /dev/null +++ b/android/anilbeesetti-nextplayer/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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 for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know 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 License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of 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 of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification 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 of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. 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 work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a 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 visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation 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 to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients 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 to +produce it from the Program, in the form of source code under the +terms 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 independent +works, 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 not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-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 excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the 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 install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional 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 you +add to a covered work, you may (if authorized by the copyright holders of +that 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 "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form 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 expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered 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 automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent 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 anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain 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 limiting +any implied license or other defenses to infringement that may +otherwise 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 or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License 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 have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License 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 the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES 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 OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy 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 greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + 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 appropriate +parts of the General Public License. Of course, your program's commands +might 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 +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/android/anilbeesetti-nextplayer/instance.json b/android/anilbeesetti-nextplayer/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..ca6d2fd933cf6964600827f91c86550b73d1ae42 --- /dev/null +++ b/android/anilbeesetti-nextplayer/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "android/anilbeesetti-nextplayer", + "platform": "android", + "repo": "https://github.com/anilbeesetti/nextplayer", + "commit": "0c471064198f2655efa6138bf46ea8cabd56e8a0", + "patches": [], + "package": "dev.anilbeesetti.nextplayer.debug", + "license": null +} diff --git a/android/anilbeesetti-nextplayer/reference/launch.sh b/android/anilbeesetti-nextplayer/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8 --- /dev/null +++ b/android/anilbeesetti-nextplayer/reference/launch.sh @@ -0,0 +1,9 @@ +#!/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 1 diff --git a/android/anilbeesetti-nextplayer/tests/android_computation_eval.json b/android/anilbeesetti-nextplayer/tests/android_computation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..dd59d9f69175963a6f0b078ad0144bdedb29c229 --- /dev/null +++ b/android/anilbeesetti-nextplayer/tests/android_computation_eval.json @@ -0,0 +1,161 @@ +{ + "module": "computation", + "total": 14, + "passed": 14, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 11, + "passed": 11, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 3, + "passed": 3, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.2727, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 14, + "depth_ge1": 12, + "depth_ge2": 4, + "value": 14, + "vlm_fine": 0 + }, + "results": [ + { + "test": "computation_search_beta_count", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "header 'Videos (1)', row beta_movie only" + }, + { + "test": "computation_search_beta_vlm", + "passed": true, + "message": "VLM: Q='In this search results screen, is there exactly ONE video result row, and does its title read 'beta_movie'?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In this search results screen, is there exactly ONE video result row, and does its title read 'beta_movie'?", + "tag": "content" + }, + { + "test": "computation_search_gamma_count", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "header 'Videos (1)', row gamma_reel only" + }, + { + "test": "computation_search_clip_count", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "header 'Videos (1)', row alpha_clip only" + }, + { + "test": "computation_search_movie_count", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "header 'Videos (1)', row beta_movie only" + }, + { + "test": "computation_search_multi_count", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "header 'Videos (3)', all three rows" + }, + { + "test": "computation_search_underscore_count", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "header 'Videos (3)', all rows, no Folders header" + }, + { + "test": "computation_search_nomatch_count", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "no Videos header, zero result rows" + }, + { + "test": "computation_folder_duration_total", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "folder row shows '00:16' and '3 Videos'" + }, + { + "test": "computation_folder_badges_vlm", + "passed": true, + "message": "VLM: Q='On the 'Download' folder row of this video app's home screen, are BOTH a total-duration badge reading '00:16' AND a count reading '3 Videos' displayed?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: On the 'Download' folder row of this video app's home screen, are BOTH a total-duration badge reading '00:16' AND a count reading '3 Videos' displayed?", + "tag": "content" + }, + { + "test": "computation_speed_chip_2x", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "big value '2.0' after 2.0 chip" + }, + { + "test": "computation_speed_chip_2x_vlm", + "passed": true, + "message": "VLM: Q='Is the large playback-speed value near the top of this dialog showing '2.0'?' A=YES expect=YES", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Is the large playback-speed value near the top of this dialog showing '2.0'?", + "tag": "content" + }, + { + "test": "computation_speed_chip_half", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "big value '0.5' after 0.5 chip" + }, + { + "test": "computation_speed_stepper_plus", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "value 1.0 + 0.1 = 1.1 after '+'" + } + ] +} \ No newline at end of file diff --git a/android/anilbeesetti-nextplayer/tests/android_interaction_eval.json b/android/anilbeesetti-nextplayer/tests/android_interaction_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..4570568efbb4abd8219059310f9eb3d07c49d3e9 --- /dev/null +++ b/android/anilbeesetti-nextplayer/tests/android_interaction_eval.json @@ -0,0 +1,116 @@ +{ + "module": "interaction", + "total": 9, + "passed": 7, + "failed": 2, + "pass_rate": 0.7778, + "rule": { + "total": 6, + "passed": 4, + "failed": 2, + "pass_rate": 0.6667 + }, + "vlm": { + "total": 3, + "passed": 3, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.5, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 9, + "depth_ge1": 9, + "depth_ge2": 2, + "value": 9, + "vlm_fine": 3 + }, + "results": [ + { + "test": "interaction_network_url_roundtrip", + "passed": false, + "message": "behavior_wrong: URL field read None, expected 'http://test.mp4'", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "URL field holds 'http://test.mp4'; Cancel restores Home 'Download'" + }, + { + "test": "interaction_network_url_edit_clear", + "passed": false, + "message": "setup_failed: could not seed the field with 'http://test.mp4'", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "field 'http://test.mp4' -> '' and placeholder 'http://example.com/example.mp4' returns" + }, + { + "test": "interaction_search_filter_sequence_vlm", + "passed": true, + "message": "VLM: Q='Below the search box (which contains the text 'beta'), is there EXACTLY ONE video result row visible (a single thumbnail with a title beside it), rather than several rows or a folder list?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Below the search box (which contains the text 'beta'), is there EXACTLY ONE video result row visible (a single thumbnail with a title beside it), rather than several rows or a folder list?", + "tag": "position" + }, + { + "test": "interaction_search_filter_sequence", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "'beta' -> single 'beta_movie' row (alpha/gamma gone); clear -> 'Popular folders' section returns" + }, + { + "test": "interaction_search_query_clip", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "'clip' filters to exactly {alpha_clip}; beta_movie/gamma_reel absent" + }, + { + "test": "interaction_quicksettings_multichange_reorder", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "flat video rows alpha,beta,gamma -> gamma,beta,alpha after Grid+Z-A+Done" + }, + { + "test": "interaction_quicksettings_multichange_reorder_vlm", + "passed": true, + "message": "VLM: Q='Are the video thumbnails laid out in a multi-column GRID with at least two thumbnails positioned SIDE BY SIDE in the same row (rather than a single one-per-row column)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Are the video thumbnails laid out in a multi-column GRID with at least two thumbnails positioned SIDE BY SIDE in the same row (rather than a single one-per-row column)?", + "tag": "position" + }, + { + "test": "interaction_sort_toggle_integrity_vlm", + "passed": true, + "message": "VLM: Q='In this single-column list of three coloured video thumbnails, is the GREEN thumbnail ('Gamma') at the TOP and the RED thumbnail ('Alpha Clip') at the BOTTOM (i.e. green, blue, red top to bottom)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In this single-column list of three coloured video thumbnails, is the GREEN thumbnail ('Gamma') at the TOP and the RED thumbnail ('Alpha Clip') at the BOTTOM (i.e. green, blue, red top to bottom)?", + "tag": "position" + }, + { + "test": "interaction_sort_toggle_integrity", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "A-Z=alpha,beta,gamma; Z-A=gamma,beta,alpha; back to A-Z restores; all 3 rows intact throughout" + } + ] +} \ No newline at end of file diff --git a/android/anilbeesetti-nextplayer/tests/android_navigation_eval.json b/android/anilbeesetti-nextplayer/tests/android_navigation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..cbc4e359edb3267b2837b40cffeb3514db40c0c5 --- /dev/null +++ b/android/anilbeesetti-nextplayer/tests/android_navigation_eval.json @@ -0,0 +1,290 @@ +{ + "module": "navigation", + "total": 28, + "passed": 28, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 22, + "passed": 22, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 6, + "passed": 6, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.2727, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 28, + "depth_ge1": 28, + "depth_ge2": 19, + "value": 0, + "vlm_fine": 5 + }, + "results": [ + { + "test": "navigation_home_to_settings", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Settings category list ('Appearance') visible; Home 'Download' row gone" + }, + { + "test": "navigation_settings_rendered_vlm", + "passed": true, + "message": "VLM: Q='Is this a settings screen showing a vertical single-column list of category rows, each with a small leading icon on the left, and a back arrow at the top-left?' A=YES expect=YES", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is this a settings screen showing a vertical single-column list of category rows, each with a small leading icon on the left, and a back arrow at the top-left?", + "tag": "position" + }, + { + "test": "navigation_settings_to_appearance", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "'Dark theme' row visible; sibling 'Media library' row gone" + }, + { + "test": "navigation_appearance_back_to_settings", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Settings root restored ('Media library' back, 'Dark theme' gone) after one BACK" + }, + { + "test": "navigation_settings_to_media_library", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "'Mark last played media' row visible; sibling 'Appearance' row gone" + }, + { + "test": "navigation_settings_to_player_settings", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "'Material You controls' row visible; sibling 'Media library' row gone" + }, + { + "test": "navigation_settings_to_about", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "'by anilbeesetti' credit visible; sibling 'Media library' row gone" + }, + { + "test": "navigation_settings_to_audio", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "'Volume boost' row visible; sibling 'Media library' row gone" + }, + { + "test": "navigation_settings_to_subtitle", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "'Embedded styles' row visible; sibling 'Media library' row gone" + }, + { + "test": "navigation_settings_to_gestures", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "'Seek gesture' row visible; sibling 'Media library' row gone" + }, + { + "test": "navigation_home_to_folder", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "'Navigate up' + video rows visible; Home '3 Videos' badge gone" + }, + { + "test": "navigation_folder_to_player", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "player 'Play/Pause' control visible; folder 'Navigate up' gone" + }, + { + "test": "navigation_player_overlay_vlm", + "passed": true, + "message": "VLM: Q='Is there a play/pause control in the CENTRE of the screen and a horizontal seek bar in the LOWER part of the screen?' A=YES expect=YES", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is there a play/pause control in the CENTRE of the screen and a horizontal seek bar in the LOWER part of the screen?", + "tag": "position" + }, + { + "test": "navigation_player_back_to_folder", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "folder 'Navigate up' restored, player 'Play/Pause' gone after one BACK" + }, + { + "test": "navigation_folder_back_to_home", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Home '3 Videos' badge restored, folder 'Navigate up' gone after one BACK" + }, + { + "test": "navigation_home_to_search", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "'Popular folders' section visible; Home 'Menu' control gone" + }, + { + "test": "navigation_search_rendered_vlm", + "passed": true, + "message": "VLM: Q='Is there a search input field spanning the TOP of the screen (with a back arrow to its left), above the rest of the content?' A=YES expect=YES", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is there a search input field spanning the TOP of the screen (with a back arrow to its left), above the rest of the content?", + "tag": "position" + }, + { + "test": "navigation_search_back_to_home", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Home 'Menu' control restored, 'Popular folders' gone after BACK" + }, + { + "test": "navigation_fab_to_network_dialog", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "'Network Stream' title + URL EditText visible; pill 'Open local video' gone" + }, + { + "test": "navigation_network_dialog_cancel_home", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Home 'Download' restored, 'Network Stream' dialog gone after Cancel" + }, + { + "test": "navigation_player_to_speed_dialog", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "'Select playback speed' dialog visible; player 'Play/Pause' gone" + }, + { + "test": "navigation_speed_dialog_rendered_vlm", + "passed": true, + "message": "VLM: Q='Is a dialog titled about playback speed showing a grid of small rounded speed-value chips (like 0.5, 1.0, 2.0) arranged in rows?' A=YES expect=YES", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is a dialog titled about playback speed showing a grid of small rounded speed-value chips (like 0.5, 1.0, 2.0) arranged in rows?", + "tag": "shape" + }, + { + "test": "navigation_speed_dialog_back_to_player", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "player 'Play/Pause' reachable again, speed dialog gone after BACK" + }, + { + "test": "navigation_player_to_audio_dialog", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "'Select audio track' + 'Audio Track #1' visible; player 'Play/Pause' gone" + }, + { + "test": "navigation_audio_dialog_rendered_vlm", + "passed": true, + "message": "VLM: Q='Is a dialog titled about audio track showing a vertical list of selectable track options (one row highlighted/selected)?' A=YES expect=YES", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is a dialog titled about audio track showing a vertical list of selectable track options (one row highlighted/selected)?", + "tag": "layout" + }, + { + "test": "navigation_player_to_subtitle_dialog", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "'Select subtitle track' + 'Open local subtitle' visible; player 'Play/Pause' gone" + }, + { + "test": "navigation_subtitle_dialog_rendered_vlm", + "passed": true, + "message": "VLM: Q='Is a dialog titled about subtitle track showing two numeric stepper controls near the bottom (each with - and + buttons around a value)?' A=YES expect=YES", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is a dialog titled about subtitle track showing two numeric stepper controls near the bottom (each with - and + buttons around a value)?", + "tag": "shape" + }, + { + "test": "navigation_deep_chain_settings_player", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Player sub reached at depth 2; BACK->Settings root->Home unwinds each hop" + } + ] +} \ No newline at end of file diff --git a/android/anilbeesetti-nextplayer/tests/android_states_eval.json b/android/anilbeesetti-nextplayer/tests/android_states_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..dd326868f18c021041be370cc8045353b85b2f9e --- /dev/null +++ b/android/anilbeesetti-nextplayer/tests/android_states_eval.json @@ -0,0 +1,167 @@ +{ + "module": "states", + "total": 14, + "passed": 12, + "failed": 2, + "pass_rate": 0.8571, + "rule": { + "total": 5, + "passed": 4, + "failed": 1, + "pass_rate": 0.8 + }, + "vlm": { + "total": 9, + "passed": 8, + "failed": 1, + "pass_rate": 0.8889 + }, + "vlm_ratio": 1.8, + "audit": { + "kit_api_version": 1, + "existence": 1, + "liveness": 0, + "interactive": 13, + "depth_ge1": 13, + "depth_ge2": 8, + "value": 0, + "vlm_fine": 8 + }, + "results": [ + { + "test": "states_loop_advances", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Loop desc Loop: Off -> Loop: One (advanced one step)" + }, + { + "test": "states_loop_advances_vlm", + "passed": true, + "message": "VLM: Q='In the row of small player-control icons along the BOTTOM edge of the screen, is there a circular loop / repeat arrows icon?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In the row of small player-control icons along the BOTTOM edge of the screen, is there a circular loop / repeat arrows icon?", + "tag": "shape" + }, + { + "test": "states_loop_full_cycle", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Loop cycles Loop: One->...->Loop: One over 3 taps (full 3-state machine)" + }, + { + "test": "states_qs_grid_selected_vlm", + "passed": true, + "message": "VLM: Q='In the 'Media Layout' segmented control (the List / Grid pair), is the 'Grid' segment the highlighted/selected one — filled with a distinct accent background colour while 'List' is not?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In the 'Media Layout' segmented control (the List / Grid pair), is the 'Grid' segment the highlighted/selected one — filled with a distinct accent background colour while 'List' is not?", + "tag": "color" + }, + { + "test": "states_qs_videos_selected_vlm", + "passed": true, + "message": "VLM: Q='In the 'Media view mode' segmented control (Tree / Folders / Videos), is the 'Videos' segment the highlighted/selected one — filled with a distinct accent background colour — rather than 'Folders'?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In the 'Media view mode' segmented control (Tree / Folders / Videos), is the 'Videos' segment the highlighted/selected one — filled with a distinct accent background colour — rather than 'Folders'?", + "tag": "color" + }, + { + "test": "states_qs_folders_selected_vlm", + "passed": true, + "message": "VLM: Q='In the 'Media view mode' segmented control (Tree / Folders / Videos), is the 'Folders' segment the highlighted/selected one — filled with a distinct accent background colour — while Tree and Videos are not?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In the 'Media view mode' segmented control (Tree / Folders / Videos), is the 'Folders' segment the highlighted/selected one — filled with a distinct accent background colour — while Tree and Videos are not?", + "tag": "color" + }, + { + "test": "states_qs_videos_flattens", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Videos mode: 'Download' folder row gone; alpha_clip/beta_movie/gamma_reel at top level" + }, + { + "test": "states_qs_videos_flattens_vlm", + "passed": true, + "message": "VLM: Q='Does the main list show individual video items each with its own thumbnail and duration badge (a flat video list), rather than a single folder entry?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Does the main list show individual video items each with its own thumbnail and duration badge (a flat video list), rather than a single folder entry?", + "tag": "layout" + }, + { + "test": "states_dark_theme_on_subtitle", + "passed": false, + "message": "setup_failed: Appearance screen not reached", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "Dark theme subtitle 'System Default' -> 'On'" + }, + { + "test": "states_dark_theme_on_vlm", + "passed": false, + "message": "setup_failed: Appearance not reached", + "depth": 3, + "jump_kind": "none", + "tier": 0, + "expect": "", + "tag": "color" + }, + { + "test": "states_high_contrast_switch_vlm", + "passed": true, + "message": "VLM: Q='For the 'High contrast dark theme' row, is its toggle switch now in the ON position — the round thumb pushed to the RIGHT side of the track with the track filled in a solid accent colour?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: For the 'High contrast dark theme' row, is its toggle switch now in the ON position — the round thumb pushed to the RIGHT side of the track with the track filled in a solid accent colour?", + "tag": "color" + }, + { + "test": "states_dynamic_color_switch_vlm", + "passed": true, + "message": "VLM: Q='For the 'Dynamic color theme' row, is its toggle switch now in the OFF position — the round thumb pushed to the LEFT side of the track with the track NOT filled with an accent colour (gray/outline)?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: For the 'Dynamic color theme' row, is its toggle switch now in the OFF position — the round thumb pushed to the LEFT side of the track with the track NOT filled with an accent colour (gray/outline)?", + "tag": "color" + }, + { + "test": "states_dark_theme_persists", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "Dark theme subtitle STILL 'On' after leaving Appearance and re-entering" + }, + { + "test": "states_dark_theme_persists_vlm", + "passed": true, + "message": "VLM: Q='Is the app still using a DARK theme — a near-black or very dark background with light/white text?' A=YES expect=YES", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is the app still using a DARK theme — a near-black or very dark background with light/white text?", + "tag": "color" + } + ] +} \ No newline at end of file diff --git a/android/anilbeesetti-nextplayer/tests/android_structure_eval.json b/android/anilbeesetti-nextplayer/tests/android_structure_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..949693c664a973bb6bb5c6a7c4a7d631a9101fee --- /dev/null +++ b/android/anilbeesetti-nextplayer/tests/android_structure_eval.json @@ -0,0 +1,211 @@ +{ + "module": "structure", + "total": 19, + "passed": 19, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 11, + "passed": 11, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 8, + "passed": 8, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.7273, + "audit": { + "kit_api_version": 1, + "existence": 2, + "liveness": 0, + "interactive": 17, + "depth_ge1": 17, + "depth_ge2": 3, + "value": 0, + "vlm_fine": 6 + }, + "results": [ + { + "test": "structure_gate_launch", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_gate_home_vlm", + "passed": true, + "message": "VLM: Q='In the top app bar of this video app, are there exactly three icon buttons (a magnifier, a grid/menu icon, and a gear) on the right side, arranged in a single horizontal row?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the top app bar of this video app, are there exactly three icon buttons (a magnifier, a grid/menu icon, and a gear) on the right side, arranged in a single horizontal row?", + "tag": "position" + }, + { + "test": "structure_fab_expand", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "FAB action-pill labels 0->3 on expand" + }, + { + "test": "structure_fab_expand_vlm", + "passed": true, + "message": "VLM: Q='Are there exactly three rounded pill-shaped buttons stacked vertically near the bottom-right (labelled about network stream, local video, and recently played), each with a leading icon?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Are there exactly three rounded pill-shaped buttons stacked vertically near the bottom-right (labelled about network stream, local video, and recently played), each with a leading icon?", + "tag": "shape" + }, + { + "test": "structure_fab_collapse", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "FAB pills 3->0 on close (X)" + }, + { + "test": "structure_viewmode_folders_to_videos", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "RadioButton rows 1(folder)->3(videos); alpha/beta/gamma shown" + }, + { + "test": "structure_viewmode_folders_to_videos_vlm", + "passed": true, + "message": "VLM: Q='Is this a single-column vertical list of exactly three video items with red, blue and green thumbnails (top to bottom), rather than one folder entry?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is this a single-column vertical list of exactly three video items with red, blue and green thumbnails (top to bottom), rather than one folder entry?", + "tag": "color" + }, + { + "test": "structure_layout_grid", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "picker re-renders (List->Grid) with the 3 videos preserved" + }, + { + "test": "structure_layout_grid_vlm", + "passed": true, + "message": "VLM: Q='Are the video thumbnails arranged in a multi-column grid with at least two thumbnails positioned SIDE BY SIDE in the same row, rather than stacked one-per-row?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Are the video thumbnails arranged in a multi-column grid with at least two thumbnails positioned SIDE BY SIDE in the same row, rather than stacked one-per-row?", + "tag": "position" + }, + { + "test": "structure_enter_player", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "picker tree (Download/3 Videos) replaced by player (Play/Pause control)" + }, + { + "test": "structure_enter_player_vlm", + "passed": true, + "message": "VLM: Q='In this landscape video player, is there a play/pause control in the CENTRE of the screen and a horizontal seek bar near the BOTTOM edge?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In this landscape video player, is there a play/pause control in the CENTRE of the screen and a horizontal seek bar near the BOTTOM edge?", + "tag": "position" + }, + { + "test": "structure_quicksettings_sheet", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "0->5 sheet section headers + Done/Cancel row appear over Home" + }, + { + "test": "structure_quicksettings_sheet_vlm", + "passed": true, + "message": "VLM: Q='In this 'Quick Settings' bottom sheet, are the 'Cancel' and 'Done' text buttons positioned at the BOTTOM of the sheet, with 'Done' to the right of 'Cancel'?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In this 'Quick Settings' bottom sheet, are the 'Cancel' and 'Done' text buttons positioned at the BOTTOM of the sheet, with 'Done' to the right of 'Cancel'?", + "tag": "position" + }, + { + "test": "structure_settings_list", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Settings root is a 9-row category list" + }, + { + "test": "structure_settings_list_vlm", + "passed": true, + "message": "VLM: Q='Is this a vertical, single-column list of setting category rows (each row a leading icon plus a title and a smaller subtitle beneath it), with roughly nine such rows?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is this a vertical, single-column list of setting category rows (each row a leading icon plus a title and a smaller subtitle beneath it), with roughly nine such rows?", + "tag": "layout" + }, + { + "test": "structure_folder_drilldown", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "rows 1->3 and a 'Navigate up' back control appears" + }, + { + "test": "structure_search_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "'Popular folders' section -> 'Videos (1)' result row on typing 'beta'" + }, + { + "test": "structure_search_shape_vlm", + "passed": true, + "message": "VLM: Q='Below a search box containing the text 'beta', is there a section header reading 'Videos (1)' with exactly one video result row beneath it?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Below a search box containing the text 'beta', is there a section header reading 'Videos (1)' with exactly one video result row beneath it?", + "tag": "content" + }, + { + "test": "structure_network_stream_dialog", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "dialog adds 1 EditText + 4 markers over Home; Cancel restores Home" + } + ] +} \ No newline at end of file diff --git a/android/anilbeesetti-nextplayer/tests/android_testgen_kit.py b/android/anilbeesetti-nextplayer/tests/android_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6 --- /dev/null +++ b/android/anilbeesetti-nextplayer/tests/android_testgen_kit.py @@ -0,0 +1,1910 @@ +#!/usr/bin/env python3 +"""Android TestGen Kit — the single source of every test helper, so a test's +NAVIGATION 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 package +name differs): always use the module-level PACKAGE (argv[1]). Never write a package +name, an .apk path, a /data/data path, or a pixel coordinate as a literal. + python3 android_testgen_kit.py lint_sources # flags all of those + +SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery): + python3 android_testgen_kit.py audit + python3 android_testgen_kit.py lint + python3 android_testgen_kit.py lint_sources + python3 android_testgen_kit.py audit_depth [results_dir] +""" +from __future__ import annotations + +import ast +import base64 +import functools +import glob +import hashlib +import json +import math +import os +import re +import shlex +import subprocess +import sys +import time +import urllib.error +import 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.0 +SETTLE = { + "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 /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 " list[dict]: + """XML -> list of attribute dicts, each with _bounds and _center.""" + nodes = [] + for m in re.finditer(r"]+?)/?>", 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} \n" + " android_testgen_kit.py audit_depth [results_dir]\n" + " android_testgen_kit.py score [manifest_dir]") diff --git a/android/anilbeesetti-nextplayer/tests/android_text_eval.json b/android/anilbeesetti-nextplayer/tests/android_text_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..f25ad6edffe8b12afdc03e54fdb8406e30d40019 --- /dev/null +++ b/android/anilbeesetti-nextplayer/tests/android_text_eval.json @@ -0,0 +1,224 @@ +{ + "module": "text", + "total": 21, + "passed": 17, + "failed": 4, + "pass_rate": 0.8095, + "rule": { + "total": 18, + "passed": 14, + "failed": 4, + "pass_rate": 0.7778 + }, + "vlm": { + "total": 3, + "passed": 3, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.1667, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 21, + "depth_ge1": 19, + "depth_ge2": 12, + "value": 2, + "vlm_fine": 0 + }, + "results": [ + { + "test": "text_search_beta_header", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "header 'Videos (1)' and result row 'beta_movie' after typing 'beta'" + }, + { + "test": "text_search_beta_header_vlm", + "passed": true, + "message": "VLM: Q='Is a header reading exactly 'Videos (1)' shown near the top of the search results, directly above one result row?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is a header reading exactly 'Videos (1)' shown near the top of the search results, directly above one result row?", + "tag": "content" + }, + { + "test": "text_search_gamma_row", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "header 'Videos (1)' and result row 'gamma_reel' after typing 'gamma'" + }, + { + "test": "text_search_substring_movie", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "header 'Videos (1)' and row 'beta_movie' after typing 'movie'" + }, + { + "test": "text_search_empty_state", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "'No results found' shown (and no 'Videos (N)' header) for a non-matching query" + }, + { + "test": "text_player_title_beta", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "player top-bar title reads 'beta_movie.mp4' (with the .mp4 extension)" + }, + { + "test": "text_player_title_beta_vlm", + "passed": true, + "message": "VLM: Q='Is the text 'beta_movie.mp4' shown as a title in the top bar of the video player, to the right of a back arrow?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is the text 'beta_movie.mp4' shown as a title in the top bar of the video player, to the right of a back arrow?", + "tag": "content" + }, + { + "test": "text_player_title_gamma", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "player top-bar title reads 'gamma_reel.mp4' (with the .mp4 extension)" + }, + { + "test": "text_player_title_alpha", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "player top-bar title reads 'alpha_clip.mp4' (with the .mp4 extension)" + }, + { + "test": "text_loop_desc_advances", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Loop button content-desc changed from 'Loop: One' to 'Loop: All' after one tap" + }, + { + "test": "text_home_folder_labels", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "Home folder row shows 'Download' and count chip '3 Videos'" + }, + { + "test": "text_home_folder_labels_vlm", + "passed": true, + "message": "VLM: Q='Is a folder entry labeled 'Download' shown together with a small badge/chip reading '3 Videos' on the same row?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Is a folder entry labeled 'Download' shown together with a small badge/chip reading '3 Videos' on the same row?", + "tag": "content" + }, + { + "test": "text_folder_video_path", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "each video row shows the path '/storage/emulated/0/Download'" + }, + { + "test": "text_folder_titles_no_extension", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "picker row reads 'beta_movie' (no extension), unlike the player's 'beta_movie.mp4'" + }, + { + "test": "text_settings_controller_timeout", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "the 'Controller timeout' row's subtitle reads '4 seconds'" + }, + { + "test": "text_settings_default_speed", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "the 'Default playback speed' row's subtitle reads '1.0'" + }, + { + "test": "text_settings_dark_theme_subtitle", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "the 'Dark theme' row's subtitle reads 'System Default' (default)" + }, + { + "test": "text_about_credit_and_rows", + "passed": false, + "message": "setup_failed: About subscreen not reached", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "'by anilbeesetti', 'Libraries', 'Github' all present" + }, + { + "test": "text_about_upi_handle", + "passed": false, + "message": "setup_failed: About subscreen not reached", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "UPI row subtitle 'anilbeesetti10@oksbi'" + }, + { + "test": "text_network_dialog_label_placeholder", + "passed": false, + "message": "setup_failed: Network Stream dialog not reached via the FAB", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "label 'Enter a network URL:' + placeholder 'http://example.com/example.mp4'" + }, + { + "test": "text_network_url_reads_back", + "passed": false, + "message": "setup_failed: Network Stream dialog not reached via the FAB", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "field reads back the typed URL" + } + ] +} \ No newline at end of file diff --git a/android/anilbeesetti-nextplayer/tests/conftest.py b/android/anilbeesetti-nextplayer/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27 --- /dev/null +++ b/android/anilbeesetti-nextplayer/tests/conftest.py @@ -0,0 +1 @@ +pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"] diff --git a/android/anilbeesetti-nextplayer/tests/requirements.txt b/android/anilbeesetti-nextplayer/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c --- /dev/null +++ b/android/anilbeesetti-nextplayer/tests/requirements.txt @@ -0,0 +1,2 @@ +pytest +pillow diff --git a/android/anilbeesetti-nextplayer/tests/test_android_computation.py b/android/anilbeesetti-nextplayer/tests/test_android_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..798eb1a3957deb2fa1b9176feda2e121057869e0 --- /dev/null +++ b/android/anilbeesetti-nextplayer/tests/test_android_computation.py @@ -0,0 +1,677 @@ +#!/usr/bin/env python3 +"""COMPUTATION lane for NextPlayer (package = argv[1]; NEVER a literal). + +This lane owns input -> output VALUE tests: a user feeds an input through the real +UI path and the app DERIVES a specific value that we read back and assert against +the value OBSERVED on the running original (never computed here, never read from +source). It is the sole owner of jump_kind="value". + +The app is a video player, so its "computations" are: + + A) SEARCH FILTER COUNT (Home -> Search icon -> type a query -> the results screen + shows a header "Videos (N)" / "Folders (N)" and the matching rows). The count + and which rows appear are DERIVED from the query against the 3 fixture videos. + Ground truth OBSERVED on the original: + "beta" -> Videos (1), row beta_movie (alpha/gamma absent) + "gamma" -> Videos (1), row gamma_reel + "clip" -> Videos (1), row alpha_clip (matches alpha_clip's title) + "movie" -> Videos (1), row beta_movie + "a" -> Folders (1) + Videos (3), all three rows (substring in all) + "_" -> Videos (3), all three rows, NO Folders header (folder name has no '_') + "zzzznomatch" -> NO Videos/Folders header, none of the three rows + The strongest, most robust value surface, so several variants live here. + + B) PLAYBACK-SPEED dialog (Player -> speed icon -> "Select playback speed"): a big + current-value TextView, a chip grid (0.2 .. 4.0), and a -/+ stepper. OBSERVED: + tapping the "2.0" chip sets the big value to "2.0", the "0.5" chip to "0.5"; + the "+" stepper increments by 0.1. depth=3 (folder -> player -> dialog). The + dialog opens at the app's REMEMBERED speed (Remember selections persists it), + so chip tests assert the ABSOLUTE value (chip-independent of the start) and + the stepper test asserts start + 0.1 read off the SAME dialog. + + C) FOLDER DURATION AGGREGATE (Home): the Download folder row shows a total + duration badge derived from its 3 clips (00:05 + 00:08 + 00:03 = "00:16") and + a "3 Videos" count chip. depth=0, a derived aggregate value. + +The speed VALUE, the search COUNT header, and the folder duration are all plain +TEXT in the tree, so every core assertion is a rule (dump) assertion; VLM is used +for exactly three rendered-property confirmations as OR-companions. + +Fixtures: the 3 sample videos (alpha_clip.mp4 / beta_movie.mp4 / gamma_reel.mp4) +are authored into fixtures/ and mirrored to the device by push_fixtures() (called +by run_suite()); every test reaches them through the picker, never a pushed path. +""" +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +require_kit(1) + +# ── Ground-truth constants (strings/values OBSERVED on the running original) ───── +FOLDER_NAME = "Download" +VIDEO_TITLES = ("alpha_clip", "beta_movie", "gamma_reel") +FIXTURE_VIDEOS = ("alpha_clip.mp4", "beta_movie.mp4", "gamma_reel.mp4") +PLAYER_MARKER = "Play/Pause" # content-desc unique to the player +SPEED_DIALOG_TITLE = "Select playback speed" +FOLDER_TOTAL_DURATION = "00:16" # 00:05 + 00:08 + 00:03, observed +FOLDER_COUNT_CHIP = "3 Videos" +SPEED_STEP = 0.1 # observed "+"/"−" increment + + +# ══════════════════════════════════════════════════════════════════════════════ +# Setup / navigation helpers. Navigation helpers are named and_enter_* / +# and_reach_* so an and_enter() call backs every declared depth>=1 (audit_depth). +# ══════════════════════════════════════════════════════════════════════════════ + +def and_grant_media(): + """Tap the runtime media-permission 'Allow all' if it is showing (no-op + otherwise). restart_app() keeps the grant, so this is only a safety net.""" + for label in ("Allow all", "While using the app", "Allow"): + n = find_node_ci(ui(), label) + if n: + tap_node(n) + settle("tap") + return True + return False + + +def _home_ready(nodes): + """True once the Home picker has actually rendered its media list.""" + return bool(find_node(nodes, text=FOLDER_NAME)) or any( + find_node(nodes, text=t) for t in VIDEO_TITLES) + + +def home_ready(): + """Mirror fixtures, restart (keeps the media grant), wait until Home actually + rendered, return fresh Home nodes. Retries the launch once.""" + push_fixtures() + _ = [fixture_on_device(v) for v in FIXTURE_VIDEOS] # explicit dependency + nodes = [] + for _attempt in range(2): + restart_app() + if not wait_for_foreground(): + continue + and_grant_media() + for _ in range(6): + nodes = ui() + if _home_ready(nodes): + return nodes + settle("dump") + if _home_ready(nodes): + break + return nodes + + +def tap_topbar(nodes, desc): + """Tap a top-bar icon by content-desc. The desc node itself is not clickable — + its parent View is — so tap the tightest clickable ancestor by bounds + containment, falling back to the desc node's centre.""" + target = find_node(nodes, content_desc=desc) + if not target or "_bounds" not in target: + return False + tcx, tcy = target["_center"] + best, best_area = None, None + for n in nodes: + if n.get("clickable") != "true" or "_bounds" not in n: + continue + x1, y1, x2, y2 = n["_bounds"] + if x1 <= tcx <= x2 and y1 <= tcy <= y2: + area = (x2 - x1) * (y2 - y1) + if best_area is None or area < best_area: + best, best_area = n, area + return tap_node(best) if best else tap_node(target) + + +def find_folder_row(nodes): + """The TIGHTEST clickable node that contains the 'Download' label — the tappable + row, never the full-screen root container. Falls back to the smallest bounded + (non-full-screen) container, then to the label node itself.""" + label = find_node(nodes, text=FOLDER_NAME) + if not label or "_bounds" not in label: + return None + lx, ly = label["_center"] + s = get_screen_info() + clickable_best, clickable_area = None, None + box_best, box_area = None, None + for n in nodes: + b = n.get("_bounds") + if not b: + continue + x1, y1, x2, y2 = b + if not (x1 <= lx <= x2 and y1 <= ly <= y2): + continue + w, h = x2 - x1, y2 - y1 + if w < 200 or h < 60: + continue + # never the whole screen (the root container swallows every tap) + if w >= s["width"] and h >= int(s["height"] * 0.8): + continue + area = w * h + if n.get("clickable") == "true": + if clickable_area is None or area < clickable_area: + clickable_best, clickable_area = n, area + if box_area is None or area < box_area: + box_best, box_area = n, area + return clickable_best or box_best or label + + +def _headers(nodes): + """Every 'Videos (N)' / 'Folders (N)' header string currently on screen.""" + out = [] + for n in find_by_class(nodes, "TextView"): + t = n.get("text", "").strip() + if t.startswith("Videos (") or t.startswith("Folders ("): + out.append(t) + return out + + +def _videos_header(headers): + for h in headers: + if h.startswith("Videos ("): + return h + return "" + + +def and_reach_search(nodes): + """Home -> tap the Search top-bar icon -> Search screen (an EditText appears). + Proves the jump and counts one surface. Returns fresh search nodes or []. + + The topbar tap occasionally lands before the icon is laid out, so it is + retried (re-dumping Home between tries) until the search EditText appears.""" + for _ in range(3): + if not tap_topbar(nodes, "Search"): + nodes = ui() + continue + settle("tap") + after_nodes = ui() + if find_by_class(after_nodes, "EditText"): + and_enter("search") + return after_nodes + nodes = ui() + if not find_node(nodes, content_desc="Search"): + break # navigated elsewhere; bail + return [] + + +def run_search(query): + """Home -> Search -> type `query` -> return (fresh result nodes, headers list). + Retries the whole reach+type once, because the very first search after a fresh + launch can miss the search-icon tap (observed as a lone transient flake).""" + for _attempt in range(2): + home = home_ready() + snodes = and_reach_search(home) + if snodes: + eds = find_by_class(snodes, "EditText") + if eds and type_text(eds[0], query): + settle("keyboard") + r = ui() + return r, _headers(r) + and_reset_depth() + return None, [] + + +# ── Player / speed-dialog helpers (depth family) ──────────────────────────────── + +def dump_center(nodes): + """Centre of the CURRENT display in the dump's own (rotated) coordinate frame. + The player is landscape but `wm size` still reports portrait, so + get_screen_info() cannot be trusted there; the dump's root bounds are correct.""" + maxx = max((b[2] for b in (n.get("_bounds") for n in nodes) if b), default=0) + maxy = max((b[3] for b in (n.get("_bounds") for n in nodes) if b), default=0) + return (maxx // 2, maxy // 2) if maxx and maxy else (0, 0) + + +def raw_tap_node(node): + """Tap a node's centre with a RAW `input tap`, bypassing tap_node's bounds + check. In the landscape PlayerActivity, get_screen_info() reports the portrait + size (wm size never rotates), so tap_node wrongly rejects any x beyond the + portrait width — every chip/stepper in the landscape speed dialog. This taps + the real (rotated) coordinate directly.""" + if not node or "_center" not in node: + return False + x, y = node["_center"] + adb_shell("input", "tap", int(x), int(y)) + settle("tap") + return True + + +def reveal_player_controls(): + """Tap the (rotated) centre until the auto-hiding controls are up. Returns + fresh player nodes once 'Play/Pause' is present, else the last dump.""" + for _ in range(8): + nodes = ui() + if find_node(nodes, content_desc=PLAYER_MARKER): + return nodes + cx, cy = dump_center(nodes) + if not cx: + break + tap(cx, cy) + time.sleep(0.25) + return ui() + + +def _loop_node(nodes): + for n in nodes: + if (n.get("content-desc", "") or "").startswith("Loop"): + return n + return None + + +def _topright_icons(nodes): + """The four top-right icon Buttons in the player, sorted left->right. Index 1 + (2nd from left) is the playback-speed icon (observed).""" + cx = dump_center(nodes)[0] + btns = [n for n in nodes if "Button" in n.get("class", "") and "_bounds" in n + and n["_bounds"][1] < 230 and n["_bounds"][0] > cx] + btns.sort(key=lambda n: n["_bounds"][0]) + return btns + + +def and_enter_player(title="beta_movie"): + """Home -> Download folder -> tap a video row -> PlayerActivity (autoplays). + Enables Loop so the short clip keeps replaying (never exits mid-test), reveals + the controls, and counts TWO surfaces (folder, player). Returns player nodes + or [].""" + home = home_ready() + if not find_node(home, text=FOLDER_NAME): + return [] + # Open the folder and CONFIRM it opened (the video rows appear). The row tap can + # miss on the first go, so retry from a fresh Home a couple of times. + fnodes = [] + for _ in range(3): + folder = find_folder_row(home) or find_node(home, text=FOLDER_NAME) + tap_node(folder) + settle("tap") + fnodes = ui() + if find_node(fnodes, text=title) or find_node(fnodes, content_desc="Navigate up"): + break + home = home_ready() + if not find_node(fnodes, text=title): + return [] + and_enter("folder") # surface 1 + row = find_node(fnodes, text=title) + before = and_showing(fnodes) + tap_node(row) + settle("launch") # PlayerActivity + autoplay + import android_testgen_kit as _kit + _kit._screen_info = None # invalidate wrong geometry + pnodes = reveal_player_controls() + if not (find_node(pnodes, content_desc=PLAYER_MARKER) or and_reach( + before, and_showing(pnodes), PLAYER_MARKER, source=None)): + return [] + and_enter("player") # surface 2 + ln = _loop_node(pnodes) + if ln and ln.get("content-desc") == "Loop: Off": + raw_tap_node(ln) # keep the clip alive + time.sleep(0.3) + pnodes = reveal_player_controls() + return pnodes + + +def and_reach_speed_dialog(): + """Player -> tap the speed icon (top-right, 2nd from left) -> the 'Select + playback speed' dialog. Counts a THIRD surface. Returns fresh dialog nodes or []. + + The player controls auto-hide within ~a second, faster than a dump+tap round + trip, so a naive reveal-then-tap loses the race often. This caches the speed + icon's coordinate the first time controls are up, then repeatedly [taps centre + to re-reveal, immediately taps the CACHED coordinate] — no dump between the + reveal tap and the button tap — checking for the dialog after each. This is the + sequence observed to open the dialog reliably within the retry budget.""" + pnodes = and_enter_player("beta_movie") + if not pnodes: + return [] + speed_xy = None + for attempt in range(24): + pnodes = reveal_player_controls() + icons = _topright_icons(pnodes) + if len(icons) >= 2: + speed_xy = icons[1]["_center"] # refresh the cached coord + if speed_xy is None: + time.sleep(0.3) + continue + cx, cy = speed_xy + adb_shell("input", "tap", cx, cy) # immediate, no dump in between + time.sleep(0.9) + d = ui() + if find_node(d, text=SPEED_DIALOG_TITLE): + and_enter("speed_dialog") # surface 3 + return d + return [] + + +def speed_big_value(nodes): + """The big current-speed value: the numeric TextView above the chip grid. + Chips sit at y>=400; the value sits near y~200, so filter on y<300.""" + for n in find_by_class(nodes, "TextView"): + t = n.get("text", "").strip() + if (t and all(c.isdigit() or c == "." for c in t) + and n.get("_bounds") and n["_bounds"][1] < 300): + return t + return "" + + +def read_speed_value(retries=4): + """Read the big speed value from a FRESH dump, re-dumping until it is a parseable + number. The value TextView updates a beat after a tap, so a single early dump + can catch the stale text — poll a few times.""" + val = "" + for _ in range(retries): + val = speed_big_value(ui()) + if val: + try: + float(val) + return val + except ValueError: + pass + settle("dump") + return val + + +def speed_chip(nodes, label): + """A speed chip (numeric TextView in the chip grid, y>=400).""" + for n in find_by_class(nodes, "TextView"): + if (n.get("text", "").strip() == label + and n.get("_bounds") and n["_bounds"][1] >= 400): + return n + return None + + +def speed_steppers(nodes): + """The -/+ Buttons flanking the big value (y ~169-295), sorted left->right so + [0] is minus and [-1] is plus.""" + bs = [n for n in nodes if "Button" in n.get("class", "") and "_bounds" in n + and 150 < n["_bounds"][1] < 310 and (n["_bounds"][3] - n["_bounds"][1]) < 160] + bs.sort(key=lambda n: n["_center"][0]) + return bs + + +def _num_eq(a, b, tol=0.001): + try: + return abs(float(a) - float(b)) <= tol + except (TypeError, ValueError): + return False + + +# ══════════════════════════════════════════════════════════════════════════════ +# A) SEARCH FILTER COUNT — the strongest value surface. depth=1, jump_kind=value. +# Each test asserts the EXACT header count AND the exact rows present/absent. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_search_beta_count", "computation_search_beta_vlm")) +def test_search_beta(): + r, headers = run_search("beta") + if r is None: + record("computation_search_beta_count", False, + "setup_failed: could not reach the search results screen", + depth=1, jump_kind="value", expect="header 'Videos (1)'") + else: + vh = _videos_header(headers) + has_beta = bool(find_node(r, text="beta_movie")) + no_others = not find_node(r, text="alpha_clip") and not find_node(r, text="gamma_reel") + ok = vh == "Videos (1)" and has_beta and no_others + record("computation_search_beta_count", ok, + "" if ok else f"behavior_wrong: header={vh!r} beta={has_beta} " + f"others_absent={no_others}, expected 'Videos (1)' + only beta_movie", + depth=1, jump_kind="value", expect="header 'Videos (1)', row beta_movie only") + vlm_assert("computation_search_beta", + "In this search results screen, is there exactly ONE video result " + "row, and does its title read 'beta_movie'?", + RESULTS_DIR, depth=1, jump_kind="value", tag="content") + + +@and_test(expects=("computation_search_gamma_count",)) +def test_search_gamma(): + r, headers = run_search("gamma") + if r is None: + record("computation_search_gamma_count", False, + "setup_failed: could not reach the search results screen", + depth=1, jump_kind="value", expect="header 'Videos (1)'") + return + vh = _videos_header(headers) + has_gamma = bool(find_node(r, text="gamma_reel")) + no_others = not find_node(r, text="alpha_clip") and not find_node(r, text="beta_movie") + ok = vh == "Videos (1)" and has_gamma and no_others + record("computation_search_gamma_count", ok, + "" if ok else f"behavior_wrong: header={vh!r} gamma={has_gamma} " + f"others_absent={no_others}, expected 'Videos (1)' + only gamma_reel", + depth=1, jump_kind="value", expect="header 'Videos (1)', row gamma_reel only") + + +@and_test(expects=("computation_search_clip_count",)) +def test_search_clip(): + # "clip" is a substring of alpha_clip's title only. + r, headers = run_search("clip") + if r is None: + record("computation_search_clip_count", False, + "setup_failed: could not reach the search results screen", + depth=1, jump_kind="value", expect="header 'Videos (1)'") + return + vh = _videos_header(headers) + has_alpha = bool(find_node(r, text="alpha_clip")) + no_others = not find_node(r, text="beta_movie") and not find_node(r, text="gamma_reel") + ok = vh == "Videos (1)" and has_alpha and no_others + record("computation_search_clip_count", ok, + "" if ok else f"behavior_wrong: header={vh!r} alpha={has_alpha} " + f"others_absent={no_others}, expected 'Videos (1)' + only alpha_clip", + depth=1, jump_kind="value", expect="header 'Videos (1)', row alpha_clip only") + + +@and_test(expects=("computation_search_movie_count",)) +def test_search_movie(): + r, headers = run_search("movie") + if r is None: + record("computation_search_movie_count", False, + "setup_failed: could not reach the search results screen", + depth=1, jump_kind="value", expect="header 'Videos (1)'") + return + vh = _videos_header(headers) + has_beta = bool(find_node(r, text="beta_movie")) + no_others = not find_node(r, text="alpha_clip") and not find_node(r, text="gamma_reel") + ok = vh == "Videos (1)" and has_beta and no_others + record("computation_search_movie_count", ok, + "" if ok else f"behavior_wrong: header={vh!r} beta={has_beta} " + f"others_absent={no_others}, expected 'Videos (1)' + only beta_movie", + depth=1, jump_kind="value", expect="header 'Videos (1)', row beta_movie only") + + +@and_test(expects=("computation_search_multi_count",)) +def test_search_multi(): + # "a" is a substring in ALL three titles -> Videos (3) plus a Folders (1). + r, headers = run_search("a") + if r is None: + record("computation_search_multi_count", False, + "setup_failed: could not reach the search results screen", + depth=1, jump_kind="value", expect="header 'Videos (3)'") + return + vh = _videos_header(headers) + all_present = all(find_node(r, text=t) for t in VIDEO_TITLES) + ok = vh == "Videos (3)" and all_present + record("computation_search_multi_count", ok, + "" if ok else f"behavior_wrong: header={vh!r} all_rows={all_present}, " + f"expected 'Videos (3)' + all three rows", + depth=1, jump_kind="value", expect="header 'Videos (3)', all three rows") + + +@and_test(expects=("computation_search_underscore_count",)) +def test_search_underscore(): + # "_" is in every FILE title but NOT in the folder name -> Videos (3), NO Folders header. + r, headers = run_search("_") + if r is None: + record("computation_search_underscore_count", False, + "setup_failed: could not reach the search results screen", + depth=1, jump_kind="value", expect="header 'Videos (3)'") + return + vh = _videos_header(headers) + all_present = all(find_node(r, text=t) for t in VIDEO_TITLES) + no_folder = not any(h.startswith("Folders (") for h in headers) + ok = vh == "Videos (3)" and all_present and no_folder + record("computation_search_underscore_count", ok, + "" if ok else f"behavior_wrong: headers={headers} all_rows={all_present} " + f"no_folder={no_folder}, expected 'Videos (3)', all rows, no Folders header", + depth=1, jump_kind="value", expect="header 'Videos (3)', all rows, no Folders header") + + +@and_test(expects=("computation_search_nomatch_count",)) +def test_search_nomatch(): + # A query matching nothing -> no Videos/Folders header, none of the three rows. + r, headers = run_search("zzzznomatch") + if r is None: + record("computation_search_nomatch_count", False, + "setup_failed: could not reach the search results screen", + depth=1, jump_kind="value", expect="no video result rows") + return + any_row = any(find_node(r, text=t) for t in VIDEO_TITLES) + no_videos_header = not any(h.startswith("Videos (") for h in headers) + ok = (not any_row) and no_videos_header + record("computation_search_nomatch_count", ok, + "" if ok else f"behavior_wrong: headers={headers} any_row={any_row}, " + f"expected no Videos header and none of the three rows", + depth=1, jump_kind="value", expect="no Videos header, zero result rows") + + +# ══════════════════════════════════════════════════════════════════════════════ +# C) FOLDER DURATION AGGREGATE — derived total on the Home folder row. depth=0. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_folder_duration_total", "computation_folder_badges_vlm")) +def test_folder_duration_total(): + nodes = home_ready() + have_total = bool(find_node(nodes, text=FOLDER_TOTAL_DURATION)) + have_count = bool(find_node(nodes, text=FOLDER_COUNT_CHIP)) + have_folder = bool(find_node(nodes, text=FOLDER_NAME)) + ok = have_total and have_count and have_folder + if not have_folder: + msg = "setup_failed: Download folder row not visible (fixtures not scanned?)" + elif not (have_total and have_count): + msg = (f"behavior_wrong: folder row badges total={have_total} " + f"count={have_count}, expected '{FOLDER_TOTAL_DURATION}' and " + f"'{FOLDER_COUNT_CHIP}'") + else: + msg = "" + record("computation_folder_duration_total", ok, msg, + depth=0, jump_kind="value", + expect=f"folder row shows '{FOLDER_TOTAL_DURATION}' and '{FOLDER_COUNT_CHIP}'") + + vlm_assert("computation_folder_badges", + "On the 'Download' folder row of this video app's home screen, are " + "BOTH a total-duration badge reading '00:16' AND a count reading " + "'3 Videos' displayed?", + RESULTS_DIR, depth=0, jump_kind="value", tag="content") + + +# ══════════════════════════════════════════════════════════════════════════════ +# B) PLAYBACK-SPEED dialog — input chip/stepper -> output value. depth=3. +# Backed by and_reach_speed_dialog() (depth family). The dialog opens at the +# app's remembered speed, so chip tests assert the ABSOLUTE value the chip sets +# (start-independent) and the stepper test asserts start + 0.1 read off the same +# dialog. One VLM companion reads the big rendered value after the "2.0" chip. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_speed_chip_2x", "computation_speed_chip_2x_vlm")) +def test_speed_chip_2x(): + d = and_reach_speed_dialog() + if not d: + record("computation_speed_chip_2x", False, + "setup_failed: could not open the playback-speed dialog", + depth=3, jump_kind="value", expect="big value '2.0'") + vlm_assert("computation_speed_chip_2x", + "Is the large playback-speed value near the top of this dialog " + "showing '2.0'?", + RESULTS_DIR, depth=3, jump_kind="value", tag="content") + return + chip = speed_chip(d, "2.0") + if not chip: + record("computation_speed_chip_2x", False, + "feature_missing: no '2.0' speed chip in the dialog", + depth=3, jump_kind="value", expect="big value '2.0'") + else: + raw_tap_node(chip) + got = read_speed_value() + ok = _num_eq(got, "2.0") + record("computation_speed_chip_2x", ok, + "" if ok else f"behavior_wrong: big value shows {got!r} after tapping " + f"the '2.0' chip, expected '2.0'", + depth=3, jump_kind="value", expect="big value '2.0' after 2.0 chip") + vlm_assert("computation_speed_chip_2x", + "Is the large playback-speed value near the top of this dialog " + "showing '2.0'?", + RESULTS_DIR, depth=3, jump_kind="value", tag="content") + + +@and_test(expects=("computation_speed_chip_half",)) +def test_speed_chip_half(): + d = and_reach_speed_dialog() + if not d: + record("computation_speed_chip_half", False, + "setup_failed: could not open the playback-speed dialog", + depth=3, jump_kind="value", expect="big value '0.5'") + return + chip = speed_chip(d, "0.5") + if not chip: + record("computation_speed_chip_half", False, + "feature_missing: no '0.5' speed chip in the dialog", + depth=3, jump_kind="value", expect="big value '0.5'") + return + raw_tap_node(chip) + got = read_speed_value() + ok = _num_eq(got, "0.5") + record("computation_speed_chip_half", ok, + "" if ok else f"behavior_wrong: big value shows {got!r} after tapping the " + f"'0.5' chip, expected '0.5'", + depth=3, jump_kind="value", expect="big value '0.5' after 0.5 chip") + + +@and_test(expects=("computation_speed_stepper_plus",)) +def test_speed_stepper_plus(): + # The "+" stepper increments the big value by 0.1 (observed). Read the starting + # value off THIS dialog (it opens at the remembered speed), tap +, assert +0.1. + d = and_reach_speed_dialog() + if not d: + record("computation_speed_stepper_plus", False, + "setup_failed: could not open the playback-speed dialog", + depth=3, jump_kind="value", expect="value increases by 0.1") + return + # Anchor to a known chip first so the start value is deterministic (1.0). + anchor = speed_chip(d, "1.0") + if anchor: + raw_tap_node(anchor) + start = read_speed_value() + steppers = speed_steppers(ui()) + if not start or len(steppers) < 2: + record("computation_speed_stepper_plus", False, + "feature_missing: could not read start value or find the +/- stepper", + depth=3, jump_kind="value", expect="value increases by 0.1") + return + plus = steppers[-1] + raw_tap_node(plus) + got = read_speed_value() + expected = round(float(start) + SPEED_STEP, 4) + ok = _num_eq(got, expected) + record("computation_speed_stepper_plus", ok, + "" if ok else f"behavior_wrong: value {start!r} -> {got!r} after '+', " + f"expected {expected}", + depth=3, jump_kind="value", + expect=f"value {start} + {SPEED_STEP} = {expected} after '+'") + + +TESTS = [ + test_search_beta, + test_search_gamma, + test_search_clip, + test_search_movie, + test_search_multi, + test_search_underscore, + test_search_nomatch, + test_folder_duration_total, + test_speed_chip_2x, + test_speed_chip_half, + test_speed_stepper_plus, +] + + +if __name__ == "__main__": + run_suite(TESTS, "computation") diff --git a/android/anilbeesetti-nextplayer/tests/test_android_interaction.py b/android/anilbeesetti-nextplayer/tests/test_android_interaction.py new file mode 100644 index 0000000000000000000000000000000000000000..6b0012090029bd841a259d1581542ef17378d700 --- /dev/null +++ b/android/anilbeesetti-nextplayer/tests/test_android_interaction.py @@ -0,0 +1,1006 @@ +#!/usr/bin/env python3 +"""INTERACTION lane for NextPlayer (dev.anilbeesetti.nextplayer.debug). + +EFFECT-BY-CONSEQUENCE on user DATA. This lane owns CRUD-style data operations, +3+-step sequences where each step depends on the last, multi-record integrity, +DATA persistence across PROCESS DEATH, and (sole owner) LONG-PRESS / context +menus. Every assertion reads the CONSEQUENCE of a multi-step user action back out +of a FRESH ui() and compares it to what was observed on the running original. + +Why CONSEQUENCE, never the attr: Compose a11y on this app does NOT expose +toggle/selection state — every Switch/segment/chip reports checked=false +selected=false regardless of visual state, and tapping a switch does not flip +`checked`. So we never assert checked/selected; we assert the DATA that CHANGED +(row text / row order / selection-count text / a placeholder returning / a +persisted layout surviving relaunch), or hand the truly rendered-only consequence +(a selection highlight, a played-progress bar, a persisted grid) to the VLM. + +Ground truth — EVERY value below was observed on the running original before +authoring (probes + recon.md + recon_shots/): + * Network Stream dialog (FAB -> "Open network stream"): typing "http://test.mp4" + into its EditText makes the field's `text` read exactly that; backspace- + clearing empties it and restores the placeholder "http://example.com/example.mp4"; + Cancel dismisses the dialog and Home ("Download") returns. + * Search: typing "beta" -> header "Videos (1)" + one row "beta_movie"; clearing + returns the "Popular folders" section. "clip" -> exactly one row "alpha_clip" + and neither beta_movie nor gamma_reel. + * Quick Settings multi-change (Videos view): Grid + Z-A + Done reverses the flat + video order alpha,beta,gamma -> gamma,beta,alpha AND lays them out as a grid. + This survives force_stop_and_relaunch() (process death) — still Videos, still + gamma,beta,alpha, still grid. Restored to Folders+List+A-Z afterwards. + * LONG-PRESS a video row -> multi-select mode: a "1 / 3 Selected" header + a + "Select all" control + a Play/Rename/Share/Info/Delete action bar, and the + pressed row gets a highlighted background. Tapping a second row -> "2 / 3 + Selected"; "Select all" -> "3 / 3 Selected"; BACK exits with all three titles + intact. (NEVER taps Delete.) + * Partially playing a video then returning to the folder paints a played- + progress bar along the bottom of THAT row's thumbnail (a Compose-drawn element + absent from the a11y tree) — VLM only. + +CEDES: a toggle's checked bit / SETTINGS on-off -> states; a derived value (speed, +duration total, the search COUNT as a number) -> computation; exact label wording +-> text; whether a screen is reachable -> navigation; view-tree SHAPE -> structure. +Here we assert only DATA that changed and PERSISTED as a consequence of a +multi-step action. + +Dropped (with reasons, so the denominator is honest): + * Speed-stepper "+ + reset -> 1.0": the numeric value belongs to computation, + and the player top-bar icons are only hittable in a ~1 s window after a + frame-centre tap (the overlay fades while the a11y tree lingers) — too flaky + for a deterministic value assert here. Ceded to computation. + * FAB "Recently played" list contents: the play IS recorded, but the recorded- + vs-shown semantics (completion clears the resume entry) and the second FAB-open + navigation proved non-deterministic across a run — asserting an exact + recently-played set would be a flaky false-fail. The SAME persisted-play signal + is captured deterministically by the played-progress-bar VLM assert. + * Duration sort order: on these tiny generated fixtures the app returned + beta,alpha,gamma for BOTH A-Z and Z-A (it did not respond to direction and did + not match the clip durations), so it is not a stable observable. Title Z-A + reversal (verified deterministic) carries the reorder assertion instead. + +Fixtures: the 3 sample videos are authored into fixtures/ and mirrored to the +device by push_fixtures() (run_suite() calls it once); every test reaches them +through fixture_on_device(name), never a hand-pushed path. +""" +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 +import android_testgen_kit as kit # noqa: E402 (geometry cache for player) + +require_kit(1) + +# ── Ground-truth markers (strings observed on the running original) ───────────── +FOLDER_NAME = "Download" +VIDEO_TITLES = ("alpha_clip", "beta_movie", "gamma_reel") # default A-Z order +VIDEO_BETA = "beta_movie" +PLACEHOLDER = "http://example.com/example.mp4" +NAV_UP = "Navigate up" +URL_TEXT = "http://test.mp4" +# The fixture videos the picker opens; declared via fixture_on_device so the +# dependency is explicit and the kit pushes the bytes on a fresh emulator. +FIXTURE_VIDEOS = ("alpha_clip.mp4", "beta_movie.mp4", "gamma_reel.mp4") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Setup / query helpers (shared patterns; NOT duplicating structure/nav tests) +# ══════════════════════════════════════════════════════════════════════════════ + +def and_grant_media(): + """Tap the runtime media-permission 'Allow all' if it is showing (no-op + otherwise). restart_app() keeps the grant; clear_data() re-prompts, so this + polls a few times for the dialog to appear.""" + for _ in range(4): + for label in ("Allow all", "While using the app", "Allow"): + n = find_node_ci(ui(), label) + if n: + tap_node(n) + settle("tap") + return True + settle("dump") + return False + + +def _home_content_ready(nodes): + """True once the Home picker rendered its top bar plus either the folder row or + the flat video titles — so we never assert against a mid-load frame.""" + topbar = all(find_node(nodes, content_desc=d) for d in ("Search", "Menu", "Settings")) + body = bool(find_node(nodes, text=FOLDER_NAME)) or any( + find_node(nodes, text=t) for t in VIDEO_TITLES) + return topbar and body + + +def tap_topbar(nodes, desc): + """Tap a top-bar icon by content-desc. The desc node itself is not clickable — + its wrapping View is — so tap the tightest clickable ancestor containing the + icon centre, falling back to the desc node.""" + target = find_node(nodes, content_desc=desc) + if not target or "_bounds" not in target: + return False + tcx, tcy = target["_center"] + best, best_area = None, None + for n in nodes: + if n.get("clickable") != "true" or "_bounds" not in n: + continue + x1, y1, x2, y2 = n["_bounds"] + if x1 <= tcx <= x2 and y1 <= tcy <= y2: + area = (x2 - x1) * (y2 - y1) + if best_area is None or area < best_area: + best, best_area = n, area + return tap_node(best) if best else tap_node(target) + + +def open_quick_settings(nodes): + """Tap the 'Menu' top-bar icon; return fresh nodes with the Quick Settings + sheet up.""" + tap_topbar(nodes, "Menu") + settle("tap") + return ui() + + +def in_folders_mode(nodes): + """Home is in the default Folders view iff the 'Download' folder row shows and + the flat video titles do not.""" + return bool(find_node(nodes, text=FOLDER_NAME)) and not any( + find_node(nodes, text=t) for t in VIDEO_TITLES) + + +def normalize_home(nodes): + """Return the picker to the app default Folders + List + Title A-Z (these are + PERSISTED across restart, so a test that changed them must undo it or the next + test's home_ready fixes it). One Quick Settings visit does all three.""" + qs = open_quick_settings(nodes) + n = find_node(qs, text="Folders") # view mode + if n: + tap_node(n) + settle("tap") + n = find_node(ui(), text="List") # layout + if n: + tap_node(n) + settle("tap") + n = find_node(ui(), text="A-Z") # direction + if n: + tap_node(n) + settle("tap") + done = find_node(ui(), text="Done") + if done: + tap_node(done) + settle("tap") + return ui() + + +def home_ready(normalize=True): + """restart (KEEPS the media grant), wait for the rendered Home, and normalize + the picker to Folders + List + A-Z so DATA tests start from a known layout. + + push_fixtures() is idempotent (run_suite() also calls it); doing it here keeps + each test self-sufficient and makes the fixture dependency explicit — the files + land at fixture_on_device('beta_movie.mp4') etc.""" + push_fixtures() + _ = [fixture_on_device(v) for v in FIXTURE_VIDEOS] # explicit dependency + nodes = [] + for _attempt in range(2): + restart_app() + if not wait_for_foreground(): + continue + and_grant_media() + for _ in range(6): + nodes = ui() + if _home_content_ready(nodes): + break + settle("dump") + if _home_content_ready(nodes): + break + if not nodes: + return [] + if normalize and not in_folders_mode(nodes): + nodes = normalize_home(nodes) + return nodes + + +def home_ready_clean(normalize=True): + """Like home_ready but from a VIRGIN database (clear_data), so play history is + empty. Used only where a test needs no prior play state. Re-prompts for the + media grant, which and_grant_media() handles.""" + push_fixtures() + _ = [fixture_on_device(v) for v in FIXTURE_VIDEOS] + nodes = [] + for _attempt in range(2): + clear_data() + launch_app() + if not wait_for_foreground(): + continue + and_grant_media() + for _ in range(8): + nodes = ui() + if _home_content_ready(nodes): + break + settle("dump") + if _home_content_ready(nodes): + break + if not nodes: + return [] + if normalize and not in_folders_mode(nodes): + nodes = normalize_home(nodes) + return nodes + + +def find_fab(nodes): + """The bottom-right expand FAB: a desc-less, text-less clickable View in the + lower-right quadrant. Derived from a fresh dump — never a hardcoded coord.""" + s = get_screen_info() + best = None + for n in nodes: + if n.get("clickable") != "true": + continue + if n.get("text", "").strip() or n.get("content-desc", "").strip(): + continue + b = n.get("_bounds") + if not b: + continue + cx, cy = n["_center"] + if cx < s["width"] * 0.6 or cy < s["height"] * 0.6: + continue + w, h = b[2] - b[0], b[3] - b[1] + if w < 60 or h < 60 or w > s["width"] * 0.6: + continue + if best is None or (cy + cx) > (best["_center"][1] + best["_center"][0]): + best = n + return best + + +def video_order(nodes): + """The flat video titles in VISUAL (y-then-x sorted) order — the order the user + sees, not document order. Used for reorder / integrity assertions.""" + tvs = [n for n in nodes if n.get("text", "") in VIDEO_TITLES and n.get("_bounds")] + tvs.sort(key=lambda n: (n["_bounds"][1], n["_bounds"][0])) + return [n["text"] for n in tvs] + + +def row_for(nodes, title): + """The long-clickable list-item View that CONTAINS the given title TextView + (rows are anonymous Views; identify by y-containment, tightest wins).""" + tv = find_node(nodes, text=title) + if not tv or "_center" not in tv: + return None + _, ty = tv["_center"] + cand = [n for n in nodes + if n.get("long-clickable") == "true" and n.get("_bounds") + and n["_bounds"][1] <= ty <= n["_bounds"][3]] + cand.sort(key=lambda n: (n["_bounds"][2] - n["_bounds"][0]) + * (n["_bounds"][3] - n["_bounds"][1])) + return cand[0] if cand else None + + +def edit_field(nodes): + """The (single) EditText on the current surface, or None.""" + e = find_by_class(nodes, "EditText") + return e[0] if e else None + + +def sel_count(nodes): + """The current 'N / 3 Selected' count as an int, or 0 if not in select mode.""" + for n in nodes: + t = n.get("text", "").strip() + if t.endswith("Selected") and "/" in t: + head = t.split("/", 1)[0].strip() + if head.isdigit(): + return int(head) + return 0 + + +def tap_ancestor_of(nodes, desc): + """Tap the tightest clickable ancestor of the content-desc icon `desc`.""" + icon = find_node(nodes, content_desc=desc) + if not icon or "_center" not in icon: + return False + scx, scy = icon["_center"] + best, ba = None, None + for n in nodes: + if n.get("clickable") == "true" and n.get("_bounds"): + x1, y1, x2, y2 = n["_bounds"] + if x1 <= scx <= x2 and y1 <= scy <= y2: + area = (x2 - x1) * (y2 - y1) + if ba is None or area < ba: + best, ba = n, area + return tap_node(best or icon) + + +# ── Player geometry (landscape window reports portrait via `wm size`) ─────────── + +def _dump_center(nodes): + mx = max((b[2] for b in (n.get("_bounds") for n in nodes) if b), default=0) + my = max((b[3] for b in (n.get("_bounds") for n in nodes) if b), default=0) + return (mx // 2, my // 2) if mx and my else (0, 0) + + +def _reveal_player(): + """Tap the (rotated) frame centre until the auto-hiding player controls show, + handling the one-time 'Got it' hint. Returns fresh player nodes or the last.""" + for _ in range(6): + nodes = ui() + if find_node(nodes, content_desc="Play/Pause"): + return nodes + gi = find_node_ci(nodes, "Got it") + if gi: + tap_node(gi) + settle("tap") + continue + cx, cy = _dump_center(nodes) + if not cx: + break + tap(cx, cy) + settle("tap") + return ui() + + +# ══════════════════════════════════════════════════════════════════════════════ +# Depth-family navigation helpers. Named and_enter_*/and_reach_* so an and_enter() +# call backs every declared depth>=1 (see and_audit_depth). Each returns fresh +# nodes of the reached surface, or [] on failure. +# ══════════════════════════════════════════════════════════════════════════════ + +def and_enter_folder(nodes=None, name=FOLDER_NAME): + """Home (Folders view) -> tap the named folder -> folder contents. Returns + fresh folder nodes or [].""" + nodes = nodes if nodes is not None else home_ready() + row = find_node(nodes, text=name) + if not row or not tap_node(row): + return [] + settle("tap") + after = ui() + if find_node(after, content_desc=NAV_UP): + and_enter("folder") + return after + return [] + + +def and_open_fab(nodes=None): + """Home -> tap the FAB -> the expanded 3-pill menu. Returns fresh menu nodes + or [].""" + nodes = nodes if nodes is not None else home_ready() + fab = find_fab(nodes) + if not fab or not tap_node(fab): + return [] + settle("tap") + menu = ui() + if find_node(menu, text="Open network stream"): + and_enter("fab_menu") + return menu + return [] + + +def and_reach_network_dialog(nodes=None): + """Home -> FAB menu -> 'Open network stream' -> the Network Stream dialog. + Counts a second surface (depth 2). Returns dialog nodes or [].""" + menu = and_open_fab(nodes) + if not menu: + return [] + pill = find_node(menu, text="Open network stream") + if not pill or not tap_node(pill): + return [] + settle("tap") + dlg = ui() + if find_node(dlg, text="Network Stream") and edit_field(dlg): + and_enter("network_dialog") + return dlg + return [] + + +def and_open_search(nodes=None): + """Home -> Search screen. Returns fresh search nodes or [].""" + nodes = nodes if nodes is not None else home_ready() + if not nodes: + return [] + tap_topbar(nodes, "Search") + settle("tap") + after = ui() + if find_node(after, text="Popular folders") or edit_field(after): + and_enter("search") + return after + return [] + + +def and_reach_player(nodes=None, title=VIDEO_BETA): + """Home -> folder -> tap a video row -> PlayerActivity (landscape); reveal the + auto-hiding controls. Counts two surfaces (depth 2). Returns player nodes or + []. Kept tight so the short clip does not end mid-test.""" + folder = and_enter_folder(nodes) + if not folder: + return [] + row = find_node(folder, text=title) + if not row or not tap_node(row): + return [] + settle("launch") + kit._screen_info = None # drop stale portrait geometry + player = _reveal_player() + if find_node(player, content_desc="Play/Pause"): + and_enter("player") + return player + return [] + + +# ══════════════════════════════════════════════════════════════════════════════ +# (1) Network URL round-trip — 3-step DATA edit. Type into the field, read it back, +# then Cancel and confirm Home returns. depth=2, value. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_network_url_roundtrip",)) +def test_network_url_roundtrip(): + dlg = and_reach_network_dialog() + if not dlg: + record("interaction_network_url_roundtrip", False, + "feature_missing: Network Stream dialog not reachable via the FAB", + depth=2, jump_kind="value", + expect=f"URL field holds {URL_TEXT!r}, then Cancel restores Home") + return + field = edit_field(dlg) + absent_before = URL_TEXT not in (field.get("text", "") or "") + typed = type_text(field, URL_TEXT) + # NOTE: do NOT call hide_keyboard() here — in this dialog KEYCODE_BACK dismisses + # the whole Network Stream dialog (not just the IME), so the field vanishes + # before we can read it. The typed value is already in the tree; re-dump directly. + after = ui() + f2 = edit_field(after) + landed = bool(f2) and (f2.get("text", "") or "") == URL_TEXT + # Cancel dismisses the dialog and Home ("Download") returns. + tap_node(find_node(after, text="Cancel") or find_node_ci(after, "Cancel")) + settle("tap") + home = ui() + dismissed = (not find_node(home, text="Network Stream")) and \ + bool(find_node(home, text=FOLDER_NAME)) + ok = typed and absent_before and landed and dismissed + msg = "" + if not typed: + msg = "setup_failed: could not type into the URL field" + elif not landed: + msg = (f"behavior_wrong: URL field read {(f2.get('text') if f2 else None)!r}, " + f"expected {URL_TEXT!r}") + elif not dismissed: + msg = "behavior_wrong: Cancel did not dismiss the dialog back to Home" + record("interaction_network_url_roundtrip", ok, msg, + depth=2, jump_kind="value", + expect=f"URL field holds {URL_TEXT!r}; Cancel restores Home 'Download'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (2) Network URL edit-then-clear — multi-step DATA edit: type a URL, then +# backspace-clear it; the field empties and the placeholder returns. depth=2, +# value. Cancel at the end so no stray dialog leaks to the next test. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_network_url_edit_clear",)) +def test_network_url_edit_clear(): + dlg = and_reach_network_dialog() + if not dlg: + record("interaction_network_url_edit_clear", False, + "feature_missing: Network Stream dialog not reachable via the FAB", + depth=2, jump_kind="value", + expect=f"field {URL_TEXT!r} -> cleared to empty + placeholder returns") + return + field = edit_field(dlg) + typed = type_text(field, URL_TEXT) + # Do NOT hide_keyboard() — BACK dismisses this dialog. The value is already in + # the tree; re-dump directly to read it back. + mid = ui() + fmid = edit_field(mid) + filled = bool(fmid) and (fmid.get("text", "") or "") == URL_TEXT + # Clear: focus the field, then backspace past the whole string (keyboard up). + tap_node(fmid) + settle("keyboard") + for _ in range(len(URL_TEXT) + 4): + press_key("KEYCODE_DEL") + settle("text") + after = ui() + fa = edit_field(after) + emptied = bool(fa) and (fa.get("text", "") or "").strip() == "" + # The placeholder TextView (child of the empty EditText) reappears. + placeholder_back = bool(find_node(after, text=PLACEHOLDER)) + ok = typed and filled and emptied and placeholder_back + msg = "" + if not typed or not filled: + msg = f"setup_failed: could not seed the field with {URL_TEXT!r}" + elif not emptied: + msg = (f"behavior_wrong: field still reads " + f"{(fa.get('text') if fa else None)!r} after clearing") + elif not placeholder_back: + msg = "behavior_wrong: placeholder did not return on an empty field" + record("interaction_network_url_edit_clear", ok, msg, + depth=2, jump_kind="value", + expect=f"field {URL_TEXT!r} -> '' and placeholder {PLACEHOLDER!r} returns") + # tidy up: dismiss the dialog + tap_node(find_node(ui(), text="Cancel") or find_node_ci(ui(), "Cancel")) + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (3) Search filter sequence — 3-step: type "beta" -> the list narrows to the one +# "beta_movie" row; backspace-clear -> the "Popular folders" section returns. +# depth=1, value. VLM: exactly one result row rendered. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_search_filter_sequence", + "interaction_search_filter_sequence_vlm")) +def test_search_filter_sequence(): + search = and_open_search() + if not search: + record("interaction_search_filter_sequence", False, + "feature_missing: Search surface not reachable from Home", + depth=1, jump_kind="value", + expect="'beta' -> one 'beta_movie' row, then clear -> 'Popular folders'") + record("interaction_search_filter_sequence_vlm", False, + "feature_missing: Search surface not reachable from Home", + depth=1, jump_kind="value", tag="position") + return + popular_before = bool(find_node(search, text="Popular folders")) + field = edit_field(search) + typed = type_text(field, "beta") + settle("text") + filtered = ui() + beta_row = bool(find_node(filtered, text="beta_movie")) + others_gone = not (find_node(filtered, text="alpha_clip") + or find_node(filtered, text="gamma_reel")) + popular_hidden = not find_node(filtered, text="Popular folders") + # VLM while the single filtered result is on screen (rendered-layout check that + # complements the text rule). + vlm_assert("interaction_search_filter_sequence", + "Below the search box (which contains the text 'beta'), is there " + "EXACTLY ONE video result row visible (a single thumbnail with a " + "title beside it), rather than several rows or a folder list?", + RESULTS_DIR, depth=1, jump_kind="value", tag="position") + # Backspace-clear the query -> the empty-state 'Popular folders' returns. + f2 = edit_field(ui()) or field + tap_node(f2) + settle("keyboard") + for _ in range(8): + press_key("KEYCODE_DEL") + settle("text") + cleared = ui() + popular_back = bool(find_node(cleared, text="Popular folders")) + beta_gone = not find_node(cleared, text="beta_movie") + ok = (typed and popular_before and beta_row and others_gone + and popular_hidden and popular_back and beta_gone) + msg = "" + if not typed or not popular_before: + msg = "setup_failed: search field / 'Popular folders' empty-state missing" + elif not (beta_row and others_gone): + msg = "behavior_wrong: query 'beta' did not narrow to exactly the beta_movie row" + elif not popular_back: + msg = "behavior_wrong: clearing the query did not restore 'Popular folders'" + record("interaction_search_filter_sequence", ok, msg, + depth=1, jump_kind="value", + expect="'beta' -> single 'beta_movie' row (alpha/gamma gone); " + "clear -> 'Popular folders' section returns") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (4) Search different query, multi-record integrity — "clip" matches exactly +# alpha_clip and NEITHER beta_movie NOR gamma_reel. The negative half is what +# makes it discriminating. depth=1, value. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_search_query_clip",)) +def test_search_query_clip(): + search = and_open_search() + if not search: + record("interaction_search_query_clip", False, + "feature_missing: Search surface not reachable from Home", + depth=1, jump_kind="value", + expect="'clip' -> exactly alpha_clip; beta_movie & gamma_reel absent") + return + field = edit_field(search) + typed = type_text(field, "clip") + settle("text") + res = ui() + alpha = bool(find_node(res, text="alpha_clip")) + beta = bool(find_node(res, text="beta_movie")) + gamma = bool(find_node(res, text="gamma_reel")) + ok = typed and alpha and not beta and not gamma + msg = "" + if not typed: + msg = "setup_failed: could not type into the search field" + elif not alpha: + msg = "behavior_wrong: query 'clip' did not surface the alpha_clip row" + elif beta or gamma: + msg = (f"behavior_wrong: 'clip' also matched " + f"{'beta_movie ' if beta else ''}{'gamma_reel' if gamma else ''}".strip()) + record("interaction_search_query_clip", ok, msg, + depth=1, jump_kind="value", + expect="'clip' filters to exactly {alpha_clip}; beta_movie/gamma_reel absent") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (5) Quick Settings multi-change sequence — in Videos view, Grid + Z-A + Done +# reverses the flat video order alpha,beta,gamma -> gamma,beta,alpha. Reads the +# row order BEFORE and AFTER; asserts the exact reversed sequence. A dead shell +# that ignores the second/third tap cannot produce this. depth=1, value. +# Restores Folders+List+A-Z. VLM: grid rendered side-by-side. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_quicksettings_multichange_reorder", + "interaction_quicksettings_multichange_reorder_vlm")) +def test_quicksettings_multichange_reorder(): + nodes = home_ready() + if not nodes: + record("interaction_quicksettings_multichange_reorder", False, + "setup_failed: Home not ready", depth=1, jump_kind="value", + expect="rows reorder alpha,beta,gamma -> gamma,beta,alpha") + record("interaction_quicksettings_multichange_reorder_vlm", False, + "setup_failed: Home not ready", depth=1, jump_kind="value", tag="position") + return + # Switch to Videos (flat list) + A-Z baseline, capture the ordered rows. + qs = open_quick_settings(nodes) + tap_text(qs, "Videos") + settle("tap") + n = find_node(ui(), text="A-Z") + if n: + tap_node(n) + settle("tap") + tap_node(find_node(ui(), text="Done")) + settle("tap") + before = video_order(ui()) # expect alpha,beta,gamma + # Multi-change: Grid + Z-A + Done, all in one sheet visit. + qs2 = open_quick_settings(ui()) + grid_ok = tap_text(qs2, "Grid") + settle("tap") + za_ok = tap_text(ui(), "Z-A") + settle("tap") + tap_node(find_node(ui(), text="Done")) + settle("tap") + after_nodes = ui() + after = video_order(after_nodes) # expect gamma,beta,alpha + reversed_ok = (before == ["alpha_clip", "beta_movie", "gamma_reel"] + and after == ["gamma_reel", "beta_movie", "alpha_clip"]) + ok = grid_ok and za_ok and reversed_ok + msg = "" + if not (grid_ok and za_ok): + msg = "setup_failed: 'Grid' or 'Z-A' control not found in Quick Settings" + elif not reversed_ok: + msg = (f"behavior_wrong: order {before} -> {after}, " + f"expected alpha,beta,gamma -> gamma,beta,alpha") + record("interaction_quicksettings_multichange_reorder", ok, msg, + depth=1, jump_kind="value", + expect="flat video rows alpha,beta,gamma -> gamma,beta,alpha after Grid+Z-A+Done") + + # VLM while the grid is on screen: the reversed order rendered as a grid. + vlm_assert("interaction_quicksettings_multichange_reorder", + "Are the video thumbnails laid out in a multi-column GRID with at " + "least two thumbnails positioned SIDE BY SIDE in the same row " + "(rather than a single one-per-row column)?", + RESULTS_DIR, depth=1, jump_kind="value", tag="position") + normalize_home(after_nodes) # restore Folders+List+A-Z + + +# ══════════════════════════════════════════════════════════════════════════════ +# (6) Sort direction toggle, multi-record integrity — in Videos view, A-Z gives +# alpha,beta,gamma and Z-A gives gamma,beta,alpha; toggling back to A-Z restores +# the original order AND all three rows survive (nothing dropped or duplicated). +# Catches a recreation that keeps only one row after a reorder. depth=1, value. +# Restores Folders+List+A-Z. VLM: reversed order shown as coloured thumbnails. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_sort_toggle_integrity", + "interaction_sort_toggle_integrity_vlm")) +def test_sort_toggle_integrity(): + nodes = home_ready() + if not nodes: + record("interaction_sort_toggle_integrity", False, + "setup_failed: Home not ready", depth=1, jump_kind="value", + expect="A-Z alpha,beta,gamma <-> Z-A gamma,beta,alpha; all 3 survive") + record("interaction_sort_toggle_integrity_vlm", False, + "setup_failed: Home not ready", depth=1, jump_kind="value", tag="position") + return + # Videos view + A-Z. + qs = open_quick_settings(nodes) + tap_text(qs, "Videos") + settle("tap") + n = find_node(ui(), text="A-Z") + if n: + tap_node(n) + settle("tap") + tap_node(find_node(ui(), text="Done")) + settle("tap") + az = video_order(ui()) # expect alpha,beta,gamma + # Flip to Z-A. + qs2 = open_quick_settings(ui()) + tap_text(qs2, "Z-A") + settle("tap") + tap_node(find_node(ui(), text="Done")) + settle("tap") + za_nodes = ui() + za = video_order(za_nodes) # expect gamma,beta,alpha + # VLM while Z-A is on screen: the coloured thumbnails in reversed top-to-bottom + # order (green 'Gamma' at the TOP, red 'Alpha Clip' at the BOTTOM). + vlm_assert("interaction_sort_toggle_integrity", + "In this single-column list of three coloured video thumbnails, is " + "the GREEN thumbnail ('Gamma') at the TOP and the RED thumbnail " + "('Alpha Clip') at the BOTTOM (i.e. green, blue, red top to bottom)?", + RESULTS_DIR, depth=1, jump_kind="value", tag="position") + # Flip back to A-Z. + qs3 = open_quick_settings(za_nodes) + tap_text(qs3, "A-Z") + settle("tap") + tap_node(find_node(ui(), text="Done")) + settle("tap") + az2_nodes = ui() + az2 = video_order(az2_nodes) # expect alpha,beta,gamma again + all_three = (sorted(az) == sorted(VIDEO_TITLES) + and sorted(za) == sorted(VIDEO_TITLES) + and sorted(az2) == sorted(VIDEO_TITLES)) + ok = (az == ["alpha_clip", "beta_movie", "gamma_reel"] + and za == ["gamma_reel", "beta_movie", "alpha_clip"] + and az2 == ["alpha_clip", "beta_movie", "gamma_reel"] + and all_three) + msg = "" + if not all_three: + msg = (f"behavior_wrong: a row was lost across the reorder " + f"(A-Z={az} Z-A={za} A-Z2={az2})") + elif not ok: + msg = (f"behavior_wrong: A-Z={az} Z-A={za} A-Z-again={az2}, expected " + f"alpha,beta,gamma / gamma,beta,alpha / alpha,beta,gamma") + record("interaction_sort_toggle_integrity", ok, msg, + depth=1, jump_kind="value", + expect="A-Z=alpha,beta,gamma; Z-A=gamma,beta,alpha; back to A-Z restores; " + "all 3 rows intact throughout") + normalize_home(az2_nodes) # restore Folders+List+A-Z + + +# ══════════════════════════════════════════════════════════════════════════════ +# (7) DATA persistence across PROCESS DEATH — the highest-value test. Set a +# persisted layout (Videos + Grid + Z-A), kill the process with +# force_stop_and_relaunch(), then assert the SAME data state is still there: +# still Videos (3 titles), still reversed order gamma,beta,alpha. An in-memory +# -only recreation cannot pass this. depth=0 (the data is on the first surface +# after relaunch — no navigation to reach it), transition (a persisted state +# that survived a full restart). Restores Folders+List+A-Z. VLM: grid persists. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_persist_layout_process_death", + "interaction_persist_layout_process_death_vlm")) +def test_persist_layout_process_death(): + nodes = home_ready() + if not nodes: + record("interaction_persist_layout_process_death", False, + "setup_failed: Home not ready", depth=0, jump_kind="transition", + expect="after process death: Videos view, order gamma,beta,alpha, grid") + record("interaction_persist_layout_process_death_vlm", False, + "setup_failed: Home not ready", depth=0, jump_kind="transition", tag="position") + return + # Apply Videos + Grid + Z-A. + qs = open_quick_settings(nodes) + tap_text(qs, "Videos") + settle("tap") + tap_text(ui(), "Grid") + settle("tap") + tap_text(ui(), "Z-A") + settle("tap") + tap_node(find_node(ui(), text="Done")) + settle("tap") + pre = video_order(ui()) # expect gamma,beta,alpha + applied = pre == ["gamma_reel", "beta_movie", "alpha_clip"] + + # PROCESS DEATH: kill and relaunch (NOT clear_data — that would wipe the pref). + force_stop_and_relaunch() + wait_for_foreground() + and_grant_media() + post_nodes = [] + for _ in range(8): + post_nodes = ui() + if any(find_node(post_nodes, text=t) for t in VIDEO_TITLES): + break + settle("dump") + post = video_order(post_nodes) # expect gamma,beta,alpha still + still_videos = sum(bool(find_node(post_nodes, text=t)) for t in VIDEO_TITLES) == 3 + folders_gone = not find_node(post_nodes, text=FOLDER_NAME) + order_survived = post == ["gamma_reel", "beta_movie", "alpha_clip"] + ok = applied and still_videos and folders_gone and order_survived + msg = "" + if not applied: + msg = f"setup_failed: could not apply Videos+Grid+Z-A before death (got {pre})" + elif not still_videos: + msg = "behavior_wrong: not in Videos view after process death (layout not persisted)" + elif not order_survived: + msg = (f"behavior_wrong: order after death {post}, expected gamma,beta,alpha " + f"(sort pref did not survive process death)") + record("interaction_persist_layout_process_death", ok, msg, + depth=0, jump_kind="transition", + expect="after force_stop_and_relaunch: still Videos, order gamma,beta,alpha") + + # VLM: the grid layout also survived the process death. + vlm_assert("interaction_persist_layout_process_death", + "Are the video thumbnails laid out in a multi-column GRID with at " + "least two thumbnails SIDE BY SIDE in the same row (rather than a " + "single one-per-row column)?", + RESULTS_DIR, depth=0, jump_kind="transition", tag="position") + normalize_home(post_nodes) # restore Folders+List+A-Z + + +# ══════════════════════════════════════════════════════════════════════════════ +# (8) LONG-PRESS a video row (sole owner) — long-pressing beta_movie enters +# multi-select mode: a "1 / 3 Selected" header appears and a Play/Rename/Share/ +# Info action set appears. Asserts the selection header + the non-destructive +# actions (NEVER taps Delete). depth=1, transition. VLM: the pressed row is +# highlighted with a different background colour. +# ══════════════════════════════════════════════════════════════════════════════ + +SELECT_ACTIONS = ("Play", "Rename", "Share", "Info") # excludes Delete on purpose + + +@and_test(expects=("interaction_longpress_context_menu", + "interaction_longpress_context_menu_vlm")) +def test_longpress_context_menu(): + folder = and_enter_folder() + if not folder: + record("interaction_longpress_context_menu", False, + "setup_failed: Download folder contents not reached", + depth=1, jump_kind="transition", + expect="long-press beta_movie -> '1 / 3 Selected' + Play/Rename/Share/Info") + record("interaction_longpress_context_menu_vlm", False, + "setup_failed: Download folder contents not reached", + depth=1, jump_kind="transition", tag="color") + return + sel_before = sel_count(folder) # expect 0 (no selection yet) + row = row_for(folder, VIDEO_BETA) + pressed = long_press(row, ms=900) if row else False + settle("tap") + after = ui() + count_after = sel_count(after) # expect 1 + header_ok = count_after == 1 + actions_present = sum( + bool(find_node(after, content_desc=a) or find_node(after, text=a)) + for a in SELECT_ACTIONS) + actions_ok = actions_present >= 3 # Play/Rename/Share/Info bar + ok = pressed and sel_before == 0 and header_ok and actions_ok + msg = "" + if not pressed: + msg = "setup_failed: could not long-press the beta_movie row" + elif not header_ok: + msg = (f"behavior_wrong: selection header count = {count_after}, " + f"expected 1 after long-press") + elif not actions_ok: + msg = (f"feature_missing: only {actions_present}/4 context actions " + f"(Play/Rename/Share/Info) appeared") + record("interaction_longpress_context_menu", ok, msg, + depth=1, jump_kind="transition", + expect="long-press beta_movie -> '1 / 3 Selected' + Play/Rename/Share/Info bar") + + # VLM: the long-pressed row is visually highlighted (tinted background). + vlm_assert("interaction_longpress_context_menu", + "Is exactly ONE of the three video rows visually highlighted with a " + "tinted/coloured selection background that is different from the " + "plain white background of the other two rows?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="color") + back() # exit selection mode (safe) + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (9) Long-press multi-select integrity — long-press one row (count 1), tap a +# second row (count 2), then Select all (count 3); BACK exits and all three +# titles remain intact. A 3+-step sequence where each step depends on the last. +# depth=1, value. VLM: two rows highlighted after the 2nd tap. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_multiselect_count_sequence", + "interaction_multiselect_count_sequence_vlm")) +def test_multiselect_count_sequence(): + folder = and_enter_folder() + if not folder: + record("interaction_multiselect_count_sequence", False, + "setup_failed: Download folder contents not reached", + depth=1, jump_kind="value", + expect="select counts 1 -> 2 -> 3; all 3 titles intact after exit") + record("interaction_multiselect_count_sequence_vlm", False, + "setup_failed: Download folder contents not reached", + depth=1, jump_kind="value", tag="color") + return + # Step 1: long-press beta -> count 1. + row_b = row_for(folder, VIDEO_BETA) + long_press(row_b, ms=900) + settle("tap") + s1_nodes = ui() + c1 = sel_count(s1_nodes) + # Step 2: tap alpha row -> count 2. + row_a = row_for(s1_nodes, "alpha_clip") + tapped2 = tap_node(row_a) if row_a else False + settle("tap") + s2_nodes = ui() + c2 = sel_count(s2_nodes) + # VLM here: two rows highlighted (capture before the 3rd tap). + vlm_assert("interaction_multiselect_count_sequence", + "Are exactly TWO of the three video rows visually highlighted with a " + "tinted/coloured selection background (and the third row left on the " + "plain background)?", + RESULTS_DIR, depth=1, jump_kind="value", tag="color") + # Step 3: Select all -> count 3. + selall_ok = tap_ancestor_of(ui(), "Select all") + settle("tap") + c3 = sel_count(ui()) + # Exit selection mode and confirm every title survived (integrity). + back() + settle("tap") + final = ui() + titles_intact = sum(bool(find_node(final, text=t)) for t in VIDEO_TITLES) + exited = sel_count(final) == 0 + ok = (c1 == 1 and tapped2 and c2 == 2 and selall_ok and c3 == 3 + and titles_intact == 3 and exited) + msg = "" + if c1 != 1: + msg = f"setup_failed: long-press did not start selection (count={c1})" + elif c2 != 2: + msg = f"behavior_wrong: tapping a 2nd row gave count {c2}, expected 2" + elif c3 != 3: + msg = f"behavior_wrong: 'Select all' gave count {c3}, expected 3" + elif titles_intact != 3: + msg = (f"behavior_wrong: only {titles_intact}/3 titles remain after exiting " + f"selection (rows lost)") + record("interaction_multiselect_count_sequence", ok, msg, + depth=1, jump_kind="value", + expect="selection count 1->2->3 (long-press, +row, Select all); " + "all 3 titles intact after BACK") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (10) Played-progress persists across navigation (VLM-only DATA consequence) — +# from a VIRGIN db, play beta_movie partway, return to the folder, and the +# beta_movie thumbnail now carries a played-progress bar the other two rows do +# not. The bar is a Compose-drawn element absent from the a11y tree, so this is +# a legitimate VLM assertion. depth=1 (we navigated back to the folder to read +# the consequence). NO rule twin — the consequence is purely rendered. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_played_progress_marker_vlm",)) +def test_played_progress_marker(): + # Virgin db so no pre-existing progress on any row. + nodes = home_ready_clean() + if not nodes: + record("interaction_played_progress_marker_vlm", False, + "setup_failed: Home not ready from a clean database", + depth=1, jump_kind="transition", tag="shape") + return + player = and_reach_player(nodes, VIDEO_BETA) + if not player: + record("interaction_played_progress_marker_vlm", False, + "setup_failed: could not open beta_movie in the player", + depth=1, jump_kind="transition", tag="shape") + return + # Let it play partway (leaves a resume position ~half the 8 s clip), then BACK + # to the folder so the row can show the persisted progress. + time.sleep(4) + and_back() # player -> folder + kit._screen_info = None # returning to portrait picker + settle("tap") + for _ in range(4): # confirm we are back in folder + folder = ui() + if find_node(folder, content_desc=NAV_UP) and find_node(folder, text=VIDEO_BETA): + break + settle("dump") + vlm_assert("interaction_played_progress_marker", + "In this list of three video rows (red 'Alpha Clip', blue 'Beta " + "Movie', green 'Gamma'), does the BLUE beta_movie thumbnail have a " + "thin horizontal progress bar along its BOTTOM edge that the red and " + "green thumbnails do NOT have?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="shape") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Registry +# ══════════════════════════════════════════════════════════════════════════════ + +TESTS = [ + test_network_url_roundtrip, + test_network_url_edit_clear, + test_search_filter_sequence, + test_search_query_clip, + test_quicksettings_multichange_reorder, + test_sort_toggle_integrity, + test_persist_layout_process_death, + test_longpress_context_menu, + test_multiselect_count_sequence, + test_played_progress_marker, +] + +if __name__ == "__main__": + run_suite(TESTS, "interaction") diff --git a/android/anilbeesetti-nextplayer/tests/test_android_navigation.py b/android/anilbeesetti-nextplayer/tests/test_android_navigation.py new file mode 100644 index 0000000000000000000000000000000000000000..9abe892f35ee8544fe12c60d9d34d81a5884439f --- /dev/null +++ b/android/anilbeesetti-nextplayer/tests/test_android_navigation.py @@ -0,0 +1,917 @@ +#!/usr/bin/env python3 +"""NAVIGATION lane for NextPlayer (dev.anilbeesetti.nextplayer.debug). + +This lane owns surface REACHABILITY and BACK-STACK integrity: tapping a nav +trigger (top-bar icon, folder row, video row, settings row, FAB pill, player +top-bar icon) lands on the intended surface, and BACK unwinds the stack hop by +hop. It is the sole owner of jump_kind="reach" and of the deep (depth>=2) chains. + +Every jump is proven with the kit's and_reach(before, after, target, source): +the TARGET surface's discriminating element must have APPEARED *and* the SOURCE +surface's must have DISAPPEARED. A screen that was already in the tree was never +"reached". before/after are and_showing() snapshots. + +Ground truth (observed on the running original — see recon.md + recon_shots/ and +re-verified live before authoring): + * Home (portrait) top bar carries content-desc "Search"/"Menu"/"Settings"; + body lists the "Download" folder row with a "3 Videos" count badge; a + desc-less FAB bottom-right expands to 3 pills. + * Folder contents (Download) shows a "Navigate up" back arrow + the 3 video + rows (alpha_clip/beta_movie/gamma_reel); the Home-only "3 Videos" badge is + gone there. + * PlayerActivity is LANDSCAPE (2400x1080 in the dump while `wm size` still + reports the physical portrait 1080x2400). Controls auto-hide, and CRUCIALLY + the a11y tree keeps reporting them for a beat AFTER they visually fade — a + screenshot then shows only the video (verified). So the top-bar icons are + only hittable in the ~1 s window right after a frame-centre tap: we learn + their coordinates from one reveal, then tap centre and IMMEDIATELY tap the + icon with NO ui() dump in between (a dump's latency is enough for the overlay + to fade), retrying and hiding between tries. Because `wm size` lies here, + and_showing()/tap_node() would clip controls with x>1080, so we install the + dump's own landscape geometry (see _use_landscape_geom). + Icons left->right = playlist / playback-speed / audio-track / subtitle-track; + the centre control carries content-desc "Play/Pause". + * Settings root: 9 category rows (Appearance/Media library/Player/Gestures/ + Decoder/Audio/Subtitle/General/About). Each subscreen replaces the sibling + rows with its own content and keeps a "Navigate up" arrow; the root-only row + "Media library" therefore disappears on every subscreen (and "Appearance" on + the Media-library subscreen), which is the source marker for the sub reaches. + * Search: an EditText (hint "Search videos and folders") + a "Popular folders" + section; the Home top-bar "Menu" control is gone there. + * FAB pills: "Open network stream"/"Open local video"/"Recently played". The + network pill opens the "Network Stream" dialog (URL EditText + Done/Cancel). + * Player dialogs: "Select playback speed" (chips + "Skip silence"), + "Select audio track" ("Audio Track #1"), "Select subtitle track" + ("Open local subtitle"). + +Fixtures: the 3 sample videos are authored into fixtures/ and mirrored to the +device by push_fixtures() (run_suite() calls it once); each test reaches them +through fixture_on_device(name), never a hand-pushed path. + +CEDES (per lane contract): content strings -> text; tree shape -> structure; +selection/toggle -> states; a shown value -> computation; record creation -> +interaction. Here we assert ONLY "did we land on the target surface and leave +the source", plus BACK unwinding. +""" +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 +import android_testgen_kit as kit # noqa: E402 (for the geometry cache) + +require_kit(1) + +# ── Ground-truth markers (strings observed on the running original) ───────────── +FOLDER_NAME = "Download" +FOLDER_COUNT = "3 Videos" # Home-only badge; gone inside the folder +PLAYER_MARKER = "Play/Pause" # content-desc unique to the player +NAV_UP = "Navigate up" # back arrow on folder & settings screens +VIDEO_BETA = "beta_movie" # 8 s clip — the least race-prone player src +# The fixture videos the picker opens; declared via fixture_on_device so the +# dependency is explicit and the kit pushes the bytes on a fresh emulator. +FIXTURE_VIDEOS = ("alpha_clip.mp4", "beta_movie.mp4", "gamma_reel.mp4") + +# Settings root row that vanishes on any subscreen -> the source for sub reaches. +SETTINGS_SIBLING = "Media library" +SETTINGS_SIBLING_ALT = "Appearance" # source when the sub IS Media library + +LOOP_DESCS = ("Loop: Off", "Loop: One", "Loop: All") +# Player top-bar icon index (left->right among the right-side buttons). +PLAYER_ICON = {"speed": 1, "audio": 2, "subtitle": 3} + + +# ══════════════════════════════════════════════════════════════════════════════ +# Setup helpers +# ══════════════════════════════════════════════════════════════════════════════ + +def and_grant_media(): + """Tap the runtime media-permission 'Allow all' if it is showing (no-op + otherwise). restart_app() keeps the grant, so this is just a safety net.""" + for label in ("Allow all", "While using the app", "Allow"): + n = find_node_ci(ui(), label) + if n: + tap_node(n) + settle("tap") + return True + return False + + +def tap_topbar(nodes, desc): + """Tap a Home/folder top-bar icon by content-desc. The desc node itself is + not clickable — its wrapping View is — so tap the tightest clickable ancestor + that contains the icon centre, falling back to the desc node.""" + target = find_node(nodes, content_desc=desc) + if not target or "_bounds" not in target: + return False + tcx, tcy = target["_center"] + best, best_area = None, None + for n in nodes: + if n.get("clickable") != "true" or "_bounds" not in n: + continue + x1, y1, x2, y2 = n["_bounds"] + if x1 <= tcx <= x2 and y1 <= tcy <= y2: + area = (x2 - x1) * (y2 - y1) + if best_area is None or area < best_area: + best, best_area = n, area + return tap_node(best) if best else tap_node(target) + + +def _home_content_ready(nodes): + """True once the Home picker actually rendered its top bar + folder row, so we + never assert against a mid-load or launcher frame.""" + topbar = all(find_node(nodes, content_desc=d) for d in ("Search", "Menu", "Settings")) + body = bool(find_node(nodes, text=FOLDER_NAME)) or bool(find_node(nodes, text=VIDEO_BETA)) + return topbar and body + + +def _open_quick_settings(nodes): + tap_topbar(nodes, "Menu") + settle("tap") + return ui() + + +def _reset_view_mode(nodes): + """Normalize the picker to the default Folders view (persisted prefs survive + restart_app). Opens Quick Settings, selects Folders, taps Done.""" + qs = _open_quick_settings(nodes) + if find_node(qs, text="Folders"): + tap_text(qs, "Folders") + settle("tap") + done = find_node(ui(), text="Done") + if done: + tap_node(done) + settle("tap") + return ui() + + +def home_ready(): + """restart (keeps media grant), wait for the rendered Home, and guarantee the + default Folders view so the 'Download' folder row exists. Returns Home nodes. + + push_fixtures() is idempotent (run_suite() also calls it); doing it here keeps + each test self-sufficient and makes the fixture dependency explicit.""" + push_fixtures() + _ = [fixture_on_device(v) for v in FIXTURE_VIDEOS] # explicit dependency + nodes = [] + for _attempt in range(2): + restart_app() + if not wait_for_foreground(): + continue + and_grant_media() + for _ in range(6): + nodes = ui() + if _home_content_ready(nodes): + break + settle("dump") + if _home_content_ready(nodes): + break + if not nodes: + return [] + if not find_node(nodes, text=FOLDER_NAME): + nodes = _reset_view_mode(nodes) + return nodes + + +# ── Player geometry: the landscape window reports portrait via `wm size`, which +# would make and_showing()/tap_node() clip every control with x>1080. Derive the +# real landscape geometry from the dump's own max bounds and install it in the +# kit's cache so both helpers use the correct width. ──────────────────────────── + +def _dump_center(nodes): + maxx = max((b[2] for b in (n.get("_bounds") for n in nodes) if b), default=0) + maxy = max((b[3] for b in (n.get("_bounds") for n in nodes) if b), default=0) + return (maxx // 2, maxy // 2) if maxx and maxy else (0, 0) + + +def _use_landscape_geom(nodes): + """Point the kit's cached geometry at the dump's own (rotated) bounds so + and_showing() keeps the player controls and tap_node() accepts their x>1080 + centres. `input tap` on this app's landscape window uses these logical coords + directly (verified live).""" + maxx = max((b[2] for b in (n.get("_bounds") for n in nodes) if b), default=2400) + maxy = max((b[3] for b in (n.get("_bounds") for n in nodes) if b), default=1080) + kit._screen_info = {"width": maxx, "height": maxy, "density": 440, + "center_x": maxx // 2, "center_y": maxy // 2} + + +def _controls_up(nodes): + return bool(find_node(nodes, content_desc=PLAYER_MARKER) + or any(find_node(nodes, content_desc=d) for d in LOOP_DESCS)) + + +def _reveal_player_controls(): + """Tap the (rotated) frame centre until the auto-hiding controls are up in the + tree. Handles the one-time 'Got it' full-screen hint. Returns fresh player + nodes once controls show, else the last dump.""" + for _ in range(6): + nodes = ui() + if _controls_up(nodes): + return nodes + gi = find_node_ci(nodes, "Got it") + if gi: + tap_node(gi) + settle("tap") + continue + cx, cy = _dump_center(nodes) + if not cx: + break + tap(cx, cy) # frame-centre tap toggles controls on + settle("tap") + return ui() + + +def _player_topright_buttons(nodes): + """The four right-side top-bar icon Buttons, left->right = playlist / speed / + audio / subtitle. Located by class + top-strip y + right-half x (never a + hardcoded coordinate).""" + btns = [n for n in nodes + if n.get("class", "").endswith("Button") and n.get("clickable") == "true" + and n.get("_bounds") and n["_bounds"][1] < 300 + and n.get("_center") and n["_center"][0] > kit._screen_info["width"] * 0.6] + return sorted(btns, key=lambda n: n["_center"][0]) + + +def _flash_controls_for_shot(): + """Make the player control overlay VISIBLE for a screenshot. The overlay + fades ~1 s after appearing while the a11y tree lingers, so a plain reveal is + not enough — two rapid frame-centre taps (hide-if-up, then show) leave it + freshly rendered, and we return WITHOUT a ui() dump so the caller can screencap + before it fades.""" + base = ui() + cx, cy = _dump_center(base) + if not cx: + return + tap(cx, cy) + time.sleep(0.25) + tap(cx, cy) + time.sleep(0.25) + + +# ══════════════════════════════════════════════════════════════════════════════ +# Depth-family navigation helpers. Named and_enter_*/and_reach_* so the depth +# audit finds a backing call for every declared depth>=1 / jump_kind="reach". +# Each proves its jump with and_reach() (target appeared + source vanished) and +# increments the surface counter via and_enter(). +# ══════════════════════════════════════════════════════════════════════════════ + +def and_reach_settings(): + """Home -> Settings. Returns fresh Settings nodes or [].""" + nodes = home_ready() + if not nodes: + return [] + before = and_showing(nodes) + tap_topbar(nodes, "Settings") + settle("tap") + after_nodes = ui() + if and_reach(before, and_showing(after_nodes), "Appearance", FOLDER_NAME) or \ + (find_node(after_nodes, text="Appearance") and find_node(after_nodes, text="About")): + and_enter("settings") + return after_nodes + return [] + + +def and_reach_settings_sub(settings_nodes, row, target, source=SETTINGS_SIBLING): + """Settings root -> a subscreen. Proves target appeared + source (a root + sibling row) vanished. Counts one surface. Returns fresh sub nodes or []. + + After the tap the subscreen animates in, so we poll the dump a few times until + the target row has actually rendered before rendering the verdict — otherwise + a dump caught mid-transition can miss it (an observed flake).""" + node = find_node(settings_nodes, text=row) or scroll_into_view(row) + if not node: + return [] + before = and_showing(ui()) + if not tap_node(node): + return [] + after_nodes = ui() + for _ in range(3): + if find_node(after_nodes, text=target): + break + settle("tap") + after_nodes = ui() + if and_reach(before, and_showing(after_nodes), target, source) or \ + (find_node(after_nodes, text=target) and not find_node(after_nodes, text=source)): + and_enter(row.lower()) + return after_nodes + return [] + + +def and_reach_folder(name=FOLDER_NAME): + """Home -> the named folder. Proves 'Navigate up' appeared + the Home-only + '3 Videos' badge vanished. Returns fresh folder nodes or [].""" + nodes = home_ready() + row = find_node(nodes, text=name) + if not row: + return [] + before = and_showing(nodes) + if not tap_node(row): + return [] + after_nodes = ui() + if and_reach(before, and_showing(after_nodes), NAV_UP, FOLDER_COUNT) or \ + find_node(after_nodes, content_desc=NAV_UP): + and_enter("folder") + return after_nodes + return [] + + +def and_reach_player(title=VIDEO_BETA): + """Home -> folder -> tap a video row -> PlayerActivity. Proves 'Play/Pause' + appeared + folder's 'Navigate up' vanished, then reveals the controls and + installs landscape geometry. Returns fresh player nodes or [].""" + folder_nodes = and_reach_folder() + if not folder_nodes: + return [] + row = find_node(folder_nodes, text=title) + if not row: + return [] + before = and_showing(folder_nodes) # portrait geometry OK here + if not tap_node(row): + return [] + settle("launch") # PlayerActivity start + autoplay + kit._screen_info = None # drop the stale portrait cache + player_nodes = _reveal_player_controls() + _use_landscape_geom(player_nodes) # now controls are in-frame + if and_reach(before, and_showing(player_nodes), PLAYER_MARKER, NAV_UP) or \ + find_node(player_nodes, content_desc=PLAYER_MARKER): + and_enter("player") + return player_nodes + return [] + + +def and_reach_player_dialog(which, target, tries=6): + """From a fresh player, open the named top-bar dialog (which in + {'speed','audio','subtitle'}) and PROVE the jump: target appeared + + 'Play/Pause' vanished. + + The overlay fades ~1 s after a centre tap even while the a11y tree still + lists it, so we (1) learn the icon coordinate from one reveal, then (2) tap + the frame centre and IMMEDIATELY tap the icon with no ui() dump between them + (a dump is slow enough to miss the visible window). Retries hide the overlay + between attempts so the next centre tap re-shows it. Counts one surface + (depth 3 from Home). Returns the dialog nodes or [].""" + if not and_reach_player(): + return [] + idx = PLAYER_ICON[which] + shown = _reveal_player_controls() + _use_landscape_geom(shown) + btns = _player_topright_buttons(shown) + if len(btns) <= idx: + return [] + cx, cy = _dump_center(shown) + bx, by = btns[idx]["_center"] + before = and_showing(shown) # contains 'Play/Pause' from the reveal + for _ in range(tries): + tap(cx, cy) # show controls + time.sleep(0.35) + tap(bx, by) # tap the icon within the visible window + settle("tap") + dlg = ui() + if find_node(dlg, text=target): + if and_reach(before, and_showing(dlg), target, PLAYER_MARKER) or \ + find_node(dlg, text=target): + and_enter("player_dialog") + return dlg + if _controls_up(dlg): + tap(cx, cy) # controls left up -> hide for next try + settle("tap") + return [] + + +def and_open_search(): + """Home -> Search. Proves 'Popular folders' appeared + the Home 'Menu' + control vanished. Returns fresh search nodes or [].""" + nodes = home_ready() + if not nodes: + return [] + before = and_showing(nodes) + tap_topbar(nodes, "Search") + settle("tap") + after_nodes = ui() + if and_reach(before, and_showing(after_nodes), "Popular folders", "Menu") or \ + find_node(after_nodes, text="Popular folders"): + and_enter("search") + return after_nodes + return [] + + +def _find_fab(nodes): + """The bottom-right expand FAB: a desc-less, text-less clickable View in the + lower-right quadrant. Derived from a fresh dump — never a hardcoded coord.""" + s = get_screen_info() + best = None + for n in nodes: + if n.get("clickable") != "true": + continue + if n.get("text", "").strip() or n.get("content-desc", "").strip(): + continue + b = n.get("_bounds") + if not b: + continue + cx, cy = n["_center"] + if cx < s["width"] * 0.6 or cy < s["height"] * 0.6: + continue + w, h = b[2] - b[0], b[3] - b[1] + if w < 60 or h < 60 or w > s["width"] * 0.6: + continue + if best is None or (cy + cx) > (best["_center"][1] + best["_center"][0]): + best = n + return best + + +def and_open_fab_menu(): + """Home -> tap FAB -> the 3-pill expanded menu. Proves 'Open network stream' + appeared. Returns fresh menu nodes or [].""" + nodes = home_ready() + fab = _find_fab(nodes) + if not fab: + return [] + before = and_showing(nodes) + if not tap_node(fab): + return [] + after_nodes = ui() + if and_reach(before, and_showing(after_nodes), "Open network stream", source=None) or \ + find_node(after_nodes, text="Open network stream"): + and_enter("fab_menu") + return after_nodes + return [] + + +def and_reach_network_dialog(): + """Home -> FAB menu -> 'Open network stream' -> Network Stream dialog. Proves + 'Network Stream' appeared + the sibling pill 'Open local video' vanished. + Counts a second surface (depth 2 from Home). Returns dialog nodes or [].""" + menu = and_open_fab_menu() + if not menu: + return [] + pill = find_node(menu, text="Open network stream") + if not pill: + return [] + before = and_showing(menu) + if not tap_node(pill): + return [] + settle("tap") + dlg = ui() + if and_reach(before, and_showing(dlg), "Network Stream", "Open local video") or \ + find_node(dlg, text="Network Stream"): + and_enter("network_dialog") + return dlg + return [] + + +# ══════════════════════════════════════════════════════════════════════════════ +# (1) Home -> Settings. depth=1, reach. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_home_to_settings", "navigation_settings_rendered_vlm")) +def test_home_to_settings(): + settings_nodes = and_reach_settings() + ok = bool(settings_nodes) and bool(find_node(settings_nodes, text="Appearance")) + record("navigation_home_to_settings", ok, + "" if ok else "feature_missing: Settings surface not reached from the Home gear", + depth=1, jump_kind="reach", + expect="Settings category list ('Appearance') visible; Home 'Download' row gone") + + vlm_assert("navigation_settings_rendered", + "Is this a settings screen showing a vertical single-column list of " + "category rows, each with a small leading icon on the left, and a " + "back arrow at the top-left?", + RESULTS_DIR, depth=1, jump_kind="reach", tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (2) Settings -> Appearance -> BACK -> Settings. depth=2 round trip, reach. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_settings_to_appearance", + "navigation_appearance_back_to_settings")) +def test_appearance_roundtrip(): + settings_nodes = and_reach_settings() + sub = and_reach_settings_sub(settings_nodes, "Appearance", "Dark theme", + source=SETTINGS_SIBLING) + fwd_ok = bool(sub) and bool(find_node(sub, text="Dark theme")) + record("navigation_settings_to_appearance", fwd_ok, + "" if fwd_ok else "feature_missing: Appearance subscreen not reached", + depth=2, jump_kind="reach", + expect="'Dark theme' row visible; sibling 'Media library' row gone") + + # BACK unwinds one hop: the sibling rows return and the sub content is gone. + back_before = and_showing(ui()) + and_back() + back_after = ui() + back_ok = (and_reach(back_before, and_showing(back_after), + SETTINGS_SIBLING, "Dark theme") + or (find_node(back_after, text=SETTINGS_SIBLING) + and not find_node(back_after, text="Dark theme"))) + record("navigation_appearance_back_to_settings", bool(fwd_ok and back_ok), + "" if (fwd_ok and back_ok) + else "behavior_wrong: BACK did not restore the Settings category list", + depth=1, jump_kind="reach", + expect="Settings root restored ('Media library' back, 'Dark theme' gone) after one BACK") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (3) Settings -> Media library. depth=2, reach. (source is a different root row.) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_settings_to_media_library",)) +def test_settings_to_media_library(): + settings_nodes = and_reach_settings() + sub = and_reach_settings_sub(settings_nodes, "Media library", + "Mark last played media", source=SETTINGS_SIBLING_ALT) + ok = bool(sub) and bool(find_node(sub, text="Mark last played media")) + record("navigation_settings_to_media_library", ok, + "" if ok else "feature_missing: Media library subscreen not reached", + depth=2, jump_kind="reach", + expect="'Mark last played media' row visible; sibling 'Appearance' row gone") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (4) Settings -> Player. depth=2, reach. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_settings_to_player_settings",)) +def test_settings_to_player_settings(): + settings_nodes = and_reach_settings() + sub = and_reach_settings_sub(settings_nodes, "Player", "Material You controls", + source=SETTINGS_SIBLING) + ok = bool(sub) and bool(find_node(sub, text="Material You controls")) + record("navigation_settings_to_player_settings", ok, + "" if ok else "feature_missing: Player settings subscreen not reached", + depth=2, jump_kind="reach", + expect="'Material You controls' row visible; sibling 'Media library' row gone") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (5) Settings -> About. depth=2, reach. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_settings_to_about",)) +def test_settings_to_about(): + settings_nodes = and_reach_settings() + sub = and_reach_settings_sub(settings_nodes, "About", "by anilbeesetti", + source=SETTINGS_SIBLING) + ok = bool(sub) and bool(find_node(sub, text="by anilbeesetti")) + record("navigation_settings_to_about", ok, + "" if ok else "feature_missing: About subscreen not reached", + depth=2, jump_kind="reach", + expect="'by anilbeesetti' credit visible; sibling 'Media library' row gone") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (6) Settings -> Audio / Subtitle / Gestures. depth=2 each, reach. (breadth) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_settings_to_audio",)) +def test_settings_to_audio(): + settings_nodes = and_reach_settings() + sub = and_reach_settings_sub(settings_nodes, "Audio", "Volume boost", + source=SETTINGS_SIBLING) + ok = bool(sub) and bool(find_node(sub, text="Volume boost")) + record("navigation_settings_to_audio", ok, + "" if ok else "feature_missing: Audio subscreen not reached", + depth=2, jump_kind="reach", + expect="'Volume boost' row visible; sibling 'Media library' row gone") + + +@and_test(expects=("navigation_settings_to_subtitle",)) +def test_settings_to_subtitle(): + settings_nodes = and_reach_settings() + sub = and_reach_settings_sub(settings_nodes, "Subtitle", "Embedded styles", + source=SETTINGS_SIBLING) + ok = bool(sub) and bool(find_node(sub, text="Embedded styles")) + record("navigation_settings_to_subtitle", ok, + "" if ok else "feature_missing: Subtitle subscreen not reached", + depth=2, jump_kind="reach", + expect="'Embedded styles' row visible; sibling 'Media library' row gone") + + +@and_test(expects=("navigation_settings_to_gestures",)) +def test_settings_to_gestures(): + settings_nodes = and_reach_settings() + sub = and_reach_settings_sub(settings_nodes, "Gestures", "Seek gesture", + source=SETTINGS_SIBLING) + ok = bool(sub) and bool(find_node(sub, text="Seek gesture")) + record("navigation_settings_to_gestures", ok, + "" if ok else "feature_missing: Gestures subscreen not reached", + depth=2, jump_kind="reach", + expect="'Seek gesture' row visible; sibling 'Media library' row gone") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (7) Home -> Download folder. depth=1, reach. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_home_to_folder",)) +def test_home_to_folder(): + folder_nodes = and_reach_folder() + ok = bool(folder_nodes) and bool(find_node(folder_nodes, text=VIDEO_BETA)) \ + and bool(find_node(folder_nodes, content_desc=NAV_UP)) + record("navigation_home_to_folder", ok, + "" if ok else "feature_missing: Download folder contents not reached", + depth=1, jump_kind="reach", + expect="'Navigate up' + video rows visible; Home '3 Videos' badge gone") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (8) Folder -> Player. depth=2 from Home (Home->folder->player). reach. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_folder_to_player", "navigation_player_overlay_vlm")) +def test_folder_to_player(): + player_nodes = and_reach_player(VIDEO_BETA) + ok = bool(player_nodes) and bool(find_node(player_nodes, content_desc=PLAYER_MARKER)) + record("navigation_folder_to_player", ok, + "" if ok else "feature_missing: PlayerActivity (Play/Pause) not reached from the folder", + depth=2, jump_kind="reach", + expect="player 'Play/Pause' control visible; folder 'Navigate up' gone") + + # The overlay fades within ~1 s while the a11y tree lingers, so flash it fresh + # (two rapid centre taps) and screenshot immediately (vlm_assert's screencap + # runs first thing, before it fades again). + if ok: + _flash_controls_for_shot() + vlm_assert("navigation_player_overlay", + "Is there a play/pause control in the CENTRE of the screen and a " + "horizontal seek bar in the LOWER part of the screen?", + RESULTS_DIR, depth=2, jump_kind="reach", tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (9) Player -> BACK -> Folder. back-stack integrity, depth=2 forward. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_player_back_to_folder",)) +def test_player_back_to_folder(): + player_nodes = and_reach_player(VIDEO_BETA) + reached = bool(player_nodes) and bool(find_node(player_nodes, content_desc=PLAYER_MARKER)) + before = and_showing(player_nodes) if reached else set() + and_back() + kit._screen_info = None # returning to portrait picker + settle("tap") + folder_after = ui() + back_ok = reached and ( + and_reach(before, and_showing(folder_after), NAV_UP, PLAYER_MARKER) + or (find_node(folder_after, content_desc=NAV_UP) + and not find_node(folder_after, content_desc=PLAYER_MARKER))) + record("navigation_player_back_to_folder", bool(back_ok), + "" if back_ok else "behavior_wrong: BACK from the player did not return to the folder", + depth=2, jump_kind="reach", + expect="folder 'Navigate up' restored, player 'Play/Pause' gone after one BACK") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (10) Folder -> BACK -> Home. back-stack integrity, depth=1 forward. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_folder_back_to_home",)) +def test_folder_back_to_home(): + folder_nodes = and_reach_folder() + reached = bool(folder_nodes) and bool(find_node(folder_nodes, content_desc=NAV_UP)) + before = and_showing(folder_nodes) if reached else set() + and_back() + settle("tap") + home_after = ui() + back_ok = reached and ( + and_reach(before, and_showing(home_after), FOLDER_COUNT, NAV_UP) + or (find_node(home_after, text=FOLDER_COUNT) + and not find_node(home_after, content_desc=NAV_UP))) + record("navigation_folder_back_to_home", bool(back_ok), + "" if back_ok else "behavior_wrong: BACK from the folder did not return Home", + depth=1, jump_kind="reach", + expect="Home '3 Videos' badge restored, folder 'Navigate up' gone after one BACK") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (11) Home -> Search. depth=1, reach. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_home_to_search", "navigation_search_rendered_vlm")) +def test_home_to_search(): + search_nodes = and_open_search() + ok = bool(search_nodes) and bool(find_node(search_nodes, text="Popular folders")) + record("navigation_home_to_search", ok, + "" if ok else "feature_missing: Search surface not reached from the Home search icon", + depth=1, jump_kind="reach", + expect="'Popular folders' section visible; Home 'Menu' control gone") + + vlm_assert("navigation_search_rendered", + "Is there a search input field spanning the TOP of the screen " + "(with a back arrow to its left), above the rest of the content?", + RESULTS_DIR, depth=1, jump_kind="reach", tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (12) Search -> BACK -> Home. back-stack integrity. The search field auto-focuses +# the keyboard, so the first BACK dismisses the IME and a second returns Home. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_search_back_to_home",)) +def test_search_back_to_home(): + search_nodes = and_open_search() + reached = bool(search_nodes) and bool(find_node(search_nodes, text="Popular folders")) + before = and_showing(search_nodes) if reached else set() + home_after = search_nodes + # Up to two BACKs: one may only close the soft keyboard. + for _ in range(2): + and_back() + settle("tap") + home_after = ui() + if find_node(home_after, content_desc="Menu"): + break + back_ok = reached and ( + and_reach(before, and_showing(home_after), "Menu", "Popular folders") + or (find_node(home_after, content_desc="Menu") + and not find_node(home_after, text="Popular folders"))) + record("navigation_search_back_to_home", bool(back_ok), + "" if back_ok else "behavior_wrong: BACK from Search did not return Home", + depth=1, jump_kind="reach", + expect="Home 'Menu' control restored, 'Popular folders' gone after BACK") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (13) FAB -> Network Stream dialog -> Cancel -> Home. depth=2 forward, reach. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_fab_to_network_dialog", + "navigation_network_dialog_cancel_home")) +def test_network_dialog_roundtrip(): + dlg = and_reach_network_dialog() + fwd_ok = bool(dlg) and bool(find_node(dlg, text="Network Stream")) \ + and bool(find_by_class(dlg, "EditText")) + record("navigation_fab_to_network_dialog", fwd_ok, + "" if fwd_ok else "feature_missing: Network Stream dialog not reached via the FAB", + depth=2, jump_kind="reach", + expect="'Network Stream' title + URL EditText visible; pill 'Open local video' gone") + + # Cancel dismisses the dialog and restores Home. + cancel = find_node(dlg, text="Cancel") if dlg else None + before = and_showing(dlg) if dlg else set() + tapped = tap_node(cancel) if cancel else False + settle("tap") + home_after = ui() + cancel_ok = fwd_ok and tapped and ( + and_reach(before, and_showing(home_after), FOLDER_NAME, "Network Stream") + or (find_node(home_after, text=FOLDER_NAME) + and not find_node(home_after, text="Network Stream"))) + record("navigation_network_dialog_cancel_home", bool(cancel_ok), + "" if cancel_ok else "behavior_wrong: Cancel did not dismiss the dialog back to Home", + depth=1, jump_kind="reach", + expect="Home 'Download' restored, 'Network Stream' dialog gone after Cancel") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (14) Player -> Playback speed dialog -> BACK -> Player. depth=3 forward, reach. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_player_to_speed_dialog", + "navigation_speed_dialog_back_to_player", + "navigation_speed_dialog_rendered_vlm")) +def test_player_speed_dialog(): + dlg = and_reach_player_dialog("speed", "Select playback speed") + fwd_ok = bool(dlg) and bool(find_node(dlg, text="Select playback speed")) + record("navigation_player_to_speed_dialog", fwd_ok, + "" if fwd_ok else "feature_missing: playback-speed dialog not reached from the player", + depth=3, jump_kind="reach", + expect="'Select playback speed' dialog visible; player 'Play/Pause' gone") + + # The dialog stays up (it does not auto-hide) -> screenshot it for the VLM. + vlm_assert("navigation_speed_dialog_rendered", + "Is a dialog titled about playback speed showing a grid of small " + "rounded speed-value chips (like 0.5, 1.0, 2.0) arranged in rows?", + RESULTS_DIR, depth=3, jump_kind="reach", tag="shape") + + # BACK dismisses the dialog; the player controls become reachable again. + before = and_showing(dlg) if dlg else set() + and_back() + settle("tap") + after = _reveal_player_controls() + _use_landscape_geom(after) + back_ok = fwd_ok and ( + and_reach(before, and_showing(after), PLAYER_MARKER, "Select playback speed") + or (find_node(after, content_desc=PLAYER_MARKER) + and not find_node(after, text="Select playback speed"))) + record("navigation_speed_dialog_back_to_player", bool(back_ok), + "" if back_ok else "behavior_wrong: BACK did not return from the speed dialog to the player", + depth=2, jump_kind="reach", + expect="player 'Play/Pause' reachable again, speed dialog gone after BACK") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (15) Player -> Audio track dialog. depth=3 forward, reach. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_player_to_audio_dialog", + "navigation_audio_dialog_rendered_vlm")) +def test_player_audio_dialog(): + dlg = and_reach_player_dialog("audio", "Select audio track") + ok = bool(dlg) and bool(find_node(dlg, text="Select audio track")) \ + and bool(find_node(dlg, text="Audio Track #1")) + record("navigation_player_to_audio_dialog", ok, + "" if ok else "feature_missing: audio-track dialog not reached from the player", + depth=3, jump_kind="reach", + expect="'Select audio track' + 'Audio Track #1' visible; player 'Play/Pause' gone") + + vlm_assert("navigation_audio_dialog_rendered", + "Is a dialog titled about audio track showing a vertical list of " + "selectable track options (one row highlighted/selected)?", + RESULTS_DIR, depth=3, jump_kind="reach", tag="layout") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (16) Player -> Subtitle track dialog. depth=3 forward, reach. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_player_to_subtitle_dialog", + "navigation_subtitle_dialog_rendered_vlm")) +def test_player_subtitle_dialog(): + dlg = and_reach_player_dialog("subtitle", "Select subtitle track") + ok = bool(dlg) and bool(find_node(dlg, text="Select subtitle track")) \ + and bool(find_node(dlg, text="Open local subtitle")) + record("navigation_player_to_subtitle_dialog", ok, + "" if ok else "feature_missing: subtitle-track dialog not reached from the player", + depth=3, jump_kind="reach", + expect="'Select subtitle track' + 'Open local subtitle' visible; player 'Play/Pause' gone") + + vlm_assert("navigation_subtitle_dialog_rendered", + "Is a dialog titled about subtitle track showing two numeric " + "stepper controls near the bottom (each with - and + buttons " + "around a value)?", + RESULTS_DIR, depth=3, jump_kind="reach", tag="shape") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (17) Deep chain showcase: Home -> Settings -> Player -> BACK -> Settings -> +# BACK -> Home. Asserts the correct surface at each hop; the deepest reach +# (the Player subscreen at depth 2) is proven with and_reach. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_deep_chain_settings_player",)) +def test_deep_chain_settings_player(): + settings_nodes = and_reach_settings() # hop 1: Home -> Settings + if not settings_nodes: + record("navigation_deep_chain_settings_player", False, + "setup_failed: Settings not reached for the deep chain", + depth=2, jump_kind="reach", + expect="Player sub at depth 2, then BACK->Settings->Home unwinds each hop") + return + sub = and_reach_settings_sub(settings_nodes, "Player", "Material You controls", + source=SETTINGS_SIBLING) # hop 2: -> Player sub + deep_ok = bool(sub) and bool(find_node(sub, text="Material You controls")) + + # BACK to Settings root (sibling rows return, sub content gone). + b1 = and_showing(ui()) + and_back() + settings_again = ui() + up1_ok = (and_reach(b1, and_showing(settings_again), SETTINGS_SIBLING, + "Material You controls") + or (find_node(settings_again, text=SETTINGS_SIBLING) + and not find_node(settings_again, text="Material You controls"))) + + # BACK to Home (Home folder badge returns, Settings category rows gone). + b2 = and_showing(settings_again) + and_back() + settle("tap") + home_again = ui() + up2_ok = (and_reach(b2, and_showing(home_again), FOLDER_COUNT, "About") + or (find_node(home_again, text=FOLDER_COUNT) + and not find_node(home_again, text="About"))) + + ok = deep_ok and up1_ok and up2_ok + msg = "" + if not deep_ok: + msg = "feature_missing: could not reach the Player subscreen at depth 2" + elif not up1_ok: + msg = "behavior_wrong: first BACK did not return to the Settings root" + elif not up2_ok: + msg = "behavior_wrong: second BACK did not return Home" + record("navigation_deep_chain_settings_player", ok, msg, + depth=2, jump_kind="reach", + expect="Player sub reached at depth 2; BACK->Settings root->Home unwinds each hop") + + +TESTS = [ + test_home_to_settings, + test_appearance_roundtrip, + test_settings_to_media_library, + test_settings_to_player_settings, + test_settings_to_about, + test_settings_to_audio, + test_settings_to_subtitle, + test_settings_to_gestures, + test_home_to_folder, + test_folder_to_player, + test_player_back_to_folder, + test_folder_back_to_home, + test_home_to_search, + test_search_back_to_home, + test_network_dialog_roundtrip, + test_player_speed_dialog, + test_player_audio_dialog, + test_player_subtitle_dialog, + test_deep_chain_settings_player, +] + +if __name__ == "__main__": + run_suite(TESTS, "navigation") diff --git a/android/anilbeesetti-nextplayer/tests/test_android_states.py b/android/anilbeesetti-nextplayer/tests/test_android_states.py new file mode 100644 index 0000000000000000000000000000000000000000..f77d6f730c9b2aa9e0cc8ae59e6a500dc3f06028 --- /dev/null +++ b/android/anilbeesetti-nextplayer/tests/test_android_states.py @@ -0,0 +1,822 @@ +#!/usr/bin/env python3 +"""STATES lane for NextPlayer (dev.anilbeesetti.nextplayer.debug). + +This lane owns checked / selected / enabled / focused TRANSITIONS, each paired +with its app-authored consequence, page-level state and SETTINGS PERSISTENCE. +It is the sole owner of `checked` and `focused`. + +THE DEFINING QUIRK OF THIS APP (verified live before authoring): + Compose does NOT expose toggle/selection state in the accessibility tree. + Every Switch, segmented button and chip reports checked="false"/selected="false" + REGARDLESS of its visual on/off, and tapping does NOT flip the attr. So a bare + "the attr is X" assertion is worthless here. Every test below therefore pairs a + state TRIGGER with either + * a downstream RULE consequence that DOES surface in the tree + (the player Loop button's content-desc cycles One->All->Off->One; a + settings-row SUBTITLE text changes; the picker list flattens), or + * a VLM read of the rendered switch / highlight / checkmark. + We NEVER assert checked/selected for the Compose toggles. + +GEOMETRY QUIRK (verified live): the uiautomator dump's coordinate space follows +the CURRENT device rotation and does NOT always match `wm size` — the player +forces landscape (dump ~2400 wide) while the picker/settings follow the device +(portrait, ~1080 wide). get_screen_info()'s cached width would then reject valid +taps, so before tapping on any surface we install the CURRENT dump's own max +bounds into the kit's cached geometry (_use_dump_geom) — never a hardcoded +coordinate. The VLM screenshot is a normal capture, which is what the judge sees. + +NAV-STATE PERSISTENCE (verified live): NextPlayer remembers its last in-app +location, so restart_app() can resume straight into a settings subscreen or the +player rather than Home. home_ready() therefore presses BACK to unwind whatever +surface it lands on until the Home top bar (the 'Menu' icon) appears. + +QUICK SETTINGS (verified live): in this rendering the "Quick Settings" bottom +sheet carries exactly two segmented groups — Media view mode (Tree|Folders| +Videos, default Folders) and Media Layout (List|Grid, default List) — plus +Cancel/Done. The Sort/direction/Fields sections described for the portrait layout +are NOT present here, so this file does not test them (ground-truth rule: only +assert what was observed on the running original). + +APPEARANCE switch defaults (verified live from a screenshot of the original): + Dark theme = System Default; High contrast dark theme = OFF (thumb left); + Dynamic color theme = ON (thumb right, accent-filled track). The switch VLM + tests assert the OBSERVED post-tap rendered position against these defaults. + +PLAYER LOOP timing (verified live): the 8 s clip ENDS mid-cycle and then further +Loop taps are ignored, so both Loop tests PAUSE the video first (controls then +persist) before reading/cycling. + +Fixtures: the 3 sample videos are authored into fixtures/ and pushed by +push_fixtures() (run_suite() calls it once); reached via fixture_on_device(). + +CEDES (per lane contract): the wording of a consequence string -> text; whether +a screen is reachable -> navigation; a numeric consequence -> computation; user +record persistence -> interaction. Here we assert the STATE FLIP + its consequence. +""" +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 +import android_testgen_kit as kit # noqa: E402 (for the geometry cache) + +require_kit(1) + +# ── Ground-truth markers (observed on the running original) ───────────────────── +FOLDER_NAME = "Download" +VIDEO_BETA = "beta_movie" # 8 s clip — least race-prone in the player +FIXTURE_VIDEOS = ("alpha_clip.mp4", "beta_movie.mp4", "gamma_reel.mp4") +PLAYER_MARKER = "Play/Pause" # content-desc unique to the player +LOOP_DESCS = ("Loop: Off", "Loop: One", "Loop: All") +# The Loop button cycles in this fixed order on each tap (verified live). It +# PERSISTS across restarts, so we read the CURRENT value and assert the NEXT one. +LOOP_NEXT = {"Loop: Off": "Loop: One", "Loop: One": "Loop: All", "Loop: All": "Loop: Off"} + + +def next_loop(cur): + """The expected Loop desc after one tap, given the current desc.""" + return LOOP_NEXT.get(cur, "") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Geometry: the dump's coordinate space follows the device rotation and can differ +# from `wm size`, so derive it from the dump's own bounds and install it before +# any tap. +# ══════════════════════════════════════════════════════════════════════════════ + +def _use_dump_geom(nodes): + """Point the kit's cached geometry at the current dump's own max bounds so + tap_node()/and_showing() accept this surface's real coordinates. Call it after + every fresh ui() at a new surface — the space flips between the landscape + player (~2400 wide) and the portrait picker/settings (~1080 wide).""" + maxx = max((b[2] for b in (n.get("_bounds") for n in nodes) if b), default=1080) + maxy = max((b[3] for b in (n.get("_bounds") for n in nodes) if b), default=2400) + kit._screen_info = {"width": maxx, "height": maxy, "density": 420, + "center_x": maxx // 2, "center_y": maxy // 2} + + +def uig(): + """Fresh dump + install its geometry. The standard fetch in this file.""" + nodes = ui() + _use_dump_geom(nodes) + return nodes + + +# ══════════════════════════════════════════════════════════════════════════════ +# Setup helpers +# ══════════════════════════════════════════════════════════════════════════════ + +def and_grant_media(): + """Tap the runtime media-permission 'Allow all' if it is showing (no-op + otherwise). restart_app() keeps the grant, so this is just a safety net.""" + for label in ("Allow all", "While using the app", "Allow"): + n = find_node_ci(uig(), label) + if n: + tap_node(n) + settle("tap") + return True + return False + + +def _home_showing(nodes): + topbar = all(find_node(nodes, content_desc=d) for d in ("Search", "Menu", "Settings")) + body = bool(find_node(nodes, text=FOLDER_NAME)) or bool(find_node(nodes, text=VIDEO_BETA)) + return topbar and body + + +def home_ready(): + """restart (keeps media grant), then UNWIND to Home. NextPlayer persists its + last in-app location, so after launch we may be deep in settings or in the + player; we press BACK to pop one surface at a time (checking for the Home + 'Menu' icon BEFORE each BACK so we never exit the app from Home) until the + rendered Home shows. Installs geometry and guarantees the default Folders view. + Returns Home nodes (geometry installed) or [].""" + push_fixtures() + _ = [fixture_on_device(v) for v in FIXTURE_VIDEOS] # explicit dependency + nodes = [] + for _attempt in range(3): + restart_app() + if not wait_for_foreground(): + continue + and_grant_media() + reached = False + for _ in range(7): + nodes = uig() + if _home_showing(nodes): + reached = True + break + back() # pop a persisted subscreen/dialog/player + settle("tap") + if reached: + break + if not nodes or not _home_showing(nodes): + return [] + if not find_node(nodes, text=FOLDER_NAME): + nodes = _reset_view_mode() + return nodes + + +def _tap_topbar(nodes, desc): + """Tap a top-bar icon by content-desc via its tightest clickable ancestor + (the desc node itself is not clickable).""" + target = find_node(nodes, content_desc=desc) + if not target or "_bounds" not in target: + return False + tcx, tcy = target["_center"] + best, best_area = None, None + for n in nodes: + if n.get("clickable") != "true" or "_bounds" not in n: + continue + x1, y1, x2, y2 = n["_bounds"] + if x1 <= tcx <= x2 and y1 <= tcy <= y2: + area = (x2 - x1) * (y2 - y1) + if best_area is None or area < best_area: + best, best_area = n, area + return tap_node(best or target) + + +def _tap_clickable_ancestor(nodes, node): + """Tap the tightest clickable ancestor containing `node`'s centre (Compose + controls wrap a non-clickable label/icon in a clickable box).""" + if not node or "_center" not in node: + return False + tcx, tcy = node["_center"] + best, best_area = None, None + for n in nodes: + if n.get("clickable") != "true" or "_bounds" not in n: + continue + x1, y1, x2, y2 = n["_bounds"] + if x1 <= tcx <= x2 and y1 <= tcy <= y2: + area = (x2 - x1) * (y2 - y1) + if best_area is None or area < best_area: + best, best_area = n, area + return tap_node(best or node) + + +# ── Quick Settings sheet ──────────────────────────────────────────────────────── + +def and_enter_quick_settings(): + """Home -> tap the 'Menu' icon -> the 'Quick Settings' bottom sheet. Counts one + surface (backs a depth>=1 claim). Returns (sheet_nodes, home_nodes) where + home_nodes is the pre-sheet Home dump (so callers can read what was showing + BEFORE the sheet covered it), or ([], []) on failure.""" + nodes = home_ready() + if not nodes: + return [], [] + if not _tap_topbar(nodes, "Menu"): + return [], nodes + settle("tap") + sheet = uig() + if find_node(sheet, text="Quick Settings"): + and_enter("quick_settings") + return sheet, nodes + return [], nodes + + +def _qs_done(nodes): + d = find_node(nodes, text="Done") + if d: + tap_node(d) + settle("tap") + return True + return False + + +def _qs_cancel(nodes): + c = find_node(nodes, text="Cancel") + if c: + tap_node(c) + settle("tap") + return True + return False + + +def _reset_view_mode(): + """Normalize the picker to the default Folders view (prefs survive restart). + Opens Quick Settings from a plain home dump, selects Folders, taps Done. + Returns fresh home nodes.""" + nodes = uig() + if not _tap_topbar(nodes, "Menu"): + return uig() + settle("tap") + qs = uig() + if find_node(qs, text="Folders"): + tap_text(qs, "Folders") + settle("tap") + _qs_done(uig()) + return uig() + + +# ── Appearance settings ───────────────────────────────────────────────────────── + +def and_reach_appearance(): + """Home -> Settings -> Appearance. Counts two surfaces (depth 2). Returns the + Appearance nodes (geometry installed) or [].""" + nodes = home_ready() + if not nodes: + return [] + if not _tap_topbar(nodes, "Settings"): + return [] + settle("tap") + s = uig() + if not (find_node(s, text="Appearance") and find_node(s, text="About")): + return [] + and_enter("settings") + if not tap_text(s, "Appearance"): + return [] + settle("tap") + a = uig() + if find_node(a, text="Dark theme"): + and_enter("appearance") + return a + return [] + + +def _dark_theme_subtitle(nodes): + """The current 'Dark theme' row subtitle ('System Default' / 'Off' / 'On'). + It is the sibling text directly under the 'Dark theme' title, so read whichever + of the three known values is present on the Appearance screen.""" + for val in ("System Default", "On", "Off"): + if find_node(nodes, text=val): + return val + return "" + + +def _set_dark_theme(nodes, option): + """Open the Dark theme dialog and pick `option`. Returns fresh Appearance + nodes (geometry installed).""" + if not tap_text(nodes, "Dark theme"): + return uig() + settle("tap") + dlg = uig() + if find_node(dlg, text=option): + tap_text(dlg, option) + settle("tap") + else: + _qs_cancel(dlg) + return uig() + + +# ── Player (landscape; controls auto-hide) ────────────────────────────────────── + +def _controls_up(nodes): + return bool(find_node(nodes, content_desc=PLAYER_MARKER) + or any(find_node(nodes, content_desc=d) for d in LOOP_DESCS)) + + +def _in_player(): + """True while PlayerActivity is the resumed activity — used to detect the short + fixture ending and popping back to the folder mid-reveal.""" + return "PlayerActivity" in get_current_activity() + + +def _reveal_player_controls(): + """Bring the auto-hiding player controls up. Tap the frame centre (derived from + the landscape dump geometry, since get_screen_info reports portrait here) and + grab the controls FAST — the fixtures are short (8 s) and if we dawdle the clip + ends and PlayerActivity pops back to the folder. Returns player nodes with + controls up, or []. Does NOT restart a clip that ended (caller decides).""" + def _frame_center(nodes): + root = max(nodes, key=lambda n: (n["_bounds"][2] - n["_bounds"][0]) + * (n["_bounds"][3] - n["_bounds"][1])) if nodes else None + if not root: + return None + x1, y1, x2, y2 = root["_bounds"] + return (x1 + x2) // 2, (y1 + y2) // 2 + # Compute the tap point ONCE from the bare video frame and REUSE it. Once the + # controls overlay is up the largest node can change shape and re-computing the + # centre can flip it to the wrong (portrait) point, whose tap re-hides controls. + for _ in range(5): + if not _in_player(): + return [] # clip ended / popped to folder + p = uig() + if _controls_up(p): + return p + gi = find_node_ci(p, "Got it") + if gi: + tap_node(gi) + settle("tap") + continue + c = _frame_center(p) + if not c: + return [] + tap(*c) + time.sleep(0.4) + p = uig() + if _controls_up(p): + return p + + +def and_enter_player(title=VIDEO_BETA): + """Home -> Download folder -> tap the video row -> PlayerActivity, then reveal + the controls. Counts two surfaces (depth 2 from Home). Returns fresh player + nodes with controls up (geometry installed) or [].""" + nodes = home_ready() + if not nodes: + return [] + if not tap_text(nodes, FOLDER_NAME): + return [] + settle("tap") + folder = uig() + row = find_node(folder, text=title) + if not row: + return [] + and_enter("folder") + if not tap_node(row): + return [] + # PlayerActivity needs ~1s to start & autoplay, but the fixtures are only 8s — + # a full settle("launch") (3s) plus the reveal can outlast the clip, which then + # ends and pops back to the folder. Wait just long enough to start, then reveal + # FAST so we can pause before the clip runs out. + time.sleep(1.0) + kit._screen_info = None # drop the stale picker geometry + player = _reveal_player_controls() + if _controls_up(player): + and_enter("player") + return player + return [] + + +def _read_loop(nodes): + for d in LOOP_DESCS: + if find_node(nodes, content_desc=d): + return d + return "" + + +def _pause_player(nodes): + """Tap Play/Pause once so the short clip stops advancing and the controls + stay up — otherwise the 8 s clip ends mid-cycle and further Loop taps are + ignored (verified live). Retries a reveal so a Loop desc is present on return. + Returns fresh player nodes with controls up.""" + pp = find_node(nodes, content_desc=PLAYER_MARKER) + if pp: + tap_node(pp) + settle("tap") + p = _reveal_player_controls() + if not _read_loop(p): + p = _reveal_player_controls() + return p + + +def _loop_anchor_center(nodes): + """The pixel centre of the Loop button's clickable ancestor (its desc node is + not itself clickable), or None.""" + for d in LOOP_DESCS: + n = find_node(nodes, content_desc=d) + if not n or "_center" not in n: + continue + tcx, tcy = n["_center"] + best, best_area = None, None + for x in nodes: + if x.get("clickable") != "true" or "_bounds" not in x: + continue + x1, y1, x2, y2 = x["_bounds"] + if x1 <= tcx <= x2 and y1 <= tcy <= y2: + area = (x2 - x1) * (y2 - y1) + if best_area is None or area < best_area: + best, best_area = x, area + return (best or n)["_center"] + return None + + +def _advance_loop_once(prev): + """Tap the Loop button once and return its NEW desc, guaranteeing an advance + from `prev`. Re-reveals controls if they hid and re-taps (up to 3x) if the + change did not register on the first read. Assumes the video is PAUSED so the + controls persist. Returns the new desc, or "" if none could be read.""" + for _ in range(3): + nodes = _reveal_player_controls() + c = _loop_anchor_center(nodes) + if not c: + continue + adb_shell("input", "tap", c[0], c[1]) + settle("tap") + cur = _read_loop(uig()) + if not cur: + cur = _read_loop(_reveal_player_controls()) + if cur and cur != prev: + return cur + return _read_loop(_reveal_player_controls()) + + +def _flash_player_shot(): + """Make the auto-hiding player controls freshly visible for a screenshot: one + centre tap to (re)show them if they are down, then return immediately so the + caller's screencap runs before they fade.""" + nodes = uig() + if not _controls_up(nodes): + cx, cy = kit._screen_info["center_x"], kit._screen_info["center_y"] + tap(cx, cy) + time.sleep(0.4) + + +# ══════════════════════════════════════════════════════════════════════════════ +# A) PLAYER LOOP BUTTON — the one rule-observable state transition. depth=2. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_loop_advances", "states_loop_advances_vlm")) +def test_loop_advances_one_step(): + """Read the CURRENT Loop desc, tap once, assert it advanced to the correct + NEXT value in the {Off->One, One->All, All->Off} cycle. The value persists + across restarts, so we never assume a starting point. The video is PAUSED so + the clip cannot end between the read and the assert.""" + player = and_enter_player() + if not player: + record("states_loop_advances", False, + "setup_failed: could not reach the player controls to read Loop", + depth=2, jump_kind="transition", expect="Loop desc advances one step in the cycle") + record("states_loop_advances_vlm", False, + "setup_failed: player not reached", depth=2, jump_kind="none", tag="shape") + return + player = _pause_player(player) + before = _read_loop(player) + if not before: + record("states_loop_advances", False, + "feature_missing: no 'Loop: *' control in the player", + depth=2, jump_kind="transition", expect="Loop desc advances one step in the cycle") + record("states_loop_advances_vlm", False, + "feature_missing: no Loop control", depth=2, jump_kind="none", tag="shape") + return + expected = next_loop(before) + after = _advance_loop_once(before) + ok = after == expected and after != before + record("states_loop_advances", ok, + "" if ok else f"behavior_wrong: Loop was {before!r}, expected next {expected!r}, got {after!r}", + depth=2, jump_kind="transition", + expect=f"Loop desc {before} -> {expected} (advanced one step)") + + # VLM: a loop/repeat glyph is rendered among the bottom player controls. + _flash_player_shot() + vlm_assert("states_loop_advances", + "In the row of small player-control icons along the BOTTOM edge of " + "the screen, is there a circular loop / repeat arrows icon?", + RESULTS_DIR, depth=2, jump_kind="transition", tag="shape") + + +@and_test(expects=("states_loop_full_cycle",)) +def test_loop_full_cycle_returns(): + """From wherever the Loop currently is, three taps must walk the full cycle and + return to the start value (Off->One->All->Off etc). The video is PAUSED first + so the 8 s clip cannot end mid-cycle. Proves the whole 3-state machine.""" + player = and_enter_player() + if not player: + record("states_loop_full_cycle", False, + "setup_failed: could not reach the player controls", + depth=2, jump_kind="transition", expect="Loop returns to its start value after 3 taps") + return + player = _pause_player(player) + start = _read_loop(player) + if not start: + record("states_loop_full_cycle", False, + "feature_missing: no 'Loop: *' control in the player", + depth=2, jump_kind="transition", expect="Loop returns to its start value after 3 taps") + return + seq = [start] + prev = start + for _ in range(3): + nxt = _advance_loop_once(prev) + seq.append(nxt) + prev = nxt + steps_ok = all(seq[i + 1] == next_loop(seq[i]) for i in range(3)) + ok = steps_ok and seq[3] == start and seq[1] != start + record("states_loop_full_cycle", ok, + "" if ok else f"behavior_wrong: 3-tap cycle was {seq}, expected to return to {start!r}", + depth=2, jump_kind="transition", + expect=f"Loop cycles {start}->...->{start} over 3 taps (full 3-state machine)") + + +# ══════════════════════════════════════════════════════════════════════════════ +# B) QUICK SETTINGS segmented selection — VLM (a11y hides which is selected) + +# a downstream RULE consequence (Videos mode flattens the picker). depth=1. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_qs_grid_selected_vlm",)) +def test_qs_grid_selected(): + """Tap 'Grid' in Media Layout; VLM confirms the Grid segment became the + selected/highlighted one (was List). Pure-VLM probe -> Cancel to avoid + mutating global state. The selected attr is always false here, so this is + legitimately VLM-primary.""" + sheet, _home = and_enter_quick_settings() + if not sheet or not find_node(sheet, text="Grid"): + record("states_qs_grid_selected_vlm", False, + "feature_missing: no 'Grid' segment in Quick Settings", + depth=1, jump_kind="transition", tag="color") + return + tap_text(sheet, "Grid") + settle("tap") + _use_dump_geom(ui()) + vlm_assert("states_qs_grid_selected", + "In the 'Media Layout' segmented control (the List / Grid pair), is " + "the 'Grid' segment the highlighted/selected one — filled with a " + "distinct accent background colour while 'List' is not?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="color") + _qs_cancel(uig()) # dismiss without applying + + +@and_test(expects=("states_qs_videos_selected_vlm",)) +def test_qs_videos_selected(): + """Tap 'Videos' in Media view mode; VLM confirms Videos is now the selected + segment (highlight moved off Folders). Pure-VLM probe -> Cancel.""" + sheet, _home = and_enter_quick_settings() + if not sheet or not find_node(sheet, text="Videos"): + record("states_qs_videos_selected_vlm", False, + "feature_missing: no 'Videos' segment in Quick Settings", + depth=1, jump_kind="transition", tag="color") + return + tap_text(sheet, "Videos") + settle("tap") + _use_dump_geom(ui()) + vlm_assert("states_qs_videos_selected", + "In the 'Media view mode' segmented control (Tree / Folders / " + "Videos), is the 'Videos' segment the highlighted/selected one — " + "filled with a distinct accent background colour — rather than " + "'Folders'?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="color") + _qs_cancel(uig()) + + +@and_test(expects=("states_qs_folders_selected_vlm",)) +def test_qs_folders_selected_default(): + """The default Media view mode is Folders; VLM confirms 'Folders' is the + highlighted segment when the sheet opens fresh. Pure-VLM (selected attr is + always false) -> Cancel.""" + sheet, _home = and_enter_quick_settings() + if not sheet or not find_node(sheet, text="Folders"): + record("states_qs_folders_selected_vlm", False, + "feature_missing: no 'Folders' segment in Quick Settings", + depth=1, jump_kind="transition", tag="color") + return + vlm_assert("states_qs_folders_selected", + "In the 'Media view mode' segmented control (Tree / Folders / " + "Videos), is the 'Folders' segment the highlighted/selected one — " + "filled with a distinct accent background colour — while Tree and " + "Videos are not?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="color") + _qs_cancel(uig()) + + +@and_test(expects=("states_qs_videos_flattens", "states_qs_videos_flattens_vlm")) +def test_qs_videos_mode_flattens_list(): + """RULE consequence of the selection: switching Media view mode to Videos and + pressing Done flattens the picker — the 'Download' FOLDER row disappears and + the 3 video rows (alpha_clip/beta_movie/gamma_reel) appear at the top level. + `folder_before` is read from the PRE-sheet Home dump (the open sheet covers + the folder row). RESET back to Folders afterward.""" + sheet, home = and_enter_quick_settings() + if not sheet or not find_node(sheet, text="Videos"): + record("states_qs_videos_flattens", False, + "feature_missing: no 'Videos' segment in Quick Settings", + depth=1, jump_kind="transition", + expect="Videos mode: folder row gone, flat video rows shown") + record("states_qs_videos_flattens_vlm", False, + "feature_missing: no 'Videos' segment", depth=1, jump_kind="none", tag="layout") + return + folder_before = find_node(home, text=FOLDER_NAME) is not None + tap_text(sheet, "Videos") + settle("tap") + _qs_done(uig()) + result = uig() + folder_after = find_node(result, text=FOLDER_NAME) is not None + videos_present = all(find_node(result, text=v) is not None + for v in ("alpha_clip", VIDEO_BETA, "gamma_reel")) + ok = folder_before and (not folder_after) and videos_present + record("states_qs_videos_flattens", ok, + "" if ok else "behavior_wrong: Videos mode did not flatten the folder into a flat video list", + depth=1, jump_kind="transition", + expect="Videos mode: 'Download' folder row gone; alpha_clip/beta_movie/gamma_reel at top level") + + vlm_assert("states_qs_videos_flattens", + "Does the main list show individual video items each with its own " + "thumbnail and duration badge (a flat video list), rather than a " + "single folder entry?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="layout") + + # RESET: back to the default Folders view mode. + nodes = uig() + if _tap_topbar(nodes, "Menu"): + settle("tap") + qs = uig() + if find_node(qs, text="Folders"): + tap_text(qs, "Folders") + settle("tap") + _qs_done(uig()) + + +# ══════════════════════════════════════════════════════════════════════════════ +# C) APPEARANCE — Dark theme dialog RULE consequence (subtitle) + rendered-dark +# VLM + the two switch toggles (VLM). depth=2/3. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_dark_theme_on_subtitle", "states_dark_theme_on_vlm")) +def test_dark_theme_on_changes_subtitle(): + """Open the 'Dark theme' dialog, pick 'On'; the row SUBTITLE (which DOES + surface in the tree) must change from 'System Default' to 'On'. Then VLM + confirms the whole UI actually rendered dark. RESET to System Default after.""" + a = and_reach_appearance() + if not a: + record("states_dark_theme_on_subtitle", False, + "setup_failed: Appearance screen not reached", + depth=3, jump_kind="transition", expect="Dark theme subtitle 'System Default' -> 'On'") + record("states_dark_theme_on_vlm", False, + "setup_failed: Appearance not reached", depth=3, jump_kind="none", tag="color") + return + if not find_node(a, text="Dark theme"): + record("states_dark_theme_on_subtitle", False, + "feature_missing: no 'Dark theme' row in Appearance", + depth=3, jump_kind="transition", expect="Dark theme subtitle 'System Default' -> 'On'") + record("states_dark_theme_on_vlm", False, + "feature_missing: no Dark theme row", depth=3, jump_kind="none", tag="color") + return + before = _dark_theme_subtitle(a) + a = _set_dark_theme(a, "On") + and_enter("dark_theme_dialog") # opened + dismissed a dialog surface + after = _dark_theme_subtitle(a) + ok = after == "On" and before != "On" + record("states_dark_theme_on_subtitle", ok, + "" if ok else f"behavior_wrong: subtitle was {before!r}, expected 'On', got {after!r}", + depth=3, jump_kind="transition", + expect=f"Dark theme subtitle {before or 'System Default'} -> On") + + vlm_assert("states_dark_theme_on", + "Is the app using a DARK theme right now — a near-black or very dark " + "background with light/white text?", + RESULTS_DIR, depth=3, jump_kind="transition", tag="color") + + _set_dark_theme(uig(), "System Default") # RESET + + +@and_test(expects=("states_high_contrast_switch_vlm",)) +def test_high_contrast_switch_toggles(): + """The 'High contrast dark theme' switch is OFF by default (verified). Tap it; + VLM confirms the thumb moved to the ON side (thumb RIGHT, accent-filled track). + checked attr is always false here, so this is legitimately VLM-primary. Tap + again to restore.""" + a = and_reach_appearance() + sw = find_node(a, text="High contrast dark theme") if a else None + if not sw: + record("states_high_contrast_switch_vlm", False, + "feature_missing: no 'High contrast dark theme' switch in Appearance", + depth=2, jump_kind="transition", tag="color") + return + _tap_clickable_ancestor(a, sw) + settle("tap") + _use_dump_geom(ui()) + vlm_assert("states_high_contrast_switch", + "For the 'High contrast dark theme' row, is its toggle switch now in " + "the ON position — the round thumb pushed to the RIGHT side of the " + "track with the track filled in a solid accent colour?", + RESULTS_DIR, depth=2, jump_kind="transition", tag="color") + a2 = uig() + sw2 = find_node(a2, text="High contrast dark theme") + if sw2: + _tap_clickable_ancestor(a2, sw2) # restore to OFF + settle("tap") + + +@and_test(expects=("states_dynamic_color_switch_vlm",)) +def test_dynamic_color_switch_toggles(): + """The 'Dynamic color theme' switch is ON by default (verified). Tap it OFF; + VLM confirms the thumb moved to the OFF side (thumb LEFT, unfilled/gray track). + VLM-primary (checked attr always false). Tap again to restore to ON.""" + a = and_reach_appearance() + sw = find_node(a, text="Dynamic color theme") if a else None + if not sw: + record("states_dynamic_color_switch_vlm", False, + "feature_missing: no 'Dynamic color theme' switch in Appearance", + depth=2, jump_kind="transition", tag="color") + return + _tap_clickable_ancestor(a, sw) + settle("tap") + _use_dump_geom(ui()) + vlm_assert("states_dynamic_color_switch", + "For the 'Dynamic color theme' row, is its toggle switch now in the " + "OFF position — the round thumb pushed to the LEFT side of the track " + "with the track NOT filled with an accent colour (gray/outline)?", + RESULTS_DIR, depth=2, jump_kind="transition", tag="color") + a2 = uig() + sw2 = find_node(a2, text="Dynamic color theme") + if sw2: + _tap_clickable_ancestor(a2, sw2) # restore to ON + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# D) SETTINGS PERSISTENCE — the strongest states signal. depth=2/3, transition. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_dark_theme_persists", "states_dark_theme_persists_vlm")) +def test_dark_theme_persists_across_navigation(): + """Set Dark theme = 'On', navigate AWAY (BACK to Settings root), then RE-ENTER + Appearance: the subtitle must STILL be 'On' (rule) and the screen still dark + (VLM). Proves the setting was persisted, not just held in the open dialog. + RESET to System Default after.""" + a = and_reach_appearance() + if not a or not find_node(a, text="Dark theme"): + record("states_dark_theme_persists", False, + "setup_failed: Appearance / Dark theme not reached", + depth=3, jump_kind="transition", expect="Dark theme subtitle still 'On' after leaving & re-entering") + record("states_dark_theme_persists_vlm", False, + "setup_failed: Appearance not reached", depth=3, jump_kind="none", tag="color") + return + a = _set_dark_theme(a, "On") + and_enter("dark_theme_dialog") + if _dark_theme_subtitle(a) != "On": + record("states_dark_theme_persists", False, + "setup_failed: could not set Dark theme to On before the persistence check", + depth=3, jump_kind="transition", expect="Dark theme subtitle still 'On' after re-entry") + record("states_dark_theme_persists_vlm", False, + "setup_failed: could not set On", depth=3, jump_kind="none", tag="color") + _set_dark_theme(uig(), "System Default") + return + + # Navigate away: BACK to the Settings root, confirm we left Appearance. + and_back() + settle("tap") + root = uig() + left = (find_node(root, text="Media library") is not None + and find_node(root, text="Appearance") is not None) + # Re-enter Appearance. + reentered = False + a2 = root + if left and tap_text(root, "Appearance"): + settle("tap") + a2 = uig() + reentered = find_node(a2, text="Dark theme") is not None + subtitle = _dark_theme_subtitle(a2) if reentered else "" + ok = left and reentered and subtitle == "On" + msg = "" + if not left: + msg = "behavior_wrong: BACK did not return to the Settings root" + elif not reentered: + msg = "setup_failed: could not re-enter Appearance" + elif subtitle != "On": + msg = f"behavior_wrong: after re-entry subtitle was {subtitle!r}, expected 'On' (setting not persisted)" + record("states_dark_theme_persists", ok, msg, + depth=3, jump_kind="transition", + expect="Dark theme subtitle STILL 'On' after leaving Appearance and re-entering") + + vlm_assert("states_dark_theme_persists", + "Is the app still using a DARK theme — a near-black or very dark " + "background with light/white text?", + RESULTS_DIR, depth=3, jump_kind="transition", tag="color") + + _set_dark_theme(uig(), "System Default") # RESET + + +TESTS = [ + test_loop_advances_one_step, + test_loop_full_cycle_returns, + test_qs_grid_selected, + test_qs_videos_selected, + test_qs_folders_selected_default, + test_qs_videos_mode_flattens_list, + test_dark_theme_on_changes_subtitle, + test_high_contrast_switch_toggles, + test_dynamic_color_switch_toggles, + test_dark_theme_persists_across_navigation, +] + +if __name__ == "__main__": + run_suite(TESTS, "states") diff --git a/android/anilbeesetti-nextplayer/tests/test_android_structure.py b/android/anilbeesetti-nextplayer/tests/test_android_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..17924553a2013fc3c4077c3f564a7ef0464ce5e0 --- /dev/null +++ b/android/anilbeesetti-nextplayer/tests/test_android_structure.py @@ -0,0 +1,718 @@ +#!/usr/bin/env python3 +"""STRUCTURE lane for NextPlayer (dev.anilbeesetti.nextplayer.debug). + +This lane owns exactly two things: + (1) the LAUNCH GATE — the app comes up, Home shows its top-level surfaces + (three top-bar icon controls by content-desc + the media list); jump_kind + "none", kept to a single case. + (2) tree-SHAPE deltas — an interaction changes the view-tree's SHAPE (child + count / arrangement / a new window layer), asserted by counting a widget + class or a marker-string set BEFORE and AFTER the user path, then reversed + to prove it restores. jump_kind "transition". + +Compose a11y does NOT expose toggle/selection state on this app (every Switch / +segment / chip reports checked=false selected=false regardless of visual state), +so this file NEVER asserts checked/selected — it asserts SHAPE (counts) or hands +the rendered-layout question to the VLM. + +IMPORTANT — the picker VIEW MODE (Folders/Videos/Tree) and LAYOUT (List/Grid) are +PERSISTED preferences that survive force-stop, so a test that switches to Videos +leaves the app in Videos on the next launch. Every test therefore normalizes the +picker back to Folders + List in home_ready() before it asserts, and tests that +mutate the mode restore it. This is what keeps the cases independent. + +Ground truth (observed on the running original, see recon.md + recon_shots/): + * Home top bar: 3 clickable Views whose child carries content-desc + "Search" / "Menu" / "Settings"; body is a list; a desc-less FAB View bottom-right. + * Every media/list/settings ROW carries a RadioButton child, so a RadioButton + COUNT is a robust row count: Home Folders view = 1 (the "Download" folder), + folder contents / Videos view = 3 (alpha/beta/gamma), Settings root = 9. + * FAB expands to 3 pill labels: "Open network stream" / "Open local video" / + "Recently played" (0 -> 3), and an X collapses them (3 -> 0). + * Menu opens a "Quick Settings" bottom sheet whose distinctive section headers + are {"Quick Settings","Media view mode","Media Layout","Sort","Fields"} plus + a "Done"/"Cancel" row (0 markers on Home -> 5 in the sheet). + * A video row opens PlayerActivity (landscape): picker markers ("Download" + title / "3 Videos") vanish, player marker content-desc "Play/Pause" appears. + * Search shows a "Popular folders" header (empty query); typing "beta" replaces + it with a "Videos (1)" result section (header shape change). + +Fixtures: the 3 sample videos (alpha_clip.mp4 / beta_movie.mp4 / gamma_reel.mp4) +are authored into fixtures/ and mirrored to the device by push_fixtures(); every +test reaches them through fixture_on_device(name), never a hand-pushed path. +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +require_kit(1) + +# ── Ground-truth marker sets (strings observed on the running original) ───────── +TOPBAR_DESCS = ("Search", "Menu", "Settings") +FAB_PILLS = ("Open network stream", "Open local video", "Recently played") +QS_MARKERS = ("Quick Settings", "Media view mode", "Media Layout", "Sort", "Fields") +SETTINGS_ROWS = 9 # Appearance ... About +PLAYER_MARKER = "Play/Pause" # content-desc that only exists in the player +PICKER_TITLE = "Next Player Debug" +FOLDER_NAME = "Download" +VIDEO_TITLES = ("alpha_clip", "beta_movie", "gamma_reel") +# The fixture videos the picker opens; declared via fixture_on_device so the +# dependency is explicit and the kit pushes the bytes on a fresh emulator. +FIXTURE_VIDEOS = ("alpha_clip.mp4", "beta_movie.mp4", "gamma_reel.mp4") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Helpers (setup / navigation). Navigation helpers are named and_enter_* so an +# and_enter() call backs every declared depth>=1 (see and_audit_depth). +# ══════════════════════════════════════════════════════════════════════════════ + +def and_grant_media(): + """Tap the runtime media-permission 'Allow all' if it is showing (no-op + otherwise). restart_app() keeps the grant, so this is just a safety net.""" + for label in ("Allow all", "While using the app", "Allow"): + n = find_node_ci(ui(), label) + if n: + tap_node(n) + settle("tap") + return True + return False + + +def tap_topbar(nodes, desc): + """Tap the top-bar icon by content-desc. The desc node itself is not + clickable — its PARENT View is — so tap the nearest clickable ancestor by + bounds containment, falling back to the desc node's centre.""" + target = find_node(nodes, content_desc=desc) + if not target or "_bounds" not in target: + return False + tcx, tcy = target["_center"] + best = None + best_area = None + for n in nodes: + if n.get("clickable") != "true" or "_bounds" not in n: + continue + x1, y1, x2, y2 = n["_bounds"] + if x1 <= tcx <= x2 and y1 <= tcy <= y2: # contains the icon centre + area = (x2 - x1) * (y2 - y1) + if best_area is None or area < best_area: # tightest clickable wrapper + best, best_area = n, area + return tap_node(best) if best else tap_node(target) + + +def open_quick_settings(nodes): + """Tap Menu; returns fresh nodes once the Quick Settings sheet is up.""" + tap_topbar(nodes, "Menu") + settle("tap") + return ui() + + +def in_folders_mode(nodes): + """Home is in the default Folders view iff the 'Download' folder row shows and + the flat video titles do not.""" + return bool(find_node(nodes, text=FOLDER_NAME)) and not any( + find_node(nodes, text=t) for t in VIDEO_TITLES) + + +def reset_view_mode(nodes): + """Normalize the picker to Folders + List (the app's default), because those + are PERSISTED across restart. Opens Quick Settings, selects Folders then List, + taps Done. Returns fresh Home nodes.""" + qs = open_quick_settings(nodes) + if find_node(qs, text="Folders"): + tap_text(qs, "Folders") + settle("tap") + if find_node(ui(), text="List"): + tap_text(ui(), "List") + settle("tap") + tap_node(find_node(ui(), text="Done")) + settle("tap") + return ui() + + +def _home_content_ready(nodes): + """True once the Home picker has actually rendered (top-bar controls plus a + folder row or the flat video titles), so we do not assert against a mid-load + or launcher screen. wait_for_foreground() alone is too loose — it matches the + package anywhere in the window dump even while backgrounded.""" + topbar = all(find_node(nodes, content_desc=d) for d in TOPBAR_DESCS) + body = bool(find_node(nodes, text=FOLDER_NAME)) or any( + find_node(nodes, text=t) for t in VIDEO_TITLES) + return topbar and body + + +def home_ready(normalize=True): + """Mirror the fixture videos, restart, grant media, WAIT until Home actually + rendered; return fresh Home nodes in the DEFAULT Folders+List mode. + + push_fixtures() is idempotent (run_suite() also calls it once); doing it here + keeps every test self-sufficient and makes the fixture dependency explicit — + the files land at fixture_on_device('beta_movie.mp4') etc. A launch can be + slow, so we poll for real content and retry the launch once; and because view + mode PERSISTS across restart, we reset it to Folders unless a caller opts out.""" + push_fixtures() + _ = [fixture_on_device(v) for v in FIXTURE_VIDEOS] # explicit dependency + nodes = [] + for attempt in range(2): + restart_app() + if not wait_for_foreground(): + continue + and_grant_media() + for _ in range(6): # poll for rendered Home + nodes = ui() + if _home_content_ready(nodes): + break + settle("dump") + if _home_content_ready(nodes): + break # launched cleanly + if not nodes: + return [] + if normalize and not in_folders_mode(nodes): + nodes = reset_view_mode(nodes) + return nodes + + +def count_rows(nodes): + """Number of media/list rows == number of RadioButton children on this app.""" + return len(find_by_class(nodes, "RadioButton")) + + +def marker_count(nodes, markers): + """How many of `markers` appear as an exact text/content-desc on screen.""" + present = 0 + for m in markers: + if find_node(nodes, text=m) or find_node(nodes, content_desc=m): + present += 1 + return present + + +def find_fab(nodes): + """The bottom-right expand FAB: a desc-less, text-less clickable View in the + lower-right quadrant. Derived from a fresh dump — never a hardcoded coord.""" + s = get_screen_info() + best = None + for n in nodes: + if n.get("clickable") != "true": + continue + if n.get("text", "").strip() or n.get("content-desc", "").strip(): + continue + b = n.get("_bounds") + if not b: + continue + cx, cy = n["_center"] + if cx < s["width"] * 0.6 or cy < s["height"] * 0.6: + continue + w, h = b[2] - b[0], b[3] - b[1] + if w < 60 or h < 60 or w > s["width"] * 0.6: # a real FAB, not a big panel + continue + if best is None or (cy + cx) > (best["_center"][1] + best["_center"][0]): + best = n + return best + + +def and_enter_settings(): + """Home -> Settings. Proves the jump (Settings list appears) and counts one + surface. Returns fresh Settings nodes or [].""" + nodes = home_ready() + before = and_showing(nodes) + tap_topbar(nodes, "Settings") + settle("tap") + after_nodes = ui() + after = and_showing(after_nodes) + if and_reach(before, after, "Appearance", source=None) or \ + find_node(after_nodes, text="Appearance"): + and_enter("settings") + return after_nodes + return [] + + +def and_enter_folder(name=FOLDER_NAME): + """Home (Folders view) -> tap the named folder -> folder contents. Proves the + jump ('Navigate up' present) and counts one surface. Returns fresh + folder-contents nodes or [].""" + nodes = home_ready() + row = find_node(nodes, text=name) + if not row: + return [] + before = and_showing(nodes) + tap_node(row) + settle("tap") + after_nodes = ui() + after = and_showing(after_nodes) + if and_reach(before, after, "Navigate up", source=None) or \ + find_node(after_nodes, content_desc="Navigate up"): + and_enter("folder") + return after_nodes + return [] + + +def dump_center(nodes): + """Centre of the CURRENT display in the dump's own coordinate frame. The + player is landscape but `wm size` still reports the physical portrait size, + so get_screen_info() cannot be trusted there; the dump's root bounds are in + the correct rotated frame (e.g. 2400x1080).""" + maxx = max((b[2] for b in (n.get("_bounds") for n in nodes) if b), default=0) + maxy = max((b[3] for b in (n.get("_bounds") for n in nodes) if b), default=0) + return (maxx // 2, maxy // 2) if maxx and maxy else (0, 0) + + +def reveal_player_controls(): + """Tap the (rotated) screen centre until the auto-hiding player controls are + up. Returns the fresh player nodes once 'Play/Pause' is present, else [].""" + for _ in range(5): + nodes = ui() + if find_node(nodes, content_desc=PLAYER_MARKER): + return nodes + cx, cy = dump_center(nodes) + if not cx: + break + tap(cx, cy) + settle("tap") + nodes = ui() + return nodes if find_node(nodes, content_desc=PLAYER_MARKER) else [] + + +def and_enter_player(title="beta_movie"): + """Home -> folder -> tap a video row -> PlayerActivity. Proves the jump + (player 'Play/Pause' appears), counts a second surface, and REVEALS the + auto-hiding controls. Returns fresh player nodes or [].""" + folder_nodes = and_enter_folder() + if not folder_nodes: + return [] + row = find_node(folder_nodes, text=title) + if not row: + return [] + before = and_showing(folder_nodes) + tap_node(row) + settle("launch") # PlayerActivity start + autoplay + global _screen_info + _screen_info = None # invalidate any cached (wrong) geometry + player_nodes = reveal_player_controls() + if player_nodes and ( + and_reach(before, and_showing(player_nodes), PLAYER_MARKER, source=None) + or find_node(player_nodes, content_desc=PLAYER_MARKER)): + and_enter("player") + return player_nodes + return [] + + +# ══════════════════════════════════════════════════════════════════════════════ +# (1) GATE — the one allowed existence case. jump_kind="none", depth=0. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_gate_launch", "structure_gate_home_vlm")) +def test_gate_launch(): + nodes = home_ready() + fg = wait_for_foreground() + container = bool(find_by_class(nodes, "FrameLayout")) + topbar = all(find_node(nodes, content_desc=d) for d in TOPBAR_DESCS) + folder = bool(find_node(nodes, text=FOLDER_NAME)) + ok = fg and container and topbar and folder + msg = "" + if not fg or not container: + msg = "setup_failed: app did not reach the foreground" + elif not topbar: + msg = "feature_missing: Home top bar lacks Search/Menu/Settings controls" + elif not folder: + msg = "setup_failed: Download folder row not visible (fixtures not scanned?)" + record("structure_gate_launch", ok, msg, depth=0, jump_kind="none") + + vlm_assert("structure_gate_home", + "In the top app bar of this video app, are there exactly three " + "icon buttons (a magnifier, a grid/menu icon, and a gear) on the " + "right side, arranged in a single horizontal row?", + RESULTS_DIR, depth=0, jump_kind="none", tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (2) FAB expand — SHAPE delta: 0 -> 3 pill labels. transition, depth=1. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_fab_expand", "structure_fab_expand_vlm")) +def test_fab_expand(): + nodes = home_ready() + before = marker_count(nodes, FAB_PILLS) # expect 0 + fab = find_fab(nodes) + tapped = tap_node(fab) if fab else False + settle("tap") + after_nodes = ui() + and_enter("fab_menu") # backs depth=1 + after = marker_count(after_nodes, FAB_PILLS) # expect 3 + ok = tapped and before == 0 and after == len(FAB_PILLS) + msg = "" + if not tapped: + msg = "setup_failed: FAB not found / not tappable" + elif after != len(FAB_PILLS): + msg = (f"behavior_wrong: FAB action pills {before}->{after}, " + f"expected 0->{len(FAB_PILLS)}") + record("structure_fab_expand", ok, msg, depth=1, jump_kind="transition", + expect=f"FAB action-pill labels {before}->{len(FAB_PILLS)} on expand") + + vlm_assert("structure_fab_expand", + "Are there exactly three rounded pill-shaped buttons stacked " + "vertically near the bottom-right (labelled about network stream, " + "local video, and recently played), each with a leading icon?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="shape") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (3) FAB collapse — reverse of (2): 3 pills -> 0. transition, depth=1. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_fab_collapse",)) +def test_fab_collapse(): + nodes = home_ready() + fab = find_fab(nodes) + tap_node(fab) + settle("tap") + expanded = ui() + and_enter("fab_menu") + n_open = marker_count(expanded, FAB_PILLS) # expect 3 + close = find_fab(expanded) # the X close FAB + tapped = tap_node(close) if close else False + settle("tap") + collapsed = ui() + and_back() + n_closed = marker_count(collapsed, FAB_PILLS) # expect 0 + ok = tapped and n_open == len(FAB_PILLS) and n_closed == 0 + msg = "" + if n_open != len(FAB_PILLS): + msg = f"setup_failed: FAB did not expand ({n_open} pills)" + elif n_closed != 0: + msg = (f"behavior_wrong: pills did not collapse " + f"({n_open}->{n_closed}, expected {len(FAB_PILLS)}->0)") + record("structure_fab_collapse", ok, msg, depth=1, jump_kind="transition", + expect=f"FAB pills {len(FAB_PILLS)}->0 on close (X)") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (4) View mode Folders -> Videos — SHAPE delta: 1 folder row -> 3 video rows. +# transition, depth=1. Tapping 'Done' dismisses the sheet (no extra BACK). +# Restored to Folders at the end so the next test starts clean. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_viewmode_folders_to_videos", + "structure_viewmode_folders_to_videos_vlm")) +def test_viewmode_folders_to_videos(): + nodes = home_ready() + rows_folders = count_rows(nodes) # expect 1 (Download) + qs = open_quick_settings(nodes) + and_enter("quick_settings") + ok_seg = tap_text(qs, "Videos") + settle("tap") + tap_node(find_node(ui(), text="Done")) # Done closes the sheet + settle("tap") + videos_nodes = ui() + rows_videos = count_rows(videos_nodes) # expect 3 (flat list) + files_present = sum(bool(find_node(videos_nodes, text=t)) for t in VIDEO_TITLES) + folder_gone = not find_node(videos_nodes, text=FOLDER_NAME) + ok = (ok_seg and rows_folders == 1 and rows_videos == 3 + and files_present == 3 and folder_gone) + msg = "" + if not ok_seg: + msg = "setup_failed: 'Videos' segment not found in Quick Settings" + elif rows_videos != 3: + msg = (f"behavior_wrong: rows {rows_folders}->{rows_videos}, " + f"expected 1 folder -> 3 videos") + elif files_present != 3: + msg = f"behavior_wrong: only {files_present}/3 video titles after switch" + elif not folder_gone: + msg = "behavior_wrong: folder row still present in Videos mode" + record("structure_viewmode_folders_to_videos", ok, msg, + depth=1, jump_kind="transition", + expect="RadioButton rows 1(folder)->3(videos); alpha/beta/gamma shown") + + # VLM before restoring, so the screenshot shows the 3-video list. + vlm_assert("structure_viewmode_folders_to_videos", + "Is this a single-column vertical list of exactly three video " + "items with red, blue and green thumbnails (top to bottom), " + "rather than one folder entry?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="color") + reset_view_mode(videos_nodes) # restore Folders+List + + +# ══════════════════════════════════════════════════════════════════════════════ +# (5) Media Layout List -> Grid — a RENDERED layout change. Rule track asserts +# the surface materially changed; the grid-vs-list judgement is VLM. +# transition, depth=1. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_layout_grid", "structure_layout_grid_vlm")) +def test_layout_grid(): + nodes = home_ready() + # Switch to Videos first (several items) so a grid is visible, capture the + # list surface, then switch to Grid — both in one Quick Settings visit. + qs = open_quick_settings(nodes) + and_enter("quick_settings") + tap_text(qs, "Videos") + settle("tap") + tap_node(find_node(ui(), text="Done")) + settle("tap") + list_nodes = ui() + before = and_showing(list_nodes) + qs2 = open_quick_settings(list_nodes) + grid = find_node(qs2, text="Grid") + ok_grid = tap_node(grid) if grid else False + settle("tap") + tap_node(find_node(ui(), text="Done")) + settle("tap") + after_nodes = ui() + after = and_showing(after_nodes) + changed = surface_changed(before, after, min_delta=2) + titles = sum(bool(find_node(after_nodes, text=t)) for t in VIDEO_TITLES) + ok = ok_grid and (changed or titles >= 2) + msg = "" + if not ok_grid: + msg = "setup_failed: 'Grid' segment not found in Quick Settings" + elif not (changed or titles >= 2): + msg = "behavior_wrong: picker did not re-render after selecting Grid" + record("structure_layout_grid", ok, msg, depth=1, jump_kind="transition", + expect="picker re-renders (List->Grid) with the 3 videos preserved") + + vlm_assert("structure_layout_grid", + "Are the video thumbnails arranged in a multi-column grid with at " + "least two thumbnails positioned SIDE BY SIDE in the same row, " + "rather than stacked one-per-row?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="position") + reset_view_mode(after_nodes) # restore Folders+List + + +# ══════════════════════════════════════════════════════════════════════════════ +# (6) Enter Player — SHAPE: picker tree replaced by player tree. transition, +# depth=2 (Home -> folder -> player), backed by and_enter_player(). +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_enter_player", "structure_enter_player_vlm")) +def test_enter_player(): + folder_nodes = and_enter_folder() + picker_had_marker = bool(find_node(folder_nodes, content_desc="Navigate up") + or find_node(folder_nodes, text="3 Videos") + or any(find_node(folder_nodes, text=t) for t in VIDEO_TITLES)) + player_nodes = and_enter_player("beta_movie") + has_player = bool(player_nodes and find_node(player_nodes, content_desc=PLAYER_MARKER)) + # picker markers must be GONE from the player tree (the tree was REPLACED) + picker_gone = not (find_node(player_nodes, text=FOLDER_NAME) + or find_node(player_nodes, text="3 Videos")) + ok = picker_had_marker and has_player and picker_gone + msg = "" + if not has_player: + msg = "feature_missing: player controls (Play/Pause) not present after tap" + elif not picker_gone: + msg = "behavior_wrong: picker markers still present in the player tree" + record("structure_enter_player", ok, msg, depth=2, jump_kind="transition", + expect="picker tree (Download/3 Videos) replaced by player (Play/Pause control)") + + vlm_assert("structure_enter_player", + "In this landscape video player, is there a play/pause control in " + "the CENTRE of the screen and a horizontal seek bar near the " + "BOTTOM edge?", + RESULTS_DIR, depth=2, jump_kind="transition", tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (7) Quick Settings sheet — SHAPE: a new window layer with a distinctive +# multi-section child set appears over Home. transition, depth=1. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_quicksettings_sheet", + "structure_quicksettings_sheet_vlm")) +def test_quicksettings_sheet(): + nodes = home_ready() + before = marker_count(nodes, QS_MARKERS) # expect 0 on Home + qs = open_quick_settings(nodes) + and_enter("quick_settings") + after = marker_count(qs, QS_MARKERS) # expect 5 in the sheet + has_actions = bool(find_node(qs, text="Done") and find_node(qs, text="Cancel")) + ok = before == 0 and after == len(QS_MARKERS) and has_actions + msg = "" + if after != len(QS_MARKERS): + msg = (f"behavior_wrong: Quick Settings section markers {before}->{after}, " + f"expected 0->{len(QS_MARKERS)}") + elif not has_actions: + msg = "behavior_wrong: sheet lacks the Done/Cancel action row" + record("structure_quicksettings_sheet", ok, msg, + depth=1, jump_kind="transition", + expect="0->5 sheet section headers + Done/Cancel row appear over Home") + + vlm_assert("structure_quicksettings_sheet", + "In this 'Quick Settings' bottom sheet, are the 'Cancel' and " + "'Done' text buttons positioned at the BOTTOM of the sheet, with " + "'Done' to the right of 'Cancel'?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (8) Settings list — SHAPE: a scrollable list of exactly 9 category rows. +# transition, depth=1, backed by and_enter_settings(). +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_settings_list", "structure_settings_list_vlm")) +def test_settings_list(): + settings_nodes = and_enter_settings() + reached = bool(settings_nodes) + rows = count_rows(settings_nodes) # expect 9 + ok = reached and rows == SETTINGS_ROWS + msg = "" + if not reached: + msg = "setup_failed: Settings screen not reached" + elif rows != SETTINGS_ROWS: + msg = (f"behavior_wrong: Settings category rows = {rows}, " + f"expected {SETTINGS_ROWS}") + record("structure_settings_list", ok, msg, depth=1, jump_kind="transition", + expect=f"Settings root is a {SETTINGS_ROWS}-row category list") + + vlm_assert("structure_settings_list", + "Is this a vertical, single-column list of setting category rows " + "(each row a leading icon plus a title and a smaller subtitle " + "beneath it), with roughly nine such rows?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="layout") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (9) Folder drill-down — SHAPE: 1 folder row -> 3 video rows, and a 'Navigate +# up' control appears. transition, depth=1, backed by and_enter_folder(). +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_folder_drilldown",)) +def test_folder_drilldown(): + home_nodes = home_ready() + rows_home = count_rows(home_nodes) # expect 1 (Download) + up_before = bool(find_node(home_nodes, content_desc="Navigate up")) # False + folder_nodes = and_enter_folder() + reached = bool(folder_nodes) + rows_folder = count_rows(folder_nodes) # expect 3 videos + up_after = bool(find_node(folder_nodes, content_desc="Navigate up")) # True + ok = (reached and rows_home == 1 and rows_folder == 3 + and not up_before and up_after) + msg = "" + if not reached: + msg = "setup_failed: folder contents not reached" + elif rows_folder != 3: + msg = (f"behavior_wrong: rows {rows_home}(home)->{rows_folder}(folder), " + f"expected 1->3") + elif not up_after: + msg = "behavior_wrong: 'Navigate up' control not added inside the folder" + record("structure_folder_drilldown", ok, msg, + depth=1, jump_kind="transition", + expect="rows 1->3 and a 'Navigate up' back control appears") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (10) Search screen SHAPE — 'Popular folders' section (empty query) is replaced +# by a filtered result section when a query is typed. transition, depth=1. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_search_shape", "structure_search_shape_vlm")) +def test_search_shape(): + nodes = home_ready() + tap_topbar(nodes, "Search") + settle("tap") + search_nodes = ui() + and_enter("search") + popular = bool(find_node(search_nodes, text="Popular folders")) + edit = find_by_class(search_nodes, "EditText") + typed = type_text(edit[0], "beta") if edit else False + settle("text") + results = ui() + popular_gone = not find_node(results, text="Popular folders") + result_header = bool(find_node(results, text="Videos (1)")) + beta_row = bool(find_node(results, text="beta_movie")) + ok = popular and typed and popular_gone and (result_header or beta_row) + msg = "" + if not popular: + msg = "setup_failed: 'Popular folders' section not shown on empty search" + elif not typed: + msg = "setup_failed: could not type into the search field" + elif not (result_header or beta_row): + msg = "behavior_wrong: query 'beta' did not produce a filtered result section" + elif not popular_gone: + msg = "behavior_wrong: 'Popular folders' still present after a query" + record("structure_search_shape", ok, msg, depth=1, jump_kind="transition", + expect="'Popular folders' section -> 'Videos (1)' result row on typing 'beta'") + + vlm_assert("structure_search_shape", + "Below a search box containing the text 'beta', is there a section " + "header reading 'Videos (1)' with exactly one video result row " + "beneath it?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="content") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (11) Network Stream dialog — SHAPE delta: FAB -> "Open network stream" adds a +# NEW dialog window layer over Home (title + URL label + an EditText + a +# Done/Cancel row). Home has 0 EditText; the dialog adds exactly 1 plus 4 +# marker strings. Cancel removes the layer and restores Home. transition, +# depth=2 (Home -> FAB menu -> dialog), backed by two and_enter() calls. +# Chosen for depth-2 over an in-player delta because it has no video clip to +# race. +# ══════════════════════════════════════════════════════════════════════════════ + +NET_DIALOG_MARKERS = ("Network Stream", "Enter a network URL:", "Done", "Cancel") + + +@and_test(expects=("structure_network_stream_dialog",)) +def test_network_stream_dialog(): + nodes = home_ready() + edits_home = len(find_by_class(nodes, "EditText")) # expect 0 on Home + fab = find_fab(nodes) + if not tap_node(fab): + record("structure_network_stream_dialog", False, + "setup_failed: FAB not found / not tappable", depth=2, + jump_kind="transition", + expect="Network Stream dialog adds an EditText + 4 markers over Home") + return + settle("tap") + menu = ui() + and_enter("fab_menu") # surface 1: FAB menu + if not tap_text(menu, "Open network stream"): + record("structure_network_stream_dialog", False, + "feature_missing: 'Open network stream' action not present", depth=2, + jump_kind="transition", + expect="Network Stream dialog adds an EditText + 4 markers over Home") + return + settle("tap") + dlg = ui() + and_enter("network_dialog") # surface 2: the dialog + markers = marker_count(dlg, NET_DIALOG_MARKERS) # expect 4 + edits_dlg = len(find_by_class(dlg, "EditText")) # expect 1 + # reverse: Cancel removes the dialog layer and restores Home + tap_text(dlg, "Cancel") + settle("tap") + restored = ui() + dialog_gone = not find_node(restored, text="Network Stream") + home_back = bool(find_node(restored, text=FOLDER_NAME)) + ok = (edits_home == 0 and markers == len(NET_DIALOG_MARKERS) + and edits_dlg == 1 and dialog_gone and home_back) + msg = "" + if markers != len(NET_DIALOG_MARKERS): + msg = (f"behavior_wrong: dialog markers {markers}/" + f"{len(NET_DIALOG_MARKERS)} present") + elif edits_dlg != 1 or edits_home != 0: + msg = (f"behavior_wrong: EditText count home={edits_home} dialog={edits_dlg}, " + f"expected 0->1") + elif not dialog_gone: + msg = "behavior_wrong: dialog layer not removed after Cancel" + elif not home_back: + msg = "behavior_wrong: Home not restored after Cancel" + record("structure_network_stream_dialog", ok, msg, depth=2, + jump_kind="transition", + expect="dialog adds 1 EditText + 4 markers over Home; Cancel restores Home") + + +TESTS = [ + test_gate_launch, + test_fab_expand, + test_fab_collapse, + test_viewmode_folders_to_videos, + test_layout_grid, + test_enter_player, + test_quicksettings_sheet, + test_settings_list, + test_folder_drilldown, + test_search_shape, + test_network_stream_dialog, +] + +if __name__ == "__main__": + run_suite(TESTS, "structure") diff --git a/android/anilbeesetti-nextplayer/tests/test_android_text.py b/android/anilbeesetti-nextplayer/tests/test_android_text.py new file mode 100644 index 0000000000000000000000000000000000000000..9f85f14e903622bad41c388b377e82af71c4615b --- /dev/null +++ b/android/anilbeesetti-nextplayer/tests/test_android_text.py @@ -0,0 +1,908 @@ +#!/usr/bin/env python3 +"""TEXT lane for NextPlayer (dev.anilbeesetti.nextplayer.debug). + +This lane owns CONTENT / OUTPUT strings that a user action PRODUCES, and it is +the sole owner of exact-string equality. Every test performs an interaction and +then reads the resulting string out of a FRESH ui() and asserts it matches what +the original renders. The discriminating half is the CHANGE: the string is +ABSENT before the trigger and PRESENT after — a hardcoded label present at launch +would pass on a dead shell, so the dynamic ones are asserted absent-then-present. + +Ground truth (observed live on the running original before authoring): + * Home folder row: name "Download", count chip "3 Videos", parent path + "/storage/emulated/0" (folder-level). Title bar "Next Player Debug". + * Inside the Download folder every video row shows the FULL path + "/storage/emulated/0/Download"; titles have NO extension (alpha_clip, + beta_movie, gamma_reel); folder title bar reads "Download". + * Search (top-bar "Search"): typing "beta" -> header EXACTLY "Videos (1)" and a + result row "beta_movie"; "gamma" -> "Videos (1)" + "gamma_reel"; "movie" -> + "Videos (1)" + "beta_movie"; "zzznope" -> the empty-state "No results found" + (NO "Videos (N)" header at all). + * PlayerActivity title bar shows the filename WITH extension: "beta_movie.mp4" + / "gamma_reel.mp4" / "alpha_clip.mp4". The Loop button content-desc is one of + "Loop: Off"/"Loop: One"/"Loop: All" and advances Off->One->All->Off on tap + (the setting PERSISTS across restarts, so we read the CURRENT desc and assert + the NEXT one, never a fixed start value). + * Settings > Player: row "Controller timeout" subtitle "4 seconds"; row + "Default playback speed" subtitle "1.0". Settings > Appearance: row + "Dark theme" subtitle "System Default". Settings > About: "by anilbeesetti", + "Libraries", "Github", "UPI" + "anilbeesetti10@oksbi". (The version number + "0.16.3 (56)" is a BUILD CONSTANT and is deliberately NOT asserted.) + * FAB -> "Open network stream" opens the "Network Stream" dialog with label + "Enter a network URL:" and a placeholder text "http://example.com/example.mp4" + (rendered as its own TextView; the EditText's own text is empty). Typing into + the field reads back from a fresh dump; we dismiss with "Cancel" (NOT BACK, + which would close the whole dialog). + +CEDES (per lane contract): a computed/derived number -> computation (the folder +"00:16" total, the search COUNT as a number); a checked bit -> states; whether a +label's screen is reachable -> navigation (a label tapped to navigate is nav's +trigger, not our assertion); a widget class present -> structure; the content of +a record the user created -> interaction. Here we assert only the exact WORDS an +interaction produced. + +Fixtures: the 3 sample videos are authored into fixtures/ and mirrored to the +device by push_fixtures() (run_suite() calls it once); reached through +fixture_on_device(name), never a hand-pushed path. +""" +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 +import android_testgen_kit as kit # noqa: E402 (for the geometry cache) + +require_kit(1) + +# ── Ground-truth strings (observed on the running original) ───────────────────── +FOLDER_NAME = "Download" +FOLDER_COUNT = "3 Videos" # Home-only count chip +FOLDER_PATH = "/storage/emulated/0/Download" # shown on each video row INSIDE +NAV_UP = "Navigate up" +PLAYER_MARKER = "Play/Pause" # content-desc unique to the player +POPULAR = "Popular folders" # Search screen section +SEARCH_EMPTY = "No results found" # zero-match empty state +LOOP_DESCS = ("Loop: Off", "Loop: One", "Loop: All") +SETTINGS_SIBLING = "Media library" # a Settings-root row, gone on subs + +# The fixture videos the picker opens; declared via fixture_on_device so the +# dependency is explicit and the kit pushes the bytes on a fresh emulator. +FIXTURE_VIDEOS = ("alpha_clip.mp4", "beta_movie.mp4", "gamma_reel.mp4") + + +def next_loop(cur): + """The desc that a Loop tap should produce next (Off->One->All->Off).""" + if cur in LOOP_DESCS: + return LOOP_DESCS[(LOOP_DESCS.index(cur) + 1) % len(LOOP_DESCS)] + return None + + +def all_text(nodes): + """All non-empty visible text, joined — a cheap 'does this string appear'.""" + return " | ".join(n.get("text", "") for n in nodes if n.get("text", "").strip()) + + +def has_text(nodes, s): + """Exact-match on any node's text attribute (this lane's specialty).""" + return any(n.get("text", "").strip() == s for n in nodes) + + +def sub_of(nodes, label): + """The subtitle string that renders directly BELOW a settings row `label`. + + Settings rows are title-over-subtitle: the subtitle is the text node whose + x overlaps the label's and whose top edge sits just below the label's. Return + the closest such node's text, or "" if none.""" + row = find_node(nodes, text=label) + if not row or "_bounds" not in row: + return "" + lx1, ly1, lx2, ly2 = row["_bounds"] + best, best_dy = "", 10 ** 9 + for n in nodes: + if n is row or not n.get("text", "").strip() or "_bounds" not in n: + continue + x1, y1, x2, y2 = n["_bounds"] + # horizontal overlap with the label + starts below it + if x2 <= lx1 or x1 >= lx2 or y1 < ly2 - 5: + continue + dy = y1 - ly2 + if 0 <= dy < best_dy: + best, best_dy = n.get("text", "").strip(), dy + return best + + +# ══════════════════════════════════════════════════════════════════════════════ +# Setup helpers +# ══════════════════════════════════════════════════════════════════════════════ + +def and_grant_media(): + """Tap the runtime media-permission 'Allow all' if it is showing (no-op + otherwise). restart_app() keeps the grant, so this is just a safety net.""" + for label in ("Allow all", "While using the app", "Allow"): + n = find_node_ci(ui(), label) + if n: + tap_node(n) + settle("tap") + return True + return False + + +def tap_topbar(nodes, desc): + """Tap a top-bar icon by content-desc. The desc node itself is not clickable + — its wrapping View is — so tap the tightest clickable ancestor whose bounds + contain the icon centre, falling back to the desc node.""" + target = find_node(nodes, content_desc=desc) + if not target or "_bounds" not in target: + return False + tcx, tcy = target["_center"] + best, best_area = None, None + for n in nodes: + if n.get("clickable") != "true" or "_bounds" not in n: + continue + x1, y1, x2, y2 = n["_bounds"] + if x1 <= tcx <= x2 and y1 <= tcy <= y2: + area = (x2 - x1) * (y2 - y1) + if best_area is None or area < best_area: + best, best_area = n, area + return tap_node(best) if best else tap_node(target) + + +def _home_content_ready(nodes): + """True once the Home picker rendered its top bar + folder row, so we never + assert against a mid-load or launcher frame.""" + topbar = all(find_node(nodes, content_desc=d) + for d in ("Search", "Menu", "Settings")) + body = bool(find_node(nodes, text=FOLDER_NAME)) or bool(find_node(nodes, text="beta_movie")) + return topbar and body + + +def _open_quick_settings(nodes): + tap_topbar(nodes, "Menu") + settle("tap") + return ui() + + +def _reset_view_mode(nodes): + """Normalize the picker to the default Folders view (persisted prefs survive + restart_app). Opens Quick Settings, selects Folders, taps Done.""" + qs = _open_quick_settings(nodes) + if find_node(qs, text="Folders"): + tap_text(qs, "Folders") + settle("tap") + done = find_node(ui(), text="Done") + if done: + tap_node(done) + settle("tap") + return ui() + + +def home_ready(): + """Restart (keeps media grant), wait for the rendered Home, and guarantee the + default Folders view so the 'Download' folder row exists. Returns Home nodes. + + push_fixtures() is idempotent (run_suite() also calls it); doing it here keeps + each test self-sufficient and makes the fixture dependency explicit.""" + push_fixtures() + _ = [fixture_on_device(v) for v in FIXTURE_VIDEOS] # explicit dependency + nodes = [] + for _attempt in range(2): + restart_app() + if not wait_for_foreground(): + continue + and_grant_media() + for _ in range(6): + nodes = ui() + if _home_content_ready(nodes): + break + settle("dump") + if _home_content_ready(nodes): + break + if not nodes: + return [] + if not find_node(nodes, text=FOLDER_NAME): + nodes = _reset_view_mode(nodes) + return nodes + + +# ── Depth-family reach helpers (named and_enter_*/and_reach_* so the depth audit +# finds a backing call for every declared depth>=1). Each opens a surface and +# increments the surface counter via and_enter(). ────────────────────────────── + +def and_reach_search(): + """Home -> Search screen. Returns fresh search nodes (with the EditText) or [].""" + nodes = home_ready() + if not nodes: + return [] + tap_topbar(nodes, "Search") + settle("tap") + after = ui() + if find_node(after, text=POPULAR) or find_by_class(after, "EditText"): + and_enter("search") + return after + return [] + + +def and_search_for(query): + """Open Search, type `query`, and return the fresh result nodes (or []). + + The Search EditText auto-focuses; we still route through type_text so focus is + verified. We do NOT press ENTER — results filter live as characters arrive.""" + nodes = and_reach_search() + if not nodes: + return [] + field = find_by_class(nodes, "EditText") + if not field: + return [] + type_text(field[0], query) + settle("keyboard") + return ui() + + +def and_enter_folder(name=FOLDER_NAME): + """Home -> the named folder. Returns fresh folder nodes (video rows) or [].""" + nodes = home_ready() + row = find_node(nodes, text=name) + if not row: + return [] + if not tap_node(row): + return [] + settle("tap") + after = ui() + if find_node(after, content_desc=NAV_UP) or has_text(after, FOLDER_PATH): + and_enter("folder") + return after + return [] + + +def and_reach_settings(): + """Home -> Settings root. Returns fresh Settings nodes or [].""" + nodes = home_ready() + if not nodes: + return [] + tap_topbar(nodes, "Settings") + settle("tap") + after = ui() + if find_node(after, text="Appearance") and find_node(after, text="About"): + and_enter("settings") + return after + return [] + + +def and_reach_settings_sub(row, marker): + """Home -> Settings -> the `row` subscreen (confirmed by `marker` text). + Counts a second surface (depth 2 from Home). Returns fresh sub nodes or [].""" + settings = and_reach_settings() + if not settings: + return [] + node = find_node(settings, text=row) or scroll_into_view(row) + if not node: + return [] + if not tap_node(node): + return [] + after = ui() + for _ in range(3): + if find_node(after, text=marker): + break + settle("tap") + after = ui() + if find_node(after, text=marker): + and_enter(row.lower()) + return after + return [] + + +def _dump_center(nodes): + maxx = max((b[2] for b in (n.get("_bounds") for n in nodes) if b), default=0) + maxy = max((b[3] for b in (n.get("_bounds") for n in nodes) if b), default=0) + return (maxx // 2, maxy // 2) if maxx and maxy else (0, 0) + + +def _use_landscape_geom(nodes): + """Point the kit's cached geometry at the dump's own (rotated) bounds so + and_showing() keeps the player controls and tap_node() accepts their x>1080 + centres (the landscape player window reports portrait via `wm size`).""" + maxx = max((b[2] for b in (n.get("_bounds") for n in nodes) if b), default=2400) + maxy = max((b[3] for b in (n.get("_bounds") for n in nodes) if b), default=1080) + kit._screen_info = {"width": maxx, "height": maxy, "density": 440, + "center_x": maxx // 2, "center_y": maxy // 2} + + +def _controls_up(nodes): + return bool(find_node(nodes, content_desc=PLAYER_MARKER) + or any(find_node(nodes, content_desc=d) for d in LOOP_DESCS) + or any(n.get("text", "").endswith(".mp4") for n in nodes)) + + +def _in_player(): + return "PlayerActivity" in get_current_activity() + + +def and_enter_player(title="beta_movie"): + """Home -> Download -> tap the video row -> PlayerActivity, then REVEAL the + auto-hiding controls and install landscape geometry. Returns fresh player + nodes with controls up, or []. + + Backs depth=2 (Home->folder->player). The fixtures are SHORT (3-8 s), so we do + NOT pre-sleep the full launch settle before revealing — we tap the frame + centre in a tight loop and, if the clip ended and popped back to the folder, + re-tap the row. `title` is the picker title WITHOUT extension.""" + folder = and_enter_folder() + if not folder: + return [] + row = find_node(folder, text=title) + if not row: + return [] + if not tap_node(row): + return [] + time.sleep(1.0) + kit._screen_info = None # drop the stale portrait cache + and_enter("player") + nodes = [] + for _ in range(5): + if not _in_player(): + # clip ended / popped back to the folder — restart it from the row + folder = ui() + r = find_node(folder, text=title) + if r: + tap_node(r) + time.sleep(1.0) + kit._screen_info = None + continue + nodes = ui() + if _controls_up(nodes): + _use_landscape_geom(nodes) + return nodes + cx, cy = _dump_center(nodes) + if not cx: + break + tap(cx, cy) + time.sleep(0.4) + nodes = ui() + if _controls_up(nodes): + _use_landscape_geom(nodes) + return nodes + return [] + + +# ══════════════════════════════════════════════════════════════════════════════ +# (A) Search result header + row strings. depth=1, transition. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_search_beta_header", "text_search_beta_header_vlm")) +def test_search_beta_header(): + search = and_reach_search() + if not search: + record("text_search_beta_header", False, + "setup_failed: Search screen not reached from the Home search icon", + depth=1, jump_kind="transition", expect="header reads 'Videos (1)'") + vlm_assert("text_search_beta_header", + "Does a header reading exactly 'Videos (1)' appear near the top " + "of the search results, above a single result row?", + RESULTS_DIR, expect="NO", depth=1, jump_kind="transition", + tag="content") + return + absent = not has_text(search, "Videos (1)") + field = find_by_class(search, "EditText") + if not field: + record("text_search_beta_header", False, + "setup_failed: no search EditText on the Search screen", + depth=1, jump_kind="transition", expect="header reads 'Videos (1)'") + return + type_text(field[0], "beta") + settle("keyboard") + after = ui() + header_ok = has_text(after, "Videos (1)") + row_ok = has_text(after, "beta_movie") + ok = absent and header_ok and row_ok + record("text_search_beta_header", ok, + "" if ok else "behavior_wrong: searching 'beta' did not yield header " + "'Videos (1)' + row 'beta_movie'", + depth=1, jump_kind="transition", + expect="header 'Videos (1)' and result row 'beta_movie' after typing 'beta'") + + vlm_assert("text_search_beta_header", + "Is a header reading exactly 'Videos (1)' shown near the top of the " + "search results, directly above one result row?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", + tag="content") + + +@and_test(expects=("text_search_gamma_row",)) +def test_search_gamma_row(): + after = and_search_for("gamma") + if not after: + record("text_search_gamma_row", False, + "setup_failed: Search screen not reached / no EditText", + depth=1, jump_kind="transition", + expect="header 'Videos (1)' + row 'gamma_reel'") + return + ok = has_text(after, "Videos (1)") and has_text(after, "gamma_reel") + record("text_search_gamma_row", ok, + "" if ok else "behavior_wrong: searching 'gamma' did not yield " + "'Videos (1)' + row 'gamma_reel'", + depth=1, jump_kind="transition", + expect="header 'Videos (1)' and result row 'gamma_reel' after typing 'gamma'") + + +@and_test(expects=("text_search_substring_movie",)) +def test_search_substring_movie(): + after = and_search_for("movie") + if not after: + record("text_search_substring_movie", False, + "setup_failed: Search screen not reached / no EditText", + depth=1, jump_kind="transition", + expect="header 'Videos (1)' + row 'beta_movie'") + return + # 'movie' is a substring of only beta_movie -> exactly one match. + ok = has_text(after, "Videos (1)") and has_text(after, "beta_movie") + record("text_search_substring_movie", ok, + "" if ok else "behavior_wrong: substring 'movie' did not match exactly " + "beta_movie (expected header 'Videos (1)')", + depth=1, jump_kind="transition", + expect="header 'Videos (1)' and row 'beta_movie' after typing 'movie'") + + +@and_test(expects=("text_search_empty_state",)) +def test_search_empty_state(): + search = and_reach_search() + if not search: + record("text_search_empty_state", False, + "setup_failed: Search screen not reached", + depth=1, jump_kind="transition", expect="empty state 'No results found'") + return + absent = not has_text(search, SEARCH_EMPTY) + field = find_by_class(search, "EditText") + if not field: + record("text_search_empty_state", False, + "setup_failed: no search EditText on the Search screen", + depth=1, jump_kind="transition", expect="empty state 'No results found'") + return + type_text(field[0], "zzznope") + settle("keyboard") + after = ui() + # A non-matching query renders the empty-state string AND no 'Videos (' header. + present = has_text(after, SEARCH_EMPTY) + no_header = not any(n.get("text", "").startswith("Videos (") for n in after) + ok = absent and present and no_header + record("text_search_empty_state", ok, + "" if ok else "behavior_wrong: a non-matching query did not render the " + "'No results found' empty state", + depth=1, jump_kind="transition", + expect="'No results found' shown (and no 'Videos (N)' header) for a non-matching query") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (B) Player title-bar filename (WITH extension). depth=2, transition. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_player_title_beta", "text_player_title_beta_vlm")) +def test_player_title_beta(): + player = and_enter_player("beta_movie") + if not player: + record("text_player_title_beta", False, + "setup_failed: could not reveal PlayerActivity controls for beta_movie", + depth=2, jump_kind="transition", expect="title bar reads 'beta_movie.mp4'") + vlm_assert("text_player_title_beta", + "Is the text 'beta_movie.mp4' shown as a title in the top bar of " + "the video player, to the right of a back arrow?", + RESULTS_DIR, expect="NO", depth=2, jump_kind="transition", + tag="content") + return + ok = has_text(player, "beta_movie.mp4") + record("text_player_title_beta", ok, + "" if ok else "behavior_wrong: player top bar did not show 'beta_movie.mp4'", + depth=2, jump_kind="transition", + expect="player top-bar title reads 'beta_movie.mp4' (with the .mp4 extension)") + + vlm_assert("text_player_title_beta", + "Is the text 'beta_movie.mp4' shown as a title in the top bar of the " + "video player, to the right of a back arrow?", + RESULTS_DIR, expect="YES", depth=2, jump_kind="transition", + tag="content") + + +@and_test(expects=("text_player_title_gamma",)) +def test_player_title_gamma(): + player = and_enter_player("gamma_reel") + if not player: + record("text_player_title_gamma", False, + "setup_failed: could not reveal PlayerActivity controls for gamma_reel", + depth=2, jump_kind="transition", expect="title bar reads 'gamma_reel.mp4'") + return + ok = has_text(player, "gamma_reel.mp4") + record("text_player_title_gamma", ok, + "" if ok else "behavior_wrong: player top bar did not show 'gamma_reel.mp4'", + depth=2, jump_kind="transition", + expect="player top-bar title reads 'gamma_reel.mp4' (with the .mp4 extension)") + + +@and_test(expects=("text_player_title_alpha",)) +def test_player_title_alpha(): + player = and_enter_player("alpha_clip") + if not player: + record("text_player_title_alpha", False, + "setup_failed: could not reveal PlayerActivity controls for alpha_clip", + depth=2, jump_kind="transition", expect="title bar reads 'alpha_clip.mp4'") + return + ok = has_text(player, "alpha_clip.mp4") + record("text_player_title_alpha", ok, + "" if ok else "behavior_wrong: player top bar did not show 'alpha_clip.mp4'", + depth=2, jump_kind="transition", + expect="player top-bar title reads 'alpha_clip.mp4' (with the .mp4 extension)") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (C) Player Loop content-desc string advances on tap. depth=2, transition. +# The Loop setting PERSISTS across restarts, so read the CURRENT desc, tap +# once, and assert it became the correct NEXT desc — never a fixed start. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_loop_desc_advances",)) +def test_loop_desc_advances(): + player = and_enter_player("beta_movie") + if not player: + record("text_loop_desc_advances", False, + "setup_failed: could not reveal PlayerActivity controls", + depth=2, jump_kind="transition", expect="Loop desc advances to the next value") + return + loop = None + cur = None + for d in LOOP_DESCS: + n = find_node(player, content_desc=d) + if n: + loop, cur = n, d + break + if not loop: + record("text_loop_desc_advances", False, + "feature_missing: no 'Loop: Off/One/All' button in the player", + depth=2, jump_kind="transition", expect="Loop desc advances to the next value") + return + want = next_loop(cur) + tap_node(loop) + settle("tap") + after = _reveal_after_action(player) + ok = bool(want) and bool(find_node(after, content_desc=want)) + record("text_loop_desc_advances", ok, + "" if ok else f"behavior_wrong: Loop desc did not advance '{cur}' -> '{want}'", + depth=2, jump_kind="transition", + expect=f"Loop button content-desc changed from '{cur}' to '{want}' after one tap") + + +def _reveal_after_action(prev_nodes): + """After a player-control tap the overlay may have started to fade; re-reveal + and re-install geometry, then return a fresh dump.""" + _use_landscape_geom(prev_nodes) + for _ in range(4): + nodes = ui() + if _controls_up(nodes): + _use_landscape_geom(nodes) + return nodes + cx, cy = _dump_center(nodes) + if not cx: + break + tap(cx, cy) + time.sleep(0.35) + return ui() + + +# ══════════════════════════════════════════════════════════════════════════════ +# (D) Folder row strings. Home-level "Download"/"3 Videos" (depth 0) and the +# video-row path produced by entering the folder (depth 1). +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_home_folder_labels", "text_home_folder_labels_vlm")) +def test_home_folder_labels(): + nodes = home_ready() + if not nodes: + record("text_home_folder_labels", False, + "setup_failed: Home picker did not render its folder list", + depth=0, jump_kind="value", + expect="folder row shows 'Download' and count chip '3 Videos'") + vlm_assert("text_home_folder_labels", + "Is a folder entry labeled 'Download' shown together with a small " + "badge/chip reading '3 Videos' on the same row?", + RESULTS_DIR, expect="NO", depth=0, jump_kind="value", tag="content") + return + name_ok = has_text(nodes, FOLDER_NAME) + count_ok = has_text(nodes, FOLDER_COUNT) + ok = name_ok and count_ok + record("text_home_folder_labels", ok, + "" if ok else "behavior_wrong: Home folder row missing 'Download' and/or " + "the '3 Videos' count chip", + depth=0, jump_kind="value", + expect="Home folder row shows 'Download' and count chip '3 Videos'") + + vlm_assert("text_home_folder_labels", + "Is a folder entry labeled 'Download' shown together with a small " + "badge/chip reading '3 Videos' on the same row?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="content") + + +@and_test(expects=("text_folder_video_path",)) +def test_folder_video_path(): + folder = and_enter_folder() + if not folder: + record("text_folder_video_path", False, + "setup_failed: Download folder contents not reached", + depth=1, jump_kind="transition", + expect="video row shows path '/storage/emulated/0/Download'") + return + # The full path string only renders on the video rows INSIDE the folder. + ok = has_text(folder, FOLDER_PATH) + record("text_folder_video_path", ok, + "" if ok else "behavior_wrong: video rows did not show the path " + "'/storage/emulated/0/Download'", + depth=1, jump_kind="transition", + expect="each video row shows the path '/storage/emulated/0/Download'") + + +@and_test(expects=("text_folder_titles_no_extension",)) +def test_folder_titles_no_extension(): + folder = and_enter_folder() + if not folder: + record("text_folder_titles_no_extension", False, + "setup_failed: Download folder contents not reached", + depth=1, jump_kind="transition", + expect="picker rows read 'beta_movie' (no extension)") + return + # In the picker the titles carry NO extension; the .mp4 form is player-only. + plain = has_text(folder, "beta_movie") + no_ext = not has_text(folder, "beta_movie.mp4") + ok = plain and no_ext + record("text_folder_titles_no_extension", ok, + "" if ok else "behavior_wrong: picker row title was not the bare " + "'beta_movie' (without the .mp4 extension)", + depth=1, jump_kind="transition", + expect="picker row reads 'beta_movie' (no extension), unlike the player's 'beta_movie.mp4'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (E) Settings subtitle strings. depth=2, transition. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_settings_controller_timeout",)) +def test_settings_controller_timeout(): + sub = and_reach_settings_sub("Player", "Material You controls") + if not sub: + record("text_settings_controller_timeout", False, + "setup_failed: Player settings subscreen not reached", + depth=2, jump_kind="transition", + expect="'Controller timeout' subtitle reads '4 seconds'") + return + label_ok = has_text(sub, "Controller timeout") + subtitle = sub_of(sub, "Controller timeout") + ok = label_ok and subtitle == "4 seconds" + record("text_settings_controller_timeout", ok, + "" if ok else f"behavior_wrong: 'Controller timeout' subtitle was " + f"{subtitle!r}, expected '4 seconds'", + depth=2, jump_kind="transition", + expect="the 'Controller timeout' row's subtitle reads '4 seconds'") + + +@and_test(expects=("text_settings_default_speed",)) +def test_settings_default_speed(): + sub = and_reach_settings_sub("Player", "Material You controls") + if not sub: + record("text_settings_default_speed", False, + "setup_failed: Player settings subscreen not reached", + depth=2, jump_kind="transition", + expect="'Default playback speed' subtitle reads '1.0'") + return + label_ok = has_text(sub, "Default playback speed") + subtitle = sub_of(sub, "Default playback speed") + ok = label_ok and subtitle == "1.0" + record("text_settings_default_speed", ok, + "" if ok else f"behavior_wrong: 'Default playback speed' subtitle was " + f"{subtitle!r}, expected '1.0'", + depth=2, jump_kind="transition", + expect="the 'Default playback speed' row's subtitle reads '1.0'") + + +@and_test(expects=("text_settings_dark_theme_subtitle",)) +def test_settings_dark_theme_subtitle(): + sub = and_reach_settings_sub("Appearance", "Dark theme") + if not sub: + record("text_settings_dark_theme_subtitle", False, + "setup_failed: Appearance settings subscreen not reached", + depth=2, jump_kind="transition", + expect="'Dark theme' subtitle reads 'System Default'") + return + label_ok = has_text(sub, "Dark theme") + subtitle = sub_of(sub, "Dark theme") + ok = label_ok and subtitle == "System Default" + record("text_settings_dark_theme_subtitle", ok, + "" if ok else f"behavior_wrong: 'Dark theme' subtitle was {subtitle!r}, " + f"expected 'System Default'", + depth=2, jump_kind="transition", + expect="the 'Dark theme' row's subtitle reads 'System Default' (default)") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (F) About subscreen label strings (stable, recreation-required; NOT the version). +# depth=2, transition. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_about_credit_and_rows",)) +def test_about_credit_and_rows(): + sub = and_reach_settings_sub("About", "by anilbeesetti") + if not sub: + record("text_about_credit_and_rows", False, + "setup_failed: About subscreen not reached", + depth=2, jump_kind="transition", + expect="'by anilbeesetti', 'Libraries', 'Github' all present") + return + # Deliberately NOT asserting the version number "0.16.3 (56)" — a build + # constant the recreation cannot know. + credit = has_text(sub, "by anilbeesetti") + libs = has_text(sub, "Libraries") + github = has_text(sub, "Github") + ok = credit and libs and github + missing = [s for s, present in + (("by anilbeesetti", credit), ("Libraries", libs), ("Github", github)) + if not present] + record("text_about_credit_and_rows", ok, + "" if ok else f"behavior_wrong: About screen missing {missing}", + depth=2, jump_kind="transition", + expect="About shows the credit 'by anilbeesetti' and rows 'Libraries' and 'Github'") + + +@and_test(expects=("text_about_upi_handle",)) +def test_about_upi_handle(): + sub = and_reach_settings_sub("About", "by anilbeesetti") + if not sub: + record("text_about_upi_handle", False, + "setup_failed: About subscreen not reached", + depth=2, jump_kind="transition", + expect="UPI row subtitle 'anilbeesetti10@oksbi'") + return + label_ok = has_text(sub, "UPI") + handle_ok = has_text(sub, "anilbeesetti10@oksbi") + ok = label_ok and handle_ok + record("text_about_upi_handle", ok, + "" if ok else "behavior_wrong: About screen missing the 'UPI' row and/or " + "its 'anilbeesetti10@oksbi' handle", + depth=2, jump_kind="transition", + expect="About shows a 'UPI' row with the handle 'anilbeesetti10@oksbi'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (G) Network Stream dialog: label + placeholder, and typed-back text. +# depth=2, transition. Do NOT hide_keyboard in this dialog (BACK closes it); +# read the field from a fresh ui() and dismiss with Cancel. +# ══════════════════════════════════════════════════════════════════════════════ + +def _find_fab(nodes): + """The bottom-right expand FAB: a desc-less, text-less clickable View in the + lower-right quadrant. Derived from a fresh dump — never a hardcoded coord.""" + s = get_screen_info() + best = None + for n in nodes: + if n.get("clickable") != "true": + continue + if n.get("text", "").strip() or n.get("content-desc", "").strip(): + continue + b = n.get("_bounds") + if not b: + continue + cx, cy = n["_center"] + if cx < s["width"] * 0.6 or cy < s["height"] * 0.6: + continue + w, h = b[2] - b[0], b[3] - b[1] + if w < 60 or h < 60 or w > s["width"] * 0.6: + continue + if best is None or (cy + cx) > (best["_center"][1] + best["_center"][0]): + best = n + return best + + +def and_reach_network_dialog(): + """Home -> FAB -> 'Open network stream' -> Network Stream dialog. Counts two + surfaces (depth 2 from Home). Returns fresh dialog nodes or [].""" + nodes = home_ready() + fab = _find_fab(nodes) + if not fab: + return [] + if not tap_node(fab): + return [] + settle("tap") + menu = ui() + and_enter("fab_menu") + pill = find_node(menu, text="Open network stream") + if not pill: + return [] + if not tap_node(pill): + return [] + settle("tap") + dlg = ui() + if find_node(dlg, text="Network Stream"): + and_enter("network_dialog") + return dlg + return [] + + +@and_test(expects=("text_network_dialog_label_placeholder",)) +def test_network_dialog_label_placeholder(): + dlg = and_reach_network_dialog() + if not dlg: + record("text_network_dialog_label_placeholder", False, + "setup_failed: Network Stream dialog not reached via the FAB", + depth=2, jump_kind="transition", + expect="label 'Enter a network URL:' + placeholder 'http://example.com/example.mp4'") + return + label_ok = has_text(dlg, "Enter a network URL:") + placeholder_ok = has_text(dlg, "http://example.com/example.mp4") + ok = label_ok and placeholder_ok + # Dismiss with Cancel (NOT BACK, which closes the whole dialog and could pop + # further); keep the surface clean for later tests. + cancel = find_node(dlg, text="Cancel") + if cancel: + tap_node(cancel) + settle("tap") + record("text_network_dialog_label_placeholder", ok, + "" if ok else "behavior_wrong: dialog missing the label 'Enter a network " + "URL:' and/or placeholder 'http://example.com/example.mp4'", + depth=2, jump_kind="transition", + expect="dialog shows label 'Enter a network URL:' and placeholder " + "'http://example.com/example.mp4'") + + +@and_test(expects=("text_network_url_reads_back",)) +def test_network_url_reads_back(): + dlg = and_reach_network_dialog() + if not dlg: + record("text_network_url_reads_back", False, + "setup_failed: Network Stream dialog not reached via the FAB", + depth=2, jump_kind="transition", expect="field reads back the typed URL") + return + field = find_by_class(dlg, "EditText") + if not field: + record("text_network_url_reads_back", False, + "setup_failed: no EditText in the Network Stream dialog", + depth=2, jump_kind="transition", expect="field reads back the typed URL") + return + typed = "http://test.mp4" + absent = typed not in all_text(dlg) + type_text(field[0], typed) + settle("text") + # Read directly from a fresh dump — do NOT hide the keyboard here (BACK would + # dismiss the dialog). + after = ui() + et = find_by_class(after, "EditText") + field_text = et[0].get("text", "") if et else "" + present = typed in field_text or typed in all_text(after) + ok = absent and present + cancel = find_node(after, text="Cancel") + if cancel: + tap_node(cancel) + settle("tap") + record("text_network_url_reads_back", ok, + "" if ok else f"behavior_wrong: URL field did not read back {typed!r} " + f"(got {field_text!r})", + depth=2, jump_kind="transition", + expect=f"the URL EditText reads back the typed text {typed!r}") + + +TESTS = [ + test_search_beta_header, + test_search_gamma_row, + test_search_substring_movie, + test_search_empty_state, + test_player_title_beta, + test_player_title_gamma, + test_player_title_alpha, + test_loop_desc_advances, + test_home_folder_labels, + test_folder_video_path, + test_folder_titles_no_extension, + test_settings_controller_timeout, + test_settings_default_speed, + test_settings_dark_theme_subtitle, + test_about_credit_and_rows, + test_about_upi_handle, + test_network_dialog_label_placeholder, + test_network_url_reads_back, +] + +if __name__ == "__main__": + run_suite(TESTS, "text") diff --git a/android/anilbeesetti-nextplayer/tests/test_manifest.json b/android/anilbeesetti-nextplayer/tests/test_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..e99268a4f8e4337316183136f004b71684e6bd58 --- /dev/null +++ b/android/anilbeesetti-nextplayer/tests/test_manifest.json @@ -0,0 +1,714 @@ +{ + "manifest_version": 1, + "kit_api_version": 1, + "task_id": "nextplayer", + "baseline_model": "claude-opus-4-8", + "baseline_package": "", + "total": 97, + "manifest_sha": "2693b8802ca7", + "tests": [ + { + "name": "computation::computation_folder_badges_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_folder_duration_total", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_beta_count", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_beta_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_clip_count", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_gamma_count", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_movie_count", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_multi_count", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_nomatch_count", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_underscore_count", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_speed_chip_2x", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_speed_chip_2x_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_speed_chip_half", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_speed_stepper_plus", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_quicksettings_multichange_reorder", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_quicksettings_multichange_reorder_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_search_filter_sequence", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_search_filter_sequence_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_search_query_clip", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_sort_toggle_integrity", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_sort_toggle_integrity_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_appearance_back_to_settings", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_audio_dialog_rendered_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_deep_chain_settings_player", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_fab_to_network_dialog", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_folder_back_to_home", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_folder_to_player", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_home_to_folder", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_home_to_search", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_home_to_settings", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_network_dialog_cancel_home", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_player_back_to_folder", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_player_overlay_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_player_to_audio_dialog", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_player_to_speed_dialog", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_player_to_subtitle_dialog", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_search_back_to_home", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_search_rendered_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_settings_rendered_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_settings_to_about", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_settings_to_appearance", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_settings_to_audio", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_settings_to_gestures", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_settings_to_media_library", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_settings_to_player_settings", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_settings_to_subtitle", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_speed_dialog_back_to_player", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_speed_dialog_rendered_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_subtitle_dialog_rendered_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_theme_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_theme_persists_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dynamic_color_switch_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_high_contrast_switch_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_loop_advances", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_loop_advances_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_loop_full_cycle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_qs_folders_selected_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_qs_grid_selected_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_qs_videos_flattens", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_qs_videos_flattens_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_qs_videos_selected_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "structure::structure_enter_player", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_enter_player_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_fab_collapse", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_fab_expand", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_fab_expand_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_folder_drilldown", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_home_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_launch", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_layout_grid", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_layout_grid_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_network_stream_dialog", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_quicksettings_sheet", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_quicksettings_sheet_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_search_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_search_shape_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_list", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_list_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_viewmode_folders_to_videos", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_viewmode_folders_to_videos_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "text::text_folder_titles_no_extension", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_folder_video_path", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_home_folder_labels", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_home_folder_labels_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_loop_desc_advances", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_player_title_alpha", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_player_title_beta", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_player_title_beta_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_player_title_gamma", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_search_beta_header", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_search_beta_header_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_search_empty_state", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_search_gamma_row", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_search_substring_movie", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_controller_timeout", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_dark_theme_subtitle", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_default_speed", + "module": "text", + "baseline_status": "passed" + } + ], + "ignored": [ + { + "name": "interaction::interaction_network_url_edit_clear", + "module": "interaction", + "reason": "baseline_fail", + "baseline_status": "failed", + "message": "setup_failed: could not seed the field with 'http://test.mp4'" + }, + { + "name": "interaction::interaction_network_url_roundtrip", + "module": "interaction", + "reason": "baseline_fail", + "baseline_status": "failed", + "message": "behavior_wrong: URL field read None, expected 'http://test.mp4'" + }, + { + "name": "states::states_dark_theme_on_subtitle", + "module": "states", + "reason": "baseline_fail", + "baseline_status": "failed", + "message": "setup_failed: Appearance screen not reached" + }, + { + "name": "states::states_dark_theme_on_vlm", + "module": "states", + "reason": "baseline_fail", + "baseline_status": "failed", + "message": "setup_failed: Appearance not reached" + }, + { + "name": "text::text_about_credit_and_rows", + "module": "text", + "reason": "baseline_fail", + "baseline_status": "failed", + "message": "setup_failed: About subscreen not reached" + }, + { + "name": "text::text_about_upi_handle", + "module": "text", + "reason": "baseline_fail", + "baseline_status": "failed", + "message": "setup_failed: About subscreen not reached" + }, + { + "name": "text::text_network_dialog_label_placeholder", + "module": "text", + "reason": "baseline_fail", + "baseline_status": "failed", + "message": "setup_failed: Network Stream dialog not reached via the FAB" + }, + { + "name": "text::text_network_url_reads_back", + "module": "text", + "reason": "baseline_fail", + "baseline_status": "failed", + "message": "setup_failed: Network Stream dialog not reached via the FAB" + } + ], + "vlm_assertions": [ + { + "name": "computation::computation_search_beta_vlm", + "module": "computation", + "tag": "content" + }, + { + "name": "computation::computation_folder_badges_vlm", + "module": "computation", + "tag": "content" + }, + { + "name": "computation::computation_speed_chip_2x_vlm", + "module": "computation", + "tag": "content" + }, + { + "name": "interaction::interaction_search_filter_sequence_vlm", + "module": "interaction", + "tag": "position" + }, + { + "name": "interaction::interaction_quicksettings_multichange_reorder_vlm", + "module": "interaction", + "tag": "position" + }, + { + "name": "interaction::interaction_sort_toggle_integrity_vlm", + "module": "interaction", + "tag": "position" + }, + { + "name": "navigation::navigation_settings_rendered_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::navigation_player_overlay_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::navigation_search_rendered_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::navigation_speed_dialog_rendered_vlm", + "module": "navigation", + "tag": "shape" + }, + { + "name": "navigation::navigation_audio_dialog_rendered_vlm", + "module": "navigation", + "tag": "layout" + }, + { + "name": "navigation::navigation_subtitle_dialog_rendered_vlm", + "module": "navigation", + "tag": "shape" + }, + { + "name": "states::states_loop_advances_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_qs_grid_selected_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_qs_videos_selected_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_qs_folders_selected_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_qs_videos_flattens_vlm", + "module": "states", + "tag": "layout" + }, + { + "name": "states::states_high_contrast_switch_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_dynamic_color_switch_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_dark_theme_persists_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "structure::structure_gate_home_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_fab_expand_vlm", + "module": "structure", + "tag": "shape" + }, + { + "name": "structure::structure_viewmode_folders_to_videos_vlm", + "module": "structure", + "tag": "color" + }, + { + "name": "structure::structure_layout_grid_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_enter_player_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_quicksettings_sheet_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_settings_list_vlm", + "module": "structure", + "tag": "layout" + }, + { + "name": "structure::structure_search_shape_vlm", + "module": "structure", + "tag": "content" + }, + { + "name": "text::text_search_beta_header_vlm", + "module": "text", + "tag": "content" + }, + { + "name": "text::text_player_title_beta_vlm", + "module": "text", + "tag": "content" + }, + { + "name": "text::text_home_folder_labels_vlm", + "module": "text", + "tag": "content" + } + ], + "vlm_total": 31, + "n_vlm_unverified": 0, + "vlm_log_found": true +} \ No newline at end of file diff --git a/android/anilbeesetti-nextplayer/vlm_assertions.json b/android/anilbeesetti-nextplayer/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..d4d09f271796dd36cfcf64dbbbc5f3157330edb4 --- /dev/null +++ b/android/anilbeesetti-nextplayer/vlm_assertions.json @@ -0,0 +1,663 @@ +{ + "schema_version": 2, + "instance_id": "android/anilbeesetti-nextplayer", + "grading": { + "mode": "inline", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 32, + "with_verdict": 32, + "calibrated": 0, + "usable": null, + "scored_records": 32, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "structure_gate_home_vlm", + "screenshot": "structure_gate_home_vlm.png", + "assertion": "In the top app bar of this video app, are there exactly three icon buttons (a magnifier, a grid/menu icon, and a gear) on the right side, arranged in a single horizontal row?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_gate_home", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_fab_expand_vlm", + "screenshot": "structure_fab_expand_vlm.png", + "assertion": "Are there exactly three rounded pill-shaped buttons stacked vertically near the bottom-right (labelled about network stream, local video, and recently played), each with a leading icon?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "structure_fab_expand", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_viewmode_folders_to_videos_vlm", + "screenshot": "structure_viewmode_folders_to_videos_vlm.png", + "assertion": "Is this a single-column vertical list of exactly three video items with red, blue and green thumbnails (top to bottom), rather than one folder entry?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "structure_viewmode_folders_to_videos", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_layout_grid_vlm", + "screenshot": "structure_layout_grid_vlm.png", + "assertion": "Are the video thumbnails arranged in a multi-column grid with at least two thumbnails positioned SIDE BY SIDE in the same row, rather than stacked one-per-row?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_layout_grid", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_enter_player_vlm", + "screenshot": "structure_enter_player_vlm.png", + "assertion": "In this landscape video player, is there a play/pause control in the CENTRE of the screen and a horizontal seek bar near the BOTTOM edge?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_enter_player", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_quicksettings_sheet_vlm", + "screenshot": "structure_quicksettings_sheet_vlm.png", + "assertion": "In this 'Quick Settings' bottom sheet, are the 'Cancel' and 'Done' text buttons positioned at the BOTTOM of the sheet, with 'Done' to the right of 'Cancel'?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_quicksettings_sheet", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_settings_list_vlm", + "screenshot": "structure_settings_list_vlm.png", + "assertion": "Is this a vertical, single-column list of setting category rows (each row a leading icon plus a title and a smaller subtitle beneath it), with roughly nine such rows?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "structure_settings_list", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_search_shape_vlm", + "screenshot": "structure_search_shape_vlm.png", + "assertion": "Below a search box containing the text 'beta', is there a section header reading 'Videos (1)' with exactly one video result row beneath it?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "structure_search_shape", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "navigation_settings_rendered_vlm", + "screenshot": "navigation_settings_rendered_vlm.png", + "assertion": "Is this a settings screen showing a vertical single-column list of category rows, each with a small leading icon on the left, and a back arrow at the top-left?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "navigation_settings_rendered", + "rigor": { + "jump_kind": "reach", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "navigation_player_overlay_vlm", + "screenshot": "navigation_player_overlay_vlm.png", + "assertion": "In this landscape video player, is there a round play/pause button in the CENTRE of the screen and a horizontal seek bar near the BOTTOM edge?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "navigation_player_overlay", + "rigor": { + "jump_kind": "reach", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "navigation_search_rendered_vlm", + "screenshot": "navigation_search_rendered_vlm.png", + "assertion": "Is there a search input field spanning the TOP of the screen (with a back arrow to its left), above the rest of the content?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "navigation_search_rendered", + "rigor": { + "jump_kind": "reach", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "navigation_speed_dialog_rendered_vlm", + "screenshot": "navigation_speed_dialog_rendered_vlm.png", + "assertion": "Is a dialog titled about playback speed showing a grid of small rounded speed-value chips (like 0.5, 1.0, 2.0) arranged in rows?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "navigation_speed_dialog_rendered", + "rigor": { + "jump_kind": "reach", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "navigation_audio_dialog_rendered_vlm", + "screenshot": "navigation_audio_dialog_rendered_vlm.png", + "assertion": "Is a dialog titled about audio track showing a vertical list of selectable track options (one row highlighted/selected)?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "navigation_audio_dialog_rendered", + "rigor": { + "jump_kind": "reach", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "navigation_subtitle_dialog_rendered_vlm", + "screenshot": "navigation_subtitle_dialog_rendered_vlm.png", + "assertion": "Is a dialog titled about subtitle track showing two numeric stepper controls near the bottom (each with - and + buttons around a value)?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "navigation_subtitle_dialog_rendered", + "rigor": { + "jump_kind": "reach", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_search_filter_sequence_vlm", + "screenshot": "interaction_search_filter_sequence_vlm.png", + "assertion": "Below the search box (which contains the text 'beta'), is there EXACTLY ONE video result row visible (a single thumbnail with a title beside it), rather than several rows or a folder list?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "interaction_search_filter_sequence", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_quicksettings_multichange_reorder_vlm", + "screenshot": "interaction_quicksettings_multichange_reorder_vlm.png", + "assertion": "Are the video thumbnails laid out in a multi-column GRID with at least two thumbnails positioned SIDE BY SIDE in the same row (rather than a single one-per-row column)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "interaction_quicksettings_multichange_reorder", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_sort_toggle_integrity_vlm", + "screenshot": "interaction_sort_toggle_integrity_vlm.png", + "assertion": "In this single-column list of three coloured video thumbnails, is the GREEN thumbnail ('Gamma') at the TOP and the RED thumbnail ('Alpha Clip') at the BOTTOM (i.e. green, blue, red top to bottom)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "interaction_sort_toggle_integrity", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_search_beta_vlm", + "screenshot": "computation_search_beta_vlm.png", + "assertion": "In this search results screen, is there exactly ONE video result row, and does its title read 'beta_movie'?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "computation_search_beta", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_folder_badges_vlm", + "screenshot": "computation_folder_badges_vlm.png", + "assertion": "On the 'Download' folder row of this video app's home screen, are BOTH a total-duration badge reading '00:16' AND a count reading '3 Videos' displayed?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "computation_folder_badges", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_speed_chip_2x_vlm", + "screenshot": "computation_speed_chip_2x_vlm.png", + "assertion": "Is the large playback-speed value near the top of this dialog showing '2.0'?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "computation_speed_chip_2x", + "rigor": { + "jump_kind": "value", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_loop_advances_vlm", + "screenshot": "states_loop_advances_vlm.png", + "assertion": "In the row of player control icons along the BOTTOM of the screen, is there a circular loop/repeat arrow icon?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_loop_advances", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_qs_grid_selected_vlm", + "screenshot": "states_qs_grid_selected_vlm.png", + "assertion": "In the 'Media Layout' segmented control (the List / Grid pair), is the 'Grid' segment the highlighted/selected one — filled with a distinct accent background colour while 'List' is not?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_qs_grid_selected", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_qs_videos_selected_vlm", + "screenshot": "states_qs_videos_selected_vlm.png", + "assertion": "In the 'Media view mode' segmented control (Tree / Folders / Videos), is the 'Videos' segment the highlighted/selected one — filled with a distinct accent background colour — rather than 'Folders'?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_qs_videos_selected", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_qs_folders_selected_vlm", + "screenshot": "states_qs_folders_selected_vlm.png", + "assertion": "In the 'Media view mode' segmented control (Tree / Folders / Videos), is the 'Folders' segment the highlighted/selected one — filled with a distinct accent background colour — while Tree and Videos are not?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_qs_folders_selected", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_qs_videos_flattens_vlm", + "screenshot": "states_qs_videos_flattens_vlm.png", + "assertion": "Does the main list show individual video items each with a thumbnail and a duration badge (not a single folder entry)?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "states_qs_videos_flattens", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_dark_theme_on_vlm", + "screenshot": "states_dark_theme_on_vlm.png", + "assertion": "Is the app using a DARK theme right now — a near-black or very dark background with light/white text?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_dark_theme_on", + "rigor": { + "jump_kind": "none", + "depth": 3 + }, + "verdict": { + "answer": false, + "passed": false, + "raw": null + }, + "calibration": null + }, + { + "id": "states_dynamic_color_switch_vlm", + "screenshot": "states_dynamic_color_switch_vlm.png", + "assertion": "For the 'Dynamic color theme' row, is its toggle switch in the ON position — the thumb pushed to the RIGHT side of the track with the track filled in an accent colour?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_dynamic_color_switch", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_high_contrast_switch_vlm", + "screenshot": "states_high_contrast_switch_vlm.png", + "assertion": "For the 'High contrast dark theme' row, is its toggle switch in the ON position — the thumb pushed to the RIGHT side of the track with the track filled in an accent colour?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_high_contrast_switch", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_dark_theme_persists_vlm", + "screenshot": "states_dark_theme_persists_vlm.png", + "assertion": "Is the app still using a DARK theme — a near-black or very dark background with light/white text?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_dark_theme_persists", + "rigor": { + "jump_kind": "transition", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_search_beta_header_vlm", + "screenshot": "text_search_beta_header_vlm.png", + "assertion": "Is a header reading exactly 'Videos (1)' shown near the top of the search results, directly above one result row?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "text_search_beta_header", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_player_title_beta_vlm", + "screenshot": "text_player_title_beta_vlm.png", + "assertion": "Is the text 'beta_movie.mp4' shown as a title in the top bar of the video player, to the right of a back arrow?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "text_player_title_beta", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_home_folder_labels_vlm", + "screenshot": "text_home_folder_labels_vlm.png", + "assertion": "Is a folder entry labeled 'Download' shown together with a small badge/chip reading '3 Videos' on the same row?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "text_home_folder_labels", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + } + ], + "merged_from_files": 1, + "source_shapes": { + "list": 1 + } +} \ No newline at end of file diff --git a/android/anysoftkeyboard-anysoftkeyboard/LICENSE b/android/anysoftkeyboard-anysoftkeyboard/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4c3482beaeaf1f3fa023111030cac05a61252a46 --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2009 Menny Even-Danan + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/android/anysoftkeyboard-anysoftkeyboard/instance.json b/android/anysoftkeyboard-anysoftkeyboard/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..c8366b9991bb6f3af9583ab031dc62765b58ef3a --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "android/anysoftkeyboard-anysoftkeyboard", + "platform": "android", + "repo": "https://github.com/AnySoftKeyboard/AnySoftKeyboard", + "commit": "56bb1f0f28481b377d40dd3c174bc384b959f871", + "patches": [], + "package": "com.menny.android.anysoftkeyboard", + "license": null +} diff --git a/android/anysoftkeyboard-anysoftkeyboard/reference/launch.sh b/android/anysoftkeyboard-anysoftkeyboard/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8 --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/reference/launch.sh @@ -0,0 +1,9 @@ +#!/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 1 diff --git a/android/anysoftkeyboard-anysoftkeyboard/tests/android_computation_eval.json b/android/anysoftkeyboard-anysoftkeyboard/tests/android_computation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..eb0aacaa266dd64b6ea1c0fa020c42f16459636f --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/tests/android_computation_eval.json @@ -0,0 +1,152 @@ +{ + "module": "computation", + "total": 13, + "passed": 13, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 10, + "passed": 10, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 3, + "passed": 3, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.3, + "audit": { + "kit_api_version": 1, + "existence": 3, + "liveness": 0, + "interactive": 10, + "depth_ge1": 10, + "depth_ge2": 0, + "value": 10, + "vlm_fine": 0 + }, + "results": [ + { + "test": "computation_swipe_up_space", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Swipe up summary = Currently, Space" + }, + { + "test": "computation_swipe_up_shift", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Swipe up summary = Currently, Shift" + }, + { + "test": "computation_swipe_down_space", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Swipe down summary = Currently, Space" + }, + { + "test": "computation_swipe_left_hide", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Swipe left summary = Currently, Hide keyboard" + }, + { + "test": "computation_swipe_right_shift", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Swipe right summary = Currently, Shift" + }, + { + "test": "computation_swipe_up_changes_from_default", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Swipe up summary changes to Currently, Move cursor left" + }, + { + "test": "computation_spacebar_left_space", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Space bar swipe left summary = Currently, Space" + }, + { + "test": "computation_swipe_down_split", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Swipe down summary = Currently, Split layout" + }, + { + "test": "computation_swipe_up_value_survives_nav", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Swipe up summary = Currently, Hide keyboard after nav round-trip" + }, + { + "test": "computation_swipe_up_restore_default", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Swipe up summary = Currently, Shift (restored default)" + }, + { + "test": "computation_home_preview_qwerty_row_vlm", + "passed": true, + "message": "VLM: Q='In the on-screen keyboard preview, does the top row of letter keys read q, w, e, r, t, y from left to right?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the on-screen keyboard preview, does the top row of letter keys read q, w, e, r, t, y from left to right?", + "tag": "content" + }, + { + "test": "computation_home_preview_letters_not_numbers_vlm", + "passed": true, + "message": "VLM: Q='Is the on-screen keyboard preview showing a QWERTY letter layout (alphabetic letter keys), not a numeric keypad?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is the on-screen keyboard preview showing a QWERTY letter layout (alphabetic letter keys), not a numeric keypad?", + "tag": "content" + }, + { + "test": "computation_ui_preview_qwerty_vlm", + "passed": true, + "message": "VLM: Q='Does the keyboard preview shown on this screen display a row of letter keys beginning with q, w, e, r, t, y?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does the keyboard preview shown on this screen display a row of letter keys beginning with q, w, e, r, t, y?", + "tag": "content" + } + ] +} \ No newline at end of file diff --git a/android/anysoftkeyboard-anysoftkeyboard/tests/android_interaction_eval.json b/android/anysoftkeyboard-anysoftkeyboard/tests/android_interaction_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..7992cac47d2a3f27f44ea4ba8358f388cf3f83da --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/tests/android_interaction_eval.json @@ -0,0 +1,183 @@ +{ + "module": "interaction", + "total": 16, + "passed": 16, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 9, + "passed": 9, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 7, + "passed": 7, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.7778, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 16, + "depth_ge1": 16, + "depth_ge2": 9, + "value": 3, + "vlm_fine": 5 + }, + "results": [ + { + "test": "interaction_emoji_toggle_off", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "People card checkmark true->false" + }, + { + "test": "interaction_emoji_toggle_off_vlm", + "passed": true, + "message": "VLM: Q='These are emoji category cards, each normally showing a small check-mark badge near its top edge. Is there at least ONE card that is now MISSING that check-mark badge while the others still have it?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: These are emoji category cards, each normally showing a small check-mark badge near its top edge. Is there at least ONE card that is now MISSING that check-mark badge while the others still have it?", + "tag": "shape" + }, + { + "test": "interaction_emoji_toggle_roundtrip", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "People card checkmark True->False->True" + }, + { + "test": "interaction_emoji_multi_record_integrity", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Food off while People and Nature stay checked" + }, + { + "test": "interaction_emoji_multi_record_integrity_vlm", + "passed": true, + "message": "VLM: Q='This is a grid of emoji category cards. Do MOST cards still show a check-mark badge (i.e. only a single card is missing its badge, not all of them)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: This is a grid of emoji category cards. Do MOST cards still show a check-mark badge (i.e. only a single card is missing its badge, not all of them)?", + "tag": "shape" + }, + { + "test": "interaction_emoji_persists_process_death", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "People card stays UNchecked after force-stop + relaunch" + }, + { + "test": "interaction_emoji_persists_process_death_vlm", + "passed": true, + "message": "VLM: Q='After the app was force-stopped and relaunched, this is the emoji category grid. Is at least one card still MISSING its check-mark badge while other cards clearly show one?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: After the app was force-stopped and relaunched, this is the emoji category grid. Is at least one card still MISSING its check-mark badge while other cards clearly show one?", + "tag": "color" + }, + { + "test": "interaction_keyboard_enable", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Dvorak layout checkmark false->true" + }, + { + "test": "interaction_keyboard_enable_vlm", + "passed": true, + "message": "VLM: Q='This is a grid of keyboard-layout cards. Does the card labelled 'Dvorak' now show a check-mark badge indicating it is enabled?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: This is a grid of keyboard-layout cards. Does the card labelled 'Dvorak' now show a check-mark badge indicating it is enabled?", + "tag": "shape" + }, + { + "test": "interaction_keyboard_primary_stays_enabled", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "English enabled=True unchanged while Dvorak enabled=True" + }, + { + "test": "interaction_theme_single_select", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "single-select: Yochees Light checked, Yochees Dark unchecked" + }, + { + "test": "interaction_theme_single_select_vlm", + "passed": true, + "message": "VLM: Q='This is a grid of keyboard-theme cards. Does EXACTLY ONE theme card show a check-mark badge (not zero and not more than one)?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: This is a grid of keyboard-theme cards. Does EXACTLY ONE theme card show a check-mark badge (not zero and not more than one)?", + "tag": "shape" + }, + { + "test": "interaction_theme_persists_process_death", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Yochees Light still selected after force-stop + relaunch" + }, + { + "test": "interaction_theme_persists_process_death_vlm", + "passed": true, + "message": "VLM: Q='There is a keyboard preview near the top of this theme-selection screen. Below it, is there exactly one theme card marked with a check-mark badge?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: There is a keyboard preview near the top of this theme-selection screen. Below it, is there exactly one theme card marked with a check-mark badge?", + "tag": "content" + }, + { + "test": "interaction_theme_survives_nav_away", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Yochees Light still checked after nav away + reopen" + }, + { + "test": "interaction_theme_survives_nav_away_vlm", + "passed": true, + "message": "VLM: Q='This keyboard-theme selection screen was just reopened after navigating away. Is exactly one theme card marked with a check-mark badge?' A=YES expect=YES", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: This keyboard-theme selection screen was just reopened after navigating away. Is exactly one theme card marked with a check-mark badge?", + "tag": "content" + } + ] +} \ No newline at end of file diff --git a/android/anysoftkeyboard-anysoftkeyboard/tests/android_navigation_eval.json b/android/anysoftkeyboard-anysoftkeyboard/tests/android_navigation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..2af2b105204c9dd1f8521cbb67dc07d6c4e725b1 --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/tests/android_navigation_eval.json @@ -0,0 +1,245 @@ +{ + "module": "navigation", + "total": 23, + "passed": 23, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 17, + "passed": 17, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 6, + "passed": 6, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.3529, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 23, + "depth_ge1": 23, + "depth_ge2": 8, + "value": 0, + "vlm_fine": 5 + }, + "results": [ + { + "test": "nav_reach_about_vlm", + "passed": true, + "message": "VLM: Q='Is there a large circular icon positioned in the horizontal centre of the screen, with a bold title text directly beneath it?' A=YES expect=YES", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is there a large circular icon positioned in the horizontal centre of the screen, with a bold title text directly beneath it?", + "tag": "position" + }, + { + "test": "nav_reach_about", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "About surface: 'Additional Software Licenses' appeared and 'Welcome to AnySoftKeyboard' disappeared" + }, + { + "test": "nav_back_about_to_home", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "After one BACK: home title 'Welcome to AnySoftKeyboard' restored and About's 'Additional Software Licenses' gone" + }, + { + "test": "nav_reach_overflow_menu", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Overflow popup surface: 'Restore' (with Backup & Tweaks) appeared and 'Welcome to AnySoftKeyboard' left the dump" + }, + { + "test": "nav_reach_tab_language", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Language tab: 'Enable keyboards and languages.' appeared and 'Welcome to AnySoftKeyboard' disappeared" + }, + { + "test": "nav_reach_tab_ui_vlm", + "passed": true, + "message": "VLM: Q='Is there a light purple / violet coloured bar spanning the full width across the very top of the screen (just below the status bar)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is there a light purple / violet coloured bar spanning the full width across the very top of the screen (just below the status bar)?", + "tag": "color" + }, + { + "test": "nav_reach_tab_ui", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "UI tab: 'Pick and configure keyboard themes.' appeared and 'Welcome to AnySoftKeyboard' disappeared" + }, + { + "test": "nav_reach_tab_gestures_vlm", + "passed": true, + "message": "VLM: Q='Is the screen a vertically-scrollable list of gesture settings rows (such as Swipe up / Swipe down / Swipe left / Swipe right), each with a title and a smaller grey description line below it?' A=YES expect=YES", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is the screen a vertically-scrollable list of gesture settings rows (such as Swipe up / Swipe down / Swipe left / Swipe right), each with a title and a smaller grey description line below it?", + "tag": "layout" + }, + { + "test": "nav_reach_tab_gestures", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Gestures tab: 'Swipe up' appeared and 'Welcome to AnySoftKeyboard' disappeared" + }, + { + "test": "nav_reach_tab_emojis", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Emojis tab: 'Quick Text groups and order' appeared and 'Welcome to AnySoftKeyboard' disappeared" + }, + { + "test": "nav_reach_tab_home_from_language", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Home tab from Language: 'Welcome to AnySoftKeyboard' appeared and 'Enable keyboards and languages.' disappeared" + }, + { + "test": "nav_reach_keyboards_depth2_vlm", + "passed": true, + "message": "VLM: Q='Are the keyboard-layout preview cards arranged in a two-column grid (two cards positioned side by side per row)?' A=YES expect=YES", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Are the keyboard-layout preview cards arranged in a two-column grid (two cards positioned side by side per row)?", + "tag": "position" + }, + { + "test": "nav_reach_keyboards_depth2", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Home->Language->Keyboards: card 'QWERTY Latin keyboard' appeared and 'Enable keyboards and languages.' disappeared" + }, + { + "test": "nav_back_keyboards_to_language", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "After one BACK: 'Enable keyboards and languages.' restored and the card 'QWERTY Latin keyboard' gone" + }, + { + "test": "nav_reach_select_theme_depth2_vlm", + "passed": true, + "message": "VLM: Q='Are there keyboard THEME preview cards arranged in a two-column grid (two cards positioned side by side per row)?' A=YES expect=YES", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Are there keyboard THEME preview cards arranged in a two-column grid (two cards positioned side by side per row)?", + "tag": "position" + }, + { + "test": "nav_reach_select_theme_depth2", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Home->UI->Select theme: 'Select theme' appeared and 'Pick and configure keyboard themes.' disappeared" + }, + { + "test": "nav_reach_swipe_dialog", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Gestures->Swipe up: dialog title 'Select swipe up action' appeared and the 'Swipe down' row disappeared behind it" + }, + { + "test": "nav_back_swipe_dialog_to_gestures", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "After BACK: the 'Swipe down' row is visible again and the dialog title 'Select swipe up action' is gone" + }, + { + "test": "nav_reach_language_tweaks_depth2", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Home->Language->Tweaks: 'Show suggestions' appeared and the Language row 'Enable keyboards and languages.' disappeared" + }, + { + "test": "nav_backstack_theme_unwind", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "BACK #1: UI row 'Pick and configure keyboard themes.' restored & 'Select theme' gone; BACK #2: home title restored & UI row gone" + }, + { + "test": "nav_reach_effects_depth2_vlm", + "passed": true, + "message": "VLM: Q='Is there at least one filled / ticked check-box on the right-hand side of a settings row on this screen?' A=YES expect=YES", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is there at least one filled / ticked check-box on the right-hand side of a settings row on this screen?", + "tag": "shape" + }, + { + "test": "nav_reach_effects_depth2", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Home->UI->effects: 'Power-Saving settings' appeared and 'Keyboard effects and experience.' disappeared" + }, + { + "test": "nav_back_effects_to_ui", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "After one BACK: UI row 'Keyboard effects and experience.' restored and 'Power-Saving settings' gone" + } + ] +} \ No newline at end of file diff --git a/android/anysoftkeyboard-anysoftkeyboard/tests/android_states_eval.json b/android/anysoftkeyboard-anysoftkeyboard/tests/android_states_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..433a3ee698f7e68116a371fced331f35161ea818 --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/tests/android_states_eval.json @@ -0,0 +1,229 @@ +{ + "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": 8, + "liveness": 0, + "interactive": 13, + "depth_ge1": 13, + "depth_ge2": 7, + "value": 0, + "vlm_fine": 7 + }, + "results": [ + { + "test": "states_gesture_typing_on", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "gesture-typing checked false->true; 'BETA Feature!' alert appears" + }, + { + "test": "states_gesture_typing_on_vlm", + "passed": true, + "message": "VLM: Q='In the 'Gesture-Typing' section, does the 'Enable gesture-typing [BETA]' checkbox now appear checked (a filled/ticked box) rather than an empty square?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the 'Gesture-Typing' section, does the 'Enable gesture-typing [BETA]' checkbox now appear checked (a filled/ticked box) rather than an empty square?", + "tag": "shape" + }, + { + "test": "states_gesture_typing_roundtrip", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "gesture-typing false->true->false (round-trip restores off)" + }, + { + "test": "states_show_suggestions_switch_on_vlm", + "passed": true, + "message": "VLM: Q='Is the 'Show suggestions' toggle switch turned ON — its thumb to the RIGHT with a colored (purple) track?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is the 'Show suggestions' toggle switch turned ON — its thumb to the RIGHT with a colored (purple) track?", + "tag": "color" + }, + { + "test": "states_show_suggestions_switch", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Show suggestions switch checked true->false; thumb moves left" + }, + { + "test": "states_show_suggestions_switch_off_vlm", + "passed": true, + "message": "VLM: Q='Is the 'Show suggestions' toggle switch turned OFF — its thumb to the LEFT with a grey/uncolored track?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is the 'Show suggestions' toggle switch turned OFF — its thumb to the LEFT with a grey/uncolored track?", + "tag": "shape" + }, + { + "test": "states_suggestions_restart", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Suggestions restart checked true->false" + }, + { + "test": "states_space_switches_keyboards", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Space switches keyboards checked true->false" + }, + { + "test": "states_space_switches_keyboards_vlm", + "passed": true, + "message": "VLM: Q='Is the checkbox in the 'Space switches keyboards' row now UNCHECKED (an empty square, no tick)?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is the checkbox in the 'Space switches keyboards' row now UNCHECKED (an empty square, no tick)?", + "tag": "shape" + }, + { + "test": "states_double_space_period", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Double space to period checked true->false" + }, + { + "test": "states_remember_layout_per_app", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Remember alphabet layout per App checked true->false" + }, + { + "test": "states_theme_app_checkbox", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "'Change theme colors based on used app' checked false->true" + }, + { + "test": "states_theme_app_checkbox_vlm", + "passed": true, + "message": "VLM: Q='Does the 'Change theme colors based on used app' checkbox now appear checked (a filled/ticked box) rather than an empty square?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does the 'Change theme colors based on used app' checkbox now appear checked (a filled/ticked box) rather than an empty square?", + "tag": "shape" + }, + { + "test": "states_nav_select_home_to_language", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "selected moves Home->Language: Language true & Home false" + }, + { + "test": "states_nav_select_language_vlm", + "passed": true, + "message": "VLM: Q='In the bottom navigation bar, is the Language (globe) tab highlighted/colored and showing its 'Language' text label, while the other tabs are dark/grey icons with no label?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the bottom navigation bar, is the Language (globe) tab highlighted/colored and showing its 'Language' text label, while the other tabs are dark/grey icons with no label?", + "tag": "color" + }, + { + "test": "states_nav_select_home_to_ui", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "selected moves Home->UI: UI true, Home false, exactly 1 selected" + }, + { + "test": "states_nav_select_ui_vlm", + "passed": true, + "message": "VLM: Q='In the bottom navigation bar, is the UI (palette) tab icon highlighted in purple/colored and showing a 'UI' text label, while the other tab icons are dark/grey?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the bottom navigation bar, is the UI (palette) tab icon highlighted in purple/colored and showing a 'UI' text label, while the other tab icons are dark/grey?", + "tag": "color" + }, + { + "test": "states_nav_select_language_to_gestures", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "selected moves Language->Gestures: Gestures true & Language false" + }, + { + "test": "states_nav_select_label_layout_vlm", + "passed": true, + "message": "VLM: Q='In the bottom navigation bar, does exactly ONE tab (the Gestures tab) show a text label beneath its icon while every other tab shows only an icon with no label?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the bottom navigation bar, does exactly ONE tab (the Gestures tab) show a text label beneath its icon while every other tab shows only an icon with no label?", + "tag": "layout" + }, + { + "test": "states_gesture_typing_persists", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "gesture-typing checked stays true after force-stop+relaunch" + }, + { + "test": "states_double_space_persists", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "'Double space to period' checked stays false after force-stop+relaunch" + } + ] +} \ No newline at end of file diff --git a/android/anysoftkeyboard-anysoftkeyboard/tests/android_structure_eval.json b/android/anysoftkeyboard-anysoftkeyboard/tests/android_structure_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..306fedc3db8b1c48878b395905ebe7b644006f63 --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/tests/android_structure_eval.json @@ -0,0 +1,174 @@ +{ + "module": "structure", + "total": 15, + "passed": 15, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 8, + "passed": 8, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 7, + "passed": 7, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.875, + "audit": { + "kit_api_version": 1, + "existence": 3, + "liveness": 0, + "interactive": 12, + "depth_ge1": 8, + "depth_ge2": 2, + "value": 0, + "vlm_fine": 1 + }, + "results": [ + { + "test": "structure_gate_bottom_nav", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_gate_demo_keyboard", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_gate_demo_keyboard_vlm", + "passed": true, + "message": "VLM: Q='Is a keyboard (multiple rows of letter keys q w e r t y ...) shown in the upper part of the screen?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a keyboard (multiple rows of letter keys q w e r t y ...) shown in the upper part of the screen?", + "tag": "shape" + }, + { + "test": "structure_gestures_shape_vlm", + "passed": true, + "message": "VLM: Q='Is the screen a vertically-stacked list of settings rows, each with a title and a smaller grey description line, and NOT a grid of picture cards?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is the screen a vertically-stacked list of settings rows, each with a title and a smaller grey description line, and NOT a grid of picture cards?", + "tag": "layout" + }, + { + "test": "structure_gestures_shape", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Home(no list)->Gestures adds a RecyclerView subtree (surface key-set changes >=5 keys); restored on return to Home" + }, + { + "test": "structure_emojis_shape_vlm", + "passed": true, + "message": "VLM: Q='Does the screen show a grid of multiple picture cards arranged in two columns and several rows?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Does the screen show a grid of multiple picture cards arranged in two columns and several rows?", + "tag": "layout" + }, + { + "test": "structure_emojis_shape", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Emojis adds a GridView subtree; tree grows by >=20 nodes vs Home; restored on return to Home" + }, + { + "test": "structure_swipe_dialog_shape_vlm", + "passed": true, + "message": "VLM: Q='Is a dialog open showing a vertical list of options, each with a round radio-button circle on its left side?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is a dialog open showing a vertical list of options, each with a round radio-button circle on its left side?", + "tag": "layout" + }, + { + "test": "structure_swipe_dialog_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "'Swipe up' adds a dialog layer with >=8 CheckedTextView radio rows (0 -> >=8); removed on BACK, Gestures list restored" + }, + { + "test": "structure_about_shape_vlm", + "passed": true, + "message": "VLM: Q='Is there a purple app-bar / header strip spanning the full width across the very top of the screen?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is there a purple app-bar / header strip spanning the full width across the very top of the screen?", + "tag": "layout" + }, + { + "test": "structure_about_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "About swaps the home fragment (changelog card gone, About version/licenses appear; surface changes >=5 keys) but keeps bottom_navigation; restored on BACK" + }, + { + "test": "structure_overflow_menu_shape_vlm", + "passed": true, + "message": "VLM: Q='Is a small dropdown / pop-up menu of stacked text options open near the top-right area of the screen?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is a small dropdown / pop-up menu of stacked text options open near the top-right area of the screen?", + "tag": "layout" + }, + { + "test": "structure_overflow_menu_shape", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "overflow popup adds a menu subtree with exactly 3 items (Backup/Restore/Tweaks, absent on home -> present); removed on BACK" + }, + { + "test": "structure_theme_grid_shape_vlm", + "passed": true, + "message": "VLM: Q='Below a large keyboard preview, are there several smaller keyboard theme preview cards laid out in a two-column grid?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Below a large keyboard preview, are there several smaller keyboard theme preview cards laid out in a two-column grid?", + "tag": "layout" + }, + { + "test": "structure_theme_grid_shape", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "UI list -> Select-theme adds a grid of keyboard preview cards (tree grows >=10 nodes, surface changes >=5 keys); restored on BACK" + } + ] +} \ No newline at end of file diff --git a/android/anysoftkeyboard-anysoftkeyboard/tests/android_testgen_kit.py b/android/anysoftkeyboard-anysoftkeyboard/tests/android_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6 --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/tests/android_testgen_kit.py @@ -0,0 +1,1910 @@ +#!/usr/bin/env python3 +"""Android TestGen Kit — the single source of every test helper, so a test's +NAVIGATION 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 package +name differs): always use the module-level PACKAGE (argv[1]). Never write a package +name, an .apk path, a /data/data path, or a pixel coordinate as a literal. + python3 android_testgen_kit.py lint_sources # flags all of those + +SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery): + python3 android_testgen_kit.py audit + python3 android_testgen_kit.py lint + python3 android_testgen_kit.py lint_sources + python3 android_testgen_kit.py audit_depth [results_dir] +""" +from __future__ import annotations + +import ast +import base64 +import functools +import glob +import hashlib +import json +import math +import os +import re +import shlex +import subprocess +import sys +import time +import urllib.error +import 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.0 +SETTLE = { + "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 /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 " list[dict]: + """XML -> list of attribute dicts, each with _bounds and _center.""" + nodes = [] + for m in re.finditer(r"]+?)/?>", 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} \n" + " android_testgen_kit.py audit_depth [results_dir]\n" + " android_testgen_kit.py score [manifest_dir]") diff --git a/android/anysoftkeyboard-anysoftkeyboard/tests/android_text_eval.json b/android/anysoftkeyboard-anysoftkeyboard/tests/android_text_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..cc0008a1fe1c652e206174f7a4066635ce70b893 --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/tests/android_text_eval.json @@ -0,0 +1,233 @@ +{ + "module": "text", + "total": 22, + "passed": 22, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 19, + "passed": 19, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 3, + "passed": 3, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.1579, + "audit": { + "kit_api_version": 1, + "existence": 5, + "liveness": 0, + "interactive": 17, + "depth_ge1": 15, + "depth_ge2": 0, + "value": 17, + "vlm_fine": 0 + }, + "results": [ + { + "test": "text_title_home", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "toolbar title 'Welcome to AnySoftKeyboard'" + }, + { + "test": "text_title_language", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "toolbar title 'Language'" + }, + { + "test": "text_title_ui", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "toolbar title 'UI'" + }, + { + "test": "text_title_gestures", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "toolbar title 'Gestures'" + }, + { + "test": "text_title_emojis", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "toolbar title 'Quick Text groups and order'" + }, + { + "test": "text_about_heading", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "'AnySoftKeyboard Dev' heading on About" + }, + { + "test": "text_about_version", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "'Version 1.13.1' on About" + }, + { + "test": "text_about_copyright", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "copyright line with 'Menny Even-Danan'" + }, + { + "test": "text_about_licenses_link", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "'Additional Software Licenses' link" + }, + { + "test": "text_about_privacy_link", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "'Privacy Policy' link on About" + }, + { + "test": "text_about_website_link", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "'Visit our web-site' link on About" + }, + { + "test": "text_changelog_title", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "'Latest changes for v1.13' on Home" + }, + { + "test": "text_changelog_bullet", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "changelog bullet 'Improved gesture-typing'" + }, + { + "test": "text_not_setup_card", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "'not fully set-up for use' + 'Click here'" + }, + { + "test": "text_testing_build_card", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "'This is a testing build' card" + }, + { + "test": "text_gesture_swipe_up_summary", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "swipe-up summary 'Currently, Shift'" + }, + { + "test": "text_gesture_swipe_down_summary", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "swipe-down summary 'Currently, Hide keyboard'" + }, + { + "test": "text_dialog_title", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "dialog title 'Select swipe up action'" + }, + { + "test": "text_dialog_options", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "options 'Hide keyboard' and 'Move cursor left'" + }, + { + "test": "text_preview_qwerty_vlm", + "passed": true, + "message": "VLM: Q='Does the on-screen keyboard preview display letter keys with the letters q w e r t y visible along its top row?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does the on-screen keyboard preview display letter keys with the letters q w e r t y visible along its top row?", + "tag": "content" + }, + { + "test": "text_preview_spacebar_vlm", + "passed": true, + "message": "VLM: Q='In the keyboard preview, does the wide space bar in the bottom row show the word 'English'?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the keyboard preview, does the wide space bar in the bottom row show the word 'English'?", + "tag": "content" + }, + { + "test": "text_preview_lowercase_vlm", + "passed": true, + "message": "VLM: Q='Are the letter keys in the keyboard preview showing lowercase letters (such as a s d f) rather than uppercase letters or digits?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Are the letter keys in the keyboard preview showing lowercase letters (such as a s d f) rather than uppercase letters or digits?", + "tag": "content" + } + ] +} \ No newline at end of file diff --git a/android/anysoftkeyboard-anysoftkeyboard/tests/conftest.py b/android/anysoftkeyboard-anysoftkeyboard/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27 --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/tests/conftest.py @@ -0,0 +1 @@ +pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"] diff --git a/android/anysoftkeyboard-anysoftkeyboard/tests/requirements.txt b/android/anysoftkeyboard-anysoftkeyboard/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/tests/requirements.txt @@ -0,0 +1,2 @@ +pytest +pillow diff --git a/android/anysoftkeyboard-anysoftkeyboard/tests/test_android_computation.py b/android/anysoftkeyboard-anysoftkeyboard/tests/test_android_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..604d2ce6bfe94c8de65796843bf4baf0f9b1a172 --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/tests/test_android_computation.py @@ -0,0 +1,653 @@ +#!/usr/bin/env python3 +"""COMPUTATION test suite for AnySoftKeyboard's settings UI. + +Lane: the one genuine INPUT -> DETERMINABLE-OUTPUT surface in this keyboard +SETTINGS app. There is no calculator/converter; the input->output transform is the +**gesture-action list preferences** on the Gestures tab. Each gesture row shows a +summary of the form: + + "Define the swipe X gesture action. Currently, " + +Tapping the row opens a single-choice radio dialog ("Select swipe X action"); +picking an option CLOSES the dialog and RECOMPUTES the row summary to +"...Currently, ". The chosen VALUE is a determinable output +derived from the tap (the input). This file is the SOLE owner of jump_kind="value". + +Ground truth (read from the running original + recon/05_gestures.xml & +recon/10_swipe_up_dialog.xml, then re-verified live): + Gestures tab (gesturesSettingsFragment, toolbar title "Gestures"), rows + default + summaries: + "Swipe up" -> "...Currently, Shift" + "Swipe down" -> "...Currently, Hide keyboard" + "Swipe left" -> "...Currently, Next symbols keyboard" + "Swipe right" -> "...Currently, Next alphabet keyboard" + "Space bar swipe left" -> "Define the swipe left from space bar ... Currently, + Next symbols keyboard" + "Space bar swipe right" -> "...Currently, Next alphabet keyboard" + Swipe-up dialog title "Select swipe up action"; options are CheckedTextView rows + (id android:id/text1): Shift(checked), Space, Hide keyboard, Back-space, Back-word, + Clear entire text (DANGEROUS — never selected), Move cursor up/down/left/right, + Split layout, Merge layout, Compact layout to right/left, Show utility keyboard. + +Every test performs an INPUT (select a specific SAFE radio option) then asserts the +OUTPUT — the row's recomputed summary now contains "Currently, " +(substring, case-insensitive, tolerant of trailing punctuation/whitespace). A +different input yielding a different output is proven directly (Shift vs Space, and a +before!=after default-vs-changed test). Only SAFE options are ever selected; the +option tap is routed through is_safe/safe_tap; "Clear entire text" and anything +destructive is never touched. + +Robustness note: the radio dialog AUTO-SCROLLS so the currently-checked option sits +near the top, which can push an earlier option (e.g. "Shift", index 0) off the top of +the dump. Because the gesture preference PERSISTS across the per-test relaunch, +whichever value a prior test left becomes the next dialog's scroll anchor. So the +option picker deterministically scrolls to the TOP first, then scans DOWNWARD, so +every option is reachable regardless of the initial scroll, and taps only on a +settled dump so a row is never moving under the tap. + +VLM budget for this file: exactly 3 records. Values here are dump-readable, so VLM is +reserved for the RENDERED keyboard-preview canvas (demo_keyboard_view), which the +view tree cannot expose. Those 3 questions are captured on the Home / UI surfaces +that actually render the preview and each names an exact rendered property. +""" +import os +import re +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +# ── Constants observed on the original ─────────────────────────────────────────── +GESTURES_TAB_DESC = "Gestures" # bottom-nav content-desc (stable across pkgs) +GESTURES_MARKER = "Swipe up" # a row unique to the Gestures surface +SUMMARY_STEM = "Define the swipe" # every gesture summary starts with this +CURRENTLY = "currently" # the value marker inside a summary + +# Rows -> their DEFAULT summary value, exactly as read from the original. Used only +# to know what to look for / to prove a change away from default — never as the +# asserted OUTPUT of a selection (that is always the value we just selected). +DEFAULT_VALUE = { + "Swipe up": "Shift", + "Swipe down": "Hide keyboard", + "Swipe left": "Next symbols keyboard", + "Swipe right": "Next alphabet keyboard", + "Space bar swipe left": "Next symbols keyboard", + "Space bar swipe right": "Next alphabet keyboard", +} + +# The dialog title for a given row (matches the "Select swipe X action" pattern). +DIALOG_TITLE = { + "Swipe up": "Select swipe up action", + "Swipe down": "Select swipe down action", + "Swipe left": "Select swipe left action", + "Swipe right": "Select swipe right action", + "Space bar swipe left": "Select left from space bar action", + "Space bar swipe right": "Select right from space bar action", +} + +# SAFE options only. "Clear entire text" and any delete/reset action is excluded on +# purpose — tests mutate real device state. +SAFE_OPTIONS = {"Shift", "Space", "Hide keyboard", "Move cursor up", + "Move cursor down", "Move cursor left", "Move cursor right", + "Split layout", "Merge layout", "Show utility keyboard"} + + +# ── Normalisation / matching ───────────────────────────────────────────────────── +def _norm(s: str) -> str: + """Lower-case, collapse whitespace, strip trailing punctuation. Makes the + substring assertion robust to a faithful recreation differing on casing, spacing + or a trailing period after the value.""" + s = (s or "").lower().strip() + s = re.sub(r"\s+", " ", s) + return s.strip(" .,:;!") + + +def _summary_has_value(summary: str, value: str) -> bool: + """True iff `summary` expresses "Currently, " tolerantly. + + Requires BOTH the "currently" marker AND the value token to be present, and the + value to appear at/after the marker — so a stray occurrence of the word + elsewhere in the (long) summary cannot satisfy it. Falls back to a + marker-anchored regex when the exact separator differs.""" + n_sum, n_val = _norm(summary), _norm(value) + if not n_sum or not n_val: + return False + idx = n_sum.find(CURRENTLY) + if idx < 0: + return False + tail = n_sum[idx:] + if n_val in tail: + return True + # Tolerate an alternate separator between "currently" and the value. + return re.search(rf"{CURRENTLY}\W+{re.escape(n_val)}\b", n_sum) is not None + + +# ── Element location ───────────────────────────────────────────────────────────── +def _clickable_row_for(nodes, label_node): + """A preference title is a non-clickable TextView; its tap handler lives on an + ancestor row (a clickable LinearLayout). Return the smallest clickable node whose + bounds fully contain the label, falling back to the label itself (its centre + still lies inside the row).""" + if not label_node or "_bounds" not in label_node: + return label_node + lx1, ly1, lx2, ly2 = label_node["_bounds"] + best, best_area = None, None + for n in nodes: + if n.get("clickable") != "true" or "_bounds" not in n: + continue + x1, y1, x2, y2 = n["_bounds"] + if x1 <= lx1 and y1 <= ly1 and x2 >= lx2 and y2 >= ly2: + area = (x2 - x1) * (y2 - y1) + if best_area is None or area < best_area: + best, best_area = n, area + return best or label_node + + +def _row_title_node(nodes, row_text): + """The preference TITLE TextView for `row_text` (exact then ci). The title is a + short TextView (id android:id/title) — distinct from the long summary which only + CONTAINS the row's direction inside a sentence.""" + exact = [n for n in nodes + if n.get("text", "").strip() == row_text + and "TextView" in n.get("class", "")] + if exact: + return exact[0] + return find_node_ci(nodes, row_text) + + +def read_summary_value(nodes, row_text): + """Read the summary string for `row_text` on the Gestures surface. + + Anchors on the row's TITLE node, then picks the summary TextView (starts with + "Define the swipe" and contains "currently") whose top edge is immediately BELOW + the title — i.e. the summary belonging to THIS row, not another row that happens + to mention the same direction. Returns "" if not found.""" + title = _row_title_node(nodes, row_text) + ty = title["_bounds"][1] if (title and "_bounds" in title) else None + cands = [] + for n in nodes: + t = n.get("text", "") + if not t or "TextView" not in n.get("class", ""): + continue + nt = _norm(t) + if not nt.startswith(_norm(SUMMARY_STEM)) or CURRENTLY not in nt: + continue + b = n.get("_bounds") + top = b[1] if b else 0 + cands.append((top, t)) + if not cands: + return "" + if ty is not None: + below = [(top, t) for (top, t) in cands if top >= ty] + if below: + return min(below, key=lambda x: x[0] - ty)[1] + # No title anchor (or nothing below it): fall back to the single candidate. + return cands[0][1] + + +# ── Entry points (own copies; sibling suites stay independent) ─────────────────── +def and_enter_home(): + """Bring the app to its home surface, tolerating the first-run setup wizard. + + On a fresh data state the launch shows the setup wizard first (a node with + resource-id suffix `skip_setup_wizard` / text "Skip"); tap it if present and + re-dump. Home is depth 0 — this crosses no surface and deliberately does NOT call + an and_enter*, so a relaunch never inflates a depth claim. Returns the node list. + """ + restart_app() + wait_for_foreground() + nodes = ui() + skip = node_by_id(nodes, "skip_setup_wizard") or find_node_ci(nodes, "Skip") + if skip and is_safe(skip): + tap_node(skip) + nodes = ui() + return nodes + + +def and_enter_gestures(): + """From home, tap the Gestures bottom-nav tab and confirm the Gestures surface + (row "Swipe up" present). Counts one surface via and_enter. Returns + (ok, gest_nodes).""" + home = and_enter_home() + tab = (find_node(home, content_desc=GESTURES_TAB_DESC, clickable="true") + or find_node(home, content_desc=GESTURES_TAB_DESC) + or node_by_id(home, "gesturesSettingsFragment")) + if not tab: + return False, home + if not tap_node(tab): + return False, home + gest = ui() + if _row_title_node(gest, GESTURES_MARKER) is None: + return False, gest + and_enter("gestures") + return True, gest + + +def and_enter_swipe_dialog(gest_nodes, row_text): + """From the Gestures surface, tap `row_text` and confirm its radio dialog opened + (title from DIALOG_TITLE, or a "Select ... action" title carrying an option list). + Counts one surface via and_enter. Returns (ok, dialog_nodes).""" + label = _row_title_node(gest_nodes, row_text) + if not label: + return False, gest_nodes + row = _clickable_row_for(gest_nodes, label) + if not is_safe(row): + return False, gest_nodes + if not tap_node(row): + return False, gest_nodes + dlg = ui() + if not _dialog_open(dlg, row_text): + return False, dlg + and_enter("swipe_dialog") + return True, dlg + + +def _dialog_open(nodes, row_text): + """True iff the single-choice radio dialog is showing: a "Select ... action" + title OR at least two CheckedTextView option rows.""" + want = DIALOG_TITLE.get(row_text, "") + if want and find_node_ci(nodes, want): + return True + for n in nodes: + t = _norm(n.get("text", "")) + if t.startswith("select ") and t.endswith("action"): + return True + return len(_option_nodes(nodes)) >= 2 + + +def _option_nodes(nodes): + """The radio option rows in an open dialog (CheckedTextView, id android:id/text1).""" + out = [n for n in nodes if "CheckedTextView" in n.get("class", "")] + if out: + return out + return [n for n in nodes + if n.get("resource-id", "").rsplit("/", 1)[-1] == "text1"] + + +def _dialog_listview(nodes): + """The scrollable container of the option list, if any.""" + lv = node_by_id(nodes, "select_dialog_listview") + if lv: + return lv + for cls in ("ListView", "ScrollView", "RecyclerView"): + found = [n for n in find_by_class(nodes, cls) if n.get("scrollable") == "true"] + if found: + return found[0] + return None + + +def _scroll_dialog(nodes, up=False, frac=0.6): + """Swipe the dialog list up or down by `frac` of its height (settled by swipe()).""" + lv = _dialog_listview(nodes) + if lv and "_bounds" in lv: + x1, y1, x2, y2 = lv["_bounds"] + cx = (x1 + x2) // 2 + h = y2 - y1 + if up: + swipe(cx, int(y1 + h * 0.30), cx, int(y1 + h * (0.30 + frac))) + else: + swipe(cx, int(y1 + h * 0.75), cx, int(y1 + h * (0.75 - frac))) + else: + (scroll_up if up else scroll_down)(frac) + + +def _select_option(option_text): + """Select the radio option `option_text` in the OPEN dialog. SAFE-only: refuses + anything not in SAFE_OPTIONS and routes the tap through is_safe/safe_tap. + + Robustness: the dialog auto-scrolls so the CURRENTLY-checked item is near the top, + which can push an earlier option (e.g. "Shift", index 0) off the top of the dump. + So this first scrolls the list to its TOP (settling between swipes so no tap lands + mid-animation), then scans and scrolls DOWNWARD through the whole list. Every + option is therefore reachable regardless of the initial scroll. Returns True only + after a settled tap on the exact option row.""" + if option_text not in SAFE_OPTIONS: + return False + target = _norm(option_text) + + # 1) Settle, then scroll to the very top of the option list. + settle("tap") + prev_first = None + for _ in range(6): + nodes = ui() + opts = _option_nodes(nodes) + first = _norm(opts[0].get("text", "")) if opts else "" + if first and first == prev_first: + break # top reached (list stopped moving) + prev_first = first + _scroll_dialog(nodes, up=True) + + # 2) Scan downward for the target, re-dumping between swipes. + prev_last = None + for _ in range(8): + nodes = ui() + opts = _option_nodes(nodes) + for n in opts: + if _norm(n.get("text", "")) == target: + if not is_safe(n): + return False + # Re-locate on a settled dump so the row isn't moving under the tap. + settle("tap") + fresh = None + for m in _option_nodes(ui()): + if _norm(m.get("text", "")) == target: + fresh = m + break + return safe_tap(fresh or n) + last = _norm(opts[-1].get("text", "")) if opts else "" + if last and last == prev_last: + break # bottom reached; target absent + prev_last = last + _scroll_dialog(nodes, up=False) + return False + + +def set_and_read(row_text, option_text): + """End-to-end input->output: open Gestures, open `row_text`'s dialog, select + `option_text`, wait for the dialog to close, and read back the recomputed row + summary. Returns (summary_after, note). `note` is "" on success or a taxonomy + prefix ("setup_failed:" / "feature_missing:") describing where it stopped.""" + ok_gest, gest = and_enter_gestures() + if not ok_gest: + return "", f"setup_failed: Gestures tab / '{GESTURES_MARKER}' not reachable" + ok_dlg, _dlg = and_enter_swipe_dialog(gest, row_text) + if not ok_dlg: + return "", (f"feature_missing: radio dialog for '{row_text}' did not open " + f"(no such gesture preference)") + if not _select_option(option_text): + return "", (f"feature_missing: option '{option_text}' not selectable in the " + f"'{row_text}' dialog") + # The dialog closes on selection; re-dump the Gestures surface and read back. + settle("tap") + after_nodes = ui() + summary = read_summary_value(after_nodes, row_text) + if not summary: + # A scrollable RecyclerView may have recycled the row — scroll it back. + found = scroll_into_view(row_text, max_swipes=3) + if found: + summary = read_summary_value(ui(), row_text) + if not summary: + return "", f"setup_failed: could not read '{row_text}' summary after selecting" + return summary, "" + + +# ════════════════════════════════════════════════════════════════════════════════ +# 1) Swipe up -> select "Space" (the cleanest input->output value) +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("computation_swipe_up_space",)) +def test_swipe_up_space(): + summary, note = set_and_read("Swipe up", "Space") + ok = (not note) and _summary_has_value(summary, "Space") + msg = ("" if ok else (note or + f"behavior_wrong: Swipe up summary {summary!r} lacks 'Currently, Space'")) + record("computation_swipe_up_space", ok, msg, + depth=1, jump_kind="value", + expect="Swipe up summary = Currently, Space") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 2) Swipe up -> select "Shift" (a DIFFERENT input yields a DIFFERENT output) +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("computation_swipe_up_shift",)) +def test_swipe_up_shift(): + summary, note = set_and_read("Swipe up", "Shift") + ok = (not note) and _summary_has_value(summary, "Shift") + msg = ("" if ok else (note or + f"behavior_wrong: Swipe up summary {summary!r} lacks 'Currently, Shift'")) + record("computation_swipe_up_shift", ok, msg, + depth=1, jump_kind="value", + expect="Swipe up summary = Currently, Shift") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 3) Swipe down -> select "Space" +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("computation_swipe_down_space",)) +def test_swipe_down_space(): + summary, note = set_and_read("Swipe down", "Space") + ok = (not note) and _summary_has_value(summary, "Space") + msg = ("" if ok else (note or + f"behavior_wrong: Swipe down summary {summary!r} lacks 'Currently, Space'")) + record("computation_swipe_down_space", ok, msg, + depth=1, jump_kind="value", + expect="Swipe down summary = Currently, Space") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 4) Swipe left -> select "Hide keyboard" (safe) +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("computation_swipe_left_hide",)) +def test_swipe_left_hide(): + summary, note = set_and_read("Swipe left", "Hide keyboard") + ok = (not note) and _summary_has_value(summary, "Hide keyboard") + msg = ("" if ok else (note or + f"behavior_wrong: Swipe left summary {summary!r} lacks " + f"'Currently, Hide keyboard'")) + record("computation_swipe_left_hide", ok, msg, + depth=1, jump_kind="value", + expect="Swipe left summary = Currently, Hide keyboard") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 5) Swipe right -> select "Shift" +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("computation_swipe_right_shift",)) +def test_swipe_right_shift(): + summary, note = set_and_read("Swipe right", "Shift") + ok = (not note) and _summary_has_value(summary, "Shift") + msg = ("" if ok else (note or + f"behavior_wrong: Swipe right summary {summary!r} lacks 'Currently, Shift'")) + record("computation_swipe_right_shift", ok, msg, + depth=1, jump_kind="value", + expect="Swipe right summary = Currently, Shift") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 6) STRONGEST value test: read Swipe up's default, change to a DIFFERENT safe value, +# assert the summary VALUE CHANGED — before != after AND after == selected. +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("computation_swipe_up_changes_from_default",)) +def test_swipe_up_changes_from_default(): + name = "computation_swipe_up_changes_from_default" + ok_gest, gest = and_enter_gestures() + if not ok_gest: + record(name, False, + f"setup_failed: Gestures tab / '{GESTURES_MARKER}' not reachable", + depth=1, jump_kind="value", + expect="Swipe up summary changes to Currently, Move cursor left") + return + before_summary = read_summary_value(gest, "Swipe up") + # A safe target; the assertion only needs before != after (independent of which + # value a prior test left), plus after == this target. + target = "Move cursor left" + ok_dlg, _dlg = and_enter_swipe_dialog(gest, "Swipe up") + if not ok_dlg: + record(name, False, + "feature_missing: Swipe up radio dialog did not open", + depth=1, jump_kind="value", + expect="Swipe up summary changes to Currently, Move cursor left") + return + if not _select_option(target): + record(name, False, + f"feature_missing: option '{target}' not selectable", + depth=1, jump_kind="value", + expect="Swipe up summary changes to Currently, Move cursor left") + return + settle("tap") + after_summary = read_summary_value(ui(), "Swipe up") + if not after_summary: + found = scroll_into_view("Swipe up", max_swipes=3) + if found: + after_summary = read_summary_value(ui(), "Swipe up") + now_target = _summary_has_value(after_summary, target) + was_not_target = not _summary_has_value(before_summary, target) + changed = bool(before_summary) and bool(after_summary) \ + and _norm(before_summary) != _norm(after_summary) + ok = changed and now_target and was_not_target + if ok: + msg = "" + elif not after_summary: + msg = "setup_failed: could not read Swipe up summary after selecting" + else: + msg = (f"behavior_wrong: expected summary to change to '{target}'; " + f"before={before_summary!r} after={after_summary!r}") + record(name, ok, msg, + depth=1, jump_kind="value", + expect="Swipe up summary changes to Currently, Move cursor left") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 7) Space bar swipe left -> select "Space" +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("computation_spacebar_left_space",)) +def test_spacebar_left_space(): + summary, note = set_and_read("Space bar swipe left", "Space") + ok = (not note) and _summary_has_value(summary, "Space") + msg = ("" if ok else (note or + f"behavior_wrong: Space bar swipe left summary {summary!r} lacks " + f"'Currently, Space'")) + record("computation_spacebar_left_space", ok, msg, + depth=1, jump_kind="value", + expect="Space bar swipe left summary = Currently, Space") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 8) Swipe down -> select "Split layout" (a second, different mode/value) +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("computation_swipe_down_split",)) +def test_swipe_down_split(): + summary, note = set_and_read("Swipe down", "Split layout") + ok = (not note) and _summary_has_value(summary, "Split layout") + msg = ("" if ok else (note or + f"behavior_wrong: Swipe down summary {summary!r} lacks " + f"'Currently, Split layout'")) + record("computation_swipe_down_split", ok, msg, + depth=1, jump_kind="value", + expect="Swipe down summary = Currently, Split layout") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 9) VALUE PERSISTS across in-app navigation: select a value, navigate AWAY (Home +# tab) and BACK to Gestures, assert the computed summary still shows the value. +# Still a value assertion (input->output value that stuck), depth 1. +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("computation_swipe_up_value_survives_nav",)) +def test_swipe_up_value_survives_nav(): + name = "computation_swipe_up_value_survives_nav" + target = "Hide keyboard" + # First set the value. + summary, note = set_and_read("Swipe up", target) + if note or not _summary_has_value(summary, target): + record(name, False, + note or f"behavior_wrong: could not set Swipe up to '{target}' " + f"(got {summary!r})", + depth=1, jump_kind="value", + expect="Swipe up summary = Currently, Hide keyboard after nav round-trip") + return + # Navigate away to Home, then back to Gestures (in-app, no relaunch). + now = ui() + home_tab = (find_node(now, content_desc="Hello", clickable="true") + or node_by_id(now, "mainFragment")) + if home_tab: + tap_node(home_tab) + nn = ui() + gest_tab = (find_node(nn, content_desc=GESTURES_TAB_DESC, clickable="true") + or node_by_id(nn, "gesturesSettingsFragment")) + if not gest_tab: + record(name, False, + "setup_failed: could not navigate Home->Gestures for the round-trip", + depth=1, jump_kind="value", + expect="Swipe up summary = Currently, Hide keyboard after nav round-trip") + return + tap_node(gest_tab) + back_nodes = ui() + summary2 = read_summary_value(back_nodes, "Swipe up") + if not summary2: + found = scroll_into_view("Swipe up", max_swipes=3) + if found: + summary2 = read_summary_value(ui(), "Swipe up") + ok = _summary_has_value(summary2, target) + msg = ("" if ok else + f"behavior_wrong: after Home->Gestures round-trip, Swipe up summary " + f"{summary2!r} lacks 'Currently, {target}'") + record(name, ok, msg, + depth=1, jump_kind="value", + expect="Swipe up summary = Currently, Hide keyboard after nav round-trip") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 10) Restore Swipe up to its default "Shift" so other lanes observe defaults. +# Also a value test in its own right (input Shift -> output Currently, Shift). +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("computation_swipe_up_restore_default",)) +def test_swipe_up_restore_default(): + summary, note = set_and_read("Swipe up", DEFAULT_VALUE["Swipe up"]) + ok = (not note) and _summary_has_value(summary, DEFAULT_VALUE["Swipe up"]) + msg = ("" if ok else (note or + f"behavior_wrong: Swipe up summary {summary!r} not restored to " + f"'Currently, {DEFAULT_VALUE['Swipe up']}'")) + record("computation_swipe_up_restore_default", ok, msg, + depth=1, jump_kind="value", + expect="Swipe up summary = Currently, Shift (restored default)") + + +# ════════════════════════════════════════════════════════════════════════════════ +# VLM (exactly 3) — the RENDERED keyboard-preview canvas (demo_keyboard_view) that +# the view tree cannot expose. Captured on Home / UI, each naming an exact rendered +# property. depth reflects the surface captured on. +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("computation_home_preview_qwerty_row_vlm",)) +def test_home_preview_qwerty_row_vlm(): + and_enter_home() + # Home renders demo_keyboard_view (a canvas; no key children in the tree). + vlm_assert("computation_home_preview_qwerty_row", + "In the on-screen keyboard preview, does the top row of letter keys " + "read q, w, e, r, t, y from left to right?", + RESULTS_DIR, depth=0, jump_kind="none", tag="content") + + +@and_test(expects=("computation_home_preview_letters_not_numbers_vlm",)) +def test_home_preview_letters_not_numbers_vlm(): + and_enter_home() + vlm_assert("computation_home_preview_letters_not_numbers", + "Is the on-screen keyboard preview showing a QWERTY letter layout " + "(alphabetic letter keys), not a numeric keypad?", + RESULTS_DIR, depth=0, jump_kind="none", tag="content") + + +@and_test(expects=("computation_ui_preview_qwerty_vlm",)) +def test_ui_preview_qwerty_vlm(): + # The UI tab also renders a demo_keyboard_view preview (depth 1 from home). + home = and_enter_home() + ui_tab = (find_node(home, content_desc="UI", clickable="true") + or node_by_id(home, "userInterfaceSettingsFragment")) + captured_depth = 0 + if ui_tab and tap_node(ui_tab): + after = ui() + if find_node_ci(after, "Pick and configure keyboard themes.") is not None: + and_enter("ui") + captured_depth = 1 + vlm_assert("computation_ui_preview_qwerty", + "Does the keyboard preview shown on this screen display a row of " + "letter keys beginning with q, w, e, r, t, y?", + RESULTS_DIR, depth=captured_depth, jump_kind="none", tag="content") + + +TESTS = [ + test_swipe_up_space, + test_swipe_up_shift, + test_swipe_down_space, + test_swipe_left_hide, + test_swipe_right_shift, + test_swipe_up_changes_from_default, + test_spacebar_left_space, + test_swipe_down_split, + test_swipe_up_value_survives_nav, + test_swipe_up_restore_default, + test_home_preview_qwerty_row_vlm, + test_home_preview_letters_not_numbers_vlm, + test_ui_preview_qwerty_vlm, +] + +if __name__ == "__main__": + run_suite(TESTS, "computation") diff --git a/android/anysoftkeyboard-anysoftkeyboard/tests/test_android_interaction.py b/android/anysoftkeyboard-anysoftkeyboard/tests/test_android_interaction.py new file mode 100644 index 0000000000000000000000000000000000000000..ad42602bf91458911577416d1145887797b71f00 --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/tests/test_android_interaction.py @@ -0,0 +1,743 @@ +#!/usr/bin/env python3 +"""INTERACTION suite for AnySoftKeyboard's settings UI. + +Lane: EFFECT-BY-CONSEQUENCE on user DATA. The app's user-mutable DATA is the set +of ENABLED add-ons (emoji/quick-text categories, keyboard layouts) and the SELECTED +theme. Each is a CARD in a GridView; the *consequence* of a mutation is a checkmark +(`enabled_image` ImageView) appearing/disappearing inside the card, and the change +PERSISTS in SharedPreferences across process death. + +Toggle semantics established from the live original (recon 06/09/12 + probes): + * The `selected` attribute on the card's `title` TextView is ALWAYS "true" for + every card — it is NOT the enabled indicator. The real signal is whether the + card's clickable RelativeLayout subtree contains an `enabled_image` node + (the checkmark). `card_enabled()` below reads exactly that. + * Emoji cards: multi-select, independent, immediate (no confirm). tap -> checkmark + toggles; persists across force-stop+relaunch. + * Keyboard-layout cards: multi-enable; tapping an unselected card enables it. + * Theme cards: SINGLE-select; selecting one deselects the previously selected one. +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +RD = RESULTS_DIR + + +# ── Card-state helpers ────────────────────────────────────────────────────────── +def _title_node(nodes, label): + """The `.../title` TextView whose text == label (the card's name).""" + for n in nodes: + if (n.get("text", "") == label + and n.get("resource-id", "").endswith("/title")): + return n + return None + + +def card_container(nodes, label): + """The SMALLEST clickable RelativeLayout whose bounds enclose the card's title. + + A GridView recycles children, so ALWAYS re-find the card by its label text in a + fresh dump — never reuse a stale node. + """ + t = _title_node(nodes, label) + if not t or "_bounds" not in t: + return None + tx1, ty1, tx2, ty2 = t["_bounds"] + best = None + best_area = None + for n in nodes: + if (n.get("clickable") == "true" + and "RelativeLayout" in n.get("class", "") + and "_bounds" in n): + x1, y1, x2, y2 = n["_bounds"] + if x1 <= tx1 and y1 <= ty1 and x2 >= tx2 and y2 >= ty2: + area = (x2 - x1) * (y2 - y1) + if best is None or area < best_area: + best, best_area = n, area + return best + + +def card_enabled(nodes, label): + """True if the card `label` shows a checkmark (has an `enabled_image` whose + centre lies inside the card container). None if the card is not present. + """ + card = card_container(nodes, label) + if card is None: + return None + cx1, cy1, cx2, cy2 = card["_bounds"] + for n in nodes: + if n.get("resource-id", "").endswith("/enabled_image") and "_bounds" in n: + x1, y1, x2, y2 = n["_bounds"] + ecx, ecy = (x1 + x2) // 2, (y1 + y2) // 2 + if cx1 <= ecx <= cx2 and cy1 <= ecy <= cy2: + return True + return False + + +def tap_card(nodes, label): + """Safely tap the card named `label`. Returns True if the tap landed.""" + card = card_container(nodes, label) + if card is None: + return False + return safe_tap(card) + + +# ── Navigation helpers (the and_enter_* / and_reach_* NAMES back declared depth) ── +def and_enter_home(): + """Cold-launch to the main home, skipping the first-run setup wizard if shown.""" + restart_app() + wait_for_foreground() + nodes = ui() + skip = node_by_id(nodes, "skip_setup_wizard") or find_node_ci(nodes, "Skip") + if skip is not None: + tap_node(skip) + nodes = ui() + return nodes + + +def _skip_wizard_if_present(nodes): + skip = node_by_id(nodes, "skip_setup_wizard") or find_node_ci(nodes, "Skip") + if skip is not None: + tap_node(skip) + return ui() + return nodes + + +def and_reach_home_after_relaunch(): + """After force_stop_and_relaunch(): land on home, skipping the wizard. + + NOTE: this is a relaunch, not navigation — persistence tests keep depth=0 for + the relaunch itself; depth is only claimed for the tab we navigate into + afterwards via and_enter_emojis / and_enter_theme_selector. + """ + wait_for_foreground() + return _skip_wizard_if_present(ui()) + + +def and_enter_emojis(): + """Home -> Emojis tab (quickTextKeysBrowseFragment). Backs depth=1.""" + nodes = ui() + tab = (node_by_id(nodes, "quickTextKeysBrowseFragment") + or find_node(nodes, content_desc="Setup Emojis")) + if tab is None or not tap_node(tab): + return None + nodes = ui() + # Arrival proof: the emoji toolbar title + at least one category card. + if find_node(nodes, text="Quick Text groups and order") is None: + return None + and_enter("emojis") + return nodes + + +def and_reach_keyboards(): + """Home -> Language tab -> "Enable keyboards and languages." -> Keyboards. + + Two forward surfaces, so this backs depth=2. + """ + nodes = ui() + lang = (node_by_id(nodes, "languageSettingsFragment") + or find_node(nodes, content_desc="Language")) + if lang is None or not tap_node(lang): + return None + and_enter("language") + nodes = ui() + row = find_node_ci(nodes, "Enable keyboards and languages.") + if row is None or not tap_node(row): + return None + nodes = ui() + if find_node(nodes, text="Keyboards") is None: + return None + and_enter("keyboards") + return nodes + + +def and_enter_ui_tab(): + """Home -> UI tab (userInterfaceSettingsFragment). One surface.""" + nodes = ui() + uitab = (node_by_id(nodes, "userInterfaceSettingsFragment") + or find_node(nodes, content_desc="UI")) + if uitab is None or not tap_node(uitab): + return None + nodes = ui() + and_enter("ui") + return nodes + + +def and_reach_theme_selector(): + """Home -> UI tab -> "Pick and configure keyboard themes." -> Select theme. + + Two forward surfaces, so this backs depth=2. + """ + nodes = and_enter_ui_tab() + if nodes is None: + return None + row = find_node_ci(nodes, "Pick and configure keyboard themes.") + if row is None or not tap_node(row): + return None + nodes = ui() + if find_node(nodes, text="Select theme") is None: + return None + and_enter("select_theme") + return nodes + + +def _pick_disabled(nodes, candidates): + """First card in `candidates` that currently reads enabled=False, else None.""" + for lbl in candidates: + if card_enabled(nodes, lbl) is False: + return lbl + return None + + +def _pick_enabled(nodes, candidates): + """First card in `candidates` that currently reads enabled=True, else None.""" + for lbl in candidates: + if card_enabled(nodes, lbl) is True: + return lbl + return None + + +EMOJI_CARDS = ["People", "Food", "Nature", "Accessories", "Transport", + "Signs", "Scape", "Activity", "Office", "Emoticons"] +KBD_OFF_CANDS = ["Dvorak", "EN Keypad", "Dv Compact", "EN Compact"] +THEME_CARDS = ["Yochees Dark", "Yochees Light", "AOSP Dark theme", "AOSP Light theme"] + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1) Emoji card TOGGLE OFF — the core data mutation +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_emoji_toggle_off", + "interaction_emoji_toggle_off_vlm")) +def test_emoji_toggle_off(): + and_enter_home() + nodes = and_enter_emojis() + if nodes is None: + record("interaction_emoji_toggle_off", False, + "setup_failed: could not reach the Emojis tab", + depth=1, jump_kind="transition", expect="emoji card checkmark true->false") + record("interaction_emoji_toggle_off_vlm", False, + "setup_failed: could not reach the Emojis tab", + depth=1, jump_kind="transition", tag="shape") + return + + # Pick a card that is currently ON so we can observe true->false. + label = _pick_enabled(nodes, EMOJI_CARDS) + if label is None: + record("interaction_emoji_toggle_off", False, + "feature_missing: no enabled emoji card to toggle off", + depth=1, jump_kind="transition", expect="emoji card checkmark true->false") + record("interaction_emoji_toggle_off_vlm", False, + "setup_failed: no enabled emoji card", + depth=1, jump_kind="transition", tag="shape") + return + + before = card_enabled(nodes, label) # observed True + tapped = tap_card(nodes, label) + nodes = ui() # re-dump; recycled grid + after = card_enabled(nodes, label) # expect False + + ok = tapped and before is True and after is False + record("interaction_emoji_toggle_off", ok, + "" if ok else f"behavior_wrong: {label} checkmark did not flip " + f"true->false (before={before}, after={after})", + depth=1, jump_kind="transition", + expect=f"{label} card checkmark true->false") + + # VLM: at least one card now lacks the checkmark badge the others have. + vlm_assert("interaction_emoji_toggle_off", + "These are emoji category cards, each normally showing a small " + "check-mark badge near its top edge. Is there at least ONE card " + "that is now MISSING that check-mark badge while the others still " + "have it?", + RD, expect="YES", depth=1, jump_kind="transition", tag="shape") + + # Restore ON (best-effort) so later tests are undisturbed. + if after is False: + tap_card(ui(), label) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2) Emoji card TOGGLE round-trip — proves BOTH directions +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_emoji_toggle_roundtrip",)) +def test_emoji_toggle_roundtrip(): + and_enter_home() + nodes = and_enter_emojis() + if nodes is None: + record("interaction_emoji_toggle_roundtrip", False, + "setup_failed: could not reach the Emojis tab", + depth=1, jump_kind="transition", + expect="emoji card true->false->true") + return + + label = _pick_enabled(nodes, EMOJI_CARDS) + if label is None: + record("interaction_emoji_toggle_roundtrip", False, + "feature_missing: no enabled emoji card to round-trip", + depth=1, jump_kind="transition", + expect="emoji card true->false->true") + return + + s0 = card_enabled(nodes, label) # True + tap_card(nodes, label) + nodes = ui() + s1 = card_enabled(nodes, label) # False + tap_card(nodes, label) + nodes = ui() + s2 = card_enabled(nodes, label) # back to True + + ok = s0 is True and s1 is False and s2 is True + record("interaction_emoji_toggle_roundtrip", ok, + "" if ok else f"behavior_wrong: {label} round-trip broke " + f"({s0}->{s1}->{s2}, expected True->False->True)", + depth=1, jump_kind="transition", + expect=f"{label} card checkmark True->False->True") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3) Emoji MULTI-record integrity — toggling one card leaves the others intact +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_emoji_multi_record_integrity", + "interaction_emoji_multi_record_integrity_vlm")) +def test_emoji_multi_record_integrity(): + and_enter_home() + nodes = and_enter_emojis() + if nodes is None: + record("interaction_emoji_multi_record_integrity", False, + "setup_failed: could not reach the Emojis tab", + depth=1, jump_kind="transition", + expect="one card off; two neighbours stay on") + record("interaction_emoji_multi_record_integrity_vlm", False, + "setup_failed: could not reach the Emojis tab", + depth=1, jump_kind="transition", tag="shape") + return + + # Need three distinct cards all currently ON: mutate the middle, assert the + # outer two are untouched (catches a recreation that keeps only one row). + on_cards = [c for c in EMOJI_CARDS if card_enabled(nodes, c) is True] + if len(on_cards) < 3: + record("interaction_emoji_multi_record_integrity", False, + "feature_missing: fewer than 3 enabled emoji cards to compare", + depth=1, jump_kind="transition", + expect="one card off; two neighbours stay on") + record("interaction_emoji_multi_record_integrity_vlm", False, + "setup_failed: fewer than 3 enabled cards", + depth=1, jump_kind="transition", tag="shape") + return + + a, b, c = on_cards[0], on_cards[1], on_cards[2] + a0, c0 = card_enabled(nodes, a), card_enabled(nodes, c) # both True + tap_card(nodes, b) + nodes = ui() + b1 = card_enabled(nodes, b) # False + a1, c1 = card_enabled(nodes, a), card_enabled(nodes, c) # still True + + ok = (a0 is True and c0 is True and b1 is False + and a1 is True and c1 is True) + record("interaction_emoji_multi_record_integrity", ok, + "" if ok else f"behavior_wrong: toggling {b} disturbed a neighbour " + f"({a}:{a0}->{a1}, {b}:->{b1}, {c}:{c0}->{c1})", + depth=1, jump_kind="transition", + expect=f"{b} off while {a} and {c} stay checked") + + # VLM: the grid still shows multiple checked cards with exactly the one gap. + vlm_assert("interaction_emoji_multi_record_integrity", + "This is a grid of emoji category cards. Do MOST cards still show a " + "check-mark badge (i.e. only a single card is missing its badge, not " + "all of them)?", + RD, expect="YES", depth=1, jump_kind="transition", tag="shape") + + # Restore b ON. + if b1 is False: + tap_card(ui(), b) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4) Emoji PERSISTENCE across process death — the in-memory-only killer test +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_emoji_persists_process_death", + "interaction_emoji_persists_process_death_vlm")) +def test_emoji_persists_process_death(): + and_enter_home() + nodes = and_enter_emojis() + if nodes is None: + record("interaction_emoji_persists_process_death", False, + "setup_failed: could not reach the Emojis tab", + depth=1, jump_kind="transition", + expect="card stays deselected after process kill") + record("interaction_emoji_persists_process_death_vlm", False, + "setup_failed: could not reach the Emojis tab", + depth=1, jump_kind="transition", tag="color") + return + + label = _pick_enabled(nodes, EMOJI_CARDS) + if label is None: + record("interaction_emoji_persists_process_death", False, + "feature_missing: no enabled emoji card to toggle off", + depth=1, jump_kind="transition", + expect="card stays deselected after process kill") + record("interaction_emoji_persists_process_death_vlm", False, + "setup_failed: no enabled emoji card", + depth=1, jump_kind="transition", tag="color") + return + + before = card_enabled(nodes, label) # True + tap_card(nodes, label) + nodes = ui() + off = card_enabled(nodes, label) # False + + # Kill the process and relaunch; then NAVIGATE back to the Emojis tab. + force_stop_and_relaunch() + and_reach_home_after_relaunch() + nodes = and_enter_emojis() # depth claimed here + persisted = card_enabled(nodes, label) if nodes is not None else None + + ok = before is True and off is False and persisted is False + record("interaction_emoji_persists_process_death", ok, + "" if ok else f"behavior_wrong: {label} did not stay deselected across " + f"process death (before={before}, off={off}, " + f"after_relaunch={persisted})", + depth=1, jump_kind="transition", + expect=f"{label} card stays UNchecked after force-stop + relaunch") + + # VLM: after the kill, that card visibly lacks the check-mark badge others show. + if nodes is not None: + vlm_assert("interaction_emoji_persists_process_death", + "After the app was force-stopped and relaunched, this is the " + "emoji category grid. Is at least one card still MISSING its " + "check-mark badge while other cards clearly show one?", + RD, expect="YES", depth=1, jump_kind="transition", tag="color") + else: + record("interaction_emoji_persists_process_death_vlm", False, + "setup_failed: could not reach Emojis after relaunch", + depth=1, jump_kind="transition", tag="color") + + # Restore ON. + if persisted is False and nodes is not None: + tap_card(ui(), label) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5) Keyboard layout ENABLE (depth 2) — enable a currently-disabled layout card +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_keyboard_enable", + "interaction_keyboard_enable_vlm")) +def test_keyboard_enable(): + and_enter_home() + nodes = and_reach_keyboards() + if nodes is None: + record("interaction_keyboard_enable", False, + "setup_failed: could not reach the Keyboards browser", + depth=2, jump_kind="transition", + expect="layout card checkmark false->true") + record("interaction_keyboard_enable_vlm", False, + "setup_failed: could not reach the Keyboards browser", + depth=2, jump_kind="transition", tag="shape") + return + + label = _pick_disabled(nodes, KBD_OFF_CANDS) + if label is None: + record("interaction_keyboard_enable", False, + "feature_missing: no disabled keyboard-layout card to enable", + depth=2, jump_kind="transition", + expect="layout card checkmark false->true") + record("interaction_keyboard_enable_vlm", False, + "setup_failed: no disabled layout card", + depth=2, jump_kind="transition", tag="shape") + return + + before = card_enabled(nodes, label) # False + tapped = tap_card(nodes, label) + nodes = ui() + after = card_enabled(nodes, label) # True + + ok = tapped and before is False and after is True + record("interaction_keyboard_enable", ok, + "" if ok else f"behavior_wrong: {label} layout did not enable " + f"false->true (before={before}, after={after})", + depth=2, jump_kind="transition", + expect=f"{label} layout checkmark false->true") + + vlm_assert("interaction_keyboard_enable", + f"This is a grid of keyboard-layout cards. Does the card labelled " + f"'{label}' now show a check-mark badge indicating it is enabled?", + RD, expect="YES", depth=2, jump_kind="transition", tag="shape") + + # Restore disabled so later runs start clean. + if after is True: + tap_card(ui(), label) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 6) Multi-record integrity in Keyboards: enabling one keeps the PRIMARY enabled +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_keyboard_primary_stays_enabled",)) +def test_keyboard_primary_stays_enabled(): + and_enter_home() + nodes = and_reach_keyboards() + if nodes is None: + record("interaction_keyboard_primary_stays_enabled", False, + "setup_failed: could not reach the Keyboards browser", + depth=2, jump_kind="value", + expect="English stays enabled=True while another layout is enabled") + return + + primary = "English" + primary0 = card_enabled(nodes, primary) # expected True (QWERTY primary) + if primary0 is None: + record("interaction_keyboard_primary_stays_enabled", False, + "feature_missing: primary 'English' layout card not present", + depth=2, jump_kind="value", + expect="English stays enabled=True while another layout is enabled") + return + + label = _pick_disabled(nodes, KBD_OFF_CANDS) + if label is None: + record("interaction_keyboard_primary_stays_enabled", False, + "feature_missing: no disabled layout to enable alongside primary", + depth=2, jump_kind="value", + expect="English stays enabled=True while another layout is enabled") + return + + tap_card(nodes, label) # enable a second layout + nodes = ui() + added = card_enabled(nodes, label) # True + primary1 = card_enabled(nodes, primary) # still True (multi-enable) + + ok = primary0 is True and added is True and primary1 is True + record("interaction_keyboard_primary_stays_enabled", ok, + "" if ok else f"behavior_wrong: enabling {label} disturbed the primary " + f"(English {primary0}->{primary1}, {label}->{added})", + depth=2, jump_kind="value", + expect=f"English enabled=True unchanged while {label} enabled=True") + + # Restore the added layout to disabled. + if added is True: + tap_card(ui(), label) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 7) Theme SINGLE-select (depth 2) — selecting one DESELECTS the previous +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_theme_single_select", + "interaction_theme_single_select_vlm")) +def test_theme_single_select(): + and_enter_home() + nodes = and_reach_theme_selector() + if nodes is None: + record("interaction_theme_single_select", False, + "setup_failed: could not reach Select theme", + depth=2, jump_kind="transition", + expect="single-select: new theme on, previous off") + record("interaction_theme_single_select_vlm", False, + "setup_failed: could not reach Select theme", + depth=2, jump_kind="transition", tag="shape") + return + + current = _pick_enabled(nodes, THEME_CARDS) # the one selected theme + target = _pick_disabled(nodes, THEME_CARDS) # a different, unselected theme + if current is None or target is None: + record("interaction_theme_single_select", False, + "feature_missing: could not find one selected + one unselected theme", + depth=2, jump_kind="transition", + expect="single-select: new theme on, previous off") + record("interaction_theme_single_select_vlm", False, + "setup_failed: theme cards not in expected state", + depth=2, jump_kind="transition", tag="shape") + return + + tap_card(nodes, target) + nodes = ui() + tgt_on = card_enabled(nodes, target) # True + cur_off = card_enabled(nodes, current) # flipped to False (the key point) + + ok = tgt_on is True and cur_off is False + record("interaction_theme_single_select", ok, + "" if ok else f"behavior_wrong: single-select failed " + f"({target} on={tgt_on}, previous {current} " + f"off={cur_off})", + depth=2, jump_kind="transition", + expect=f"single-select: {target} checked, {current} unchecked") + + # VLM: exactly one theme card carries a check-mark now. + vlm_assert("interaction_theme_single_select", + "This is a grid of keyboard-theme cards. Does EXACTLY ONE theme " + "card show a check-mark badge (not zero and not more than one)?", + RD, expect="YES", depth=2, jump_kind="transition", tag="shape") + + # Restore the original selection. + nodes = ui() + if card_enabled(nodes, current) is not True: + tap_card(nodes, current) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 8) Theme selection PERSISTENCE across process death (depth 2) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_theme_persists_process_death", + "interaction_theme_persists_process_death_vlm")) +def test_theme_persists_process_death(): + and_enter_home() + nodes = and_reach_theme_selector() + if nodes is None: + record("interaction_theme_persists_process_death", False, + "setup_failed: could not reach Select theme", + depth=2, jump_kind="transition", + expect="selected theme survives process kill") + record("interaction_theme_persists_process_death_vlm", False, + "setup_failed: could not reach Select theme", + depth=2, jump_kind="transition", tag="content") + return + + original = _pick_enabled(nodes, THEME_CARDS) + target = _pick_disabled(nodes, THEME_CARDS) + if original is None or target is None: + record("interaction_theme_persists_process_death", False, + "feature_missing: could not find one selected + one unselected theme", + depth=2, jump_kind="transition", + expect="selected theme survives process kill") + record("interaction_theme_persists_process_death_vlm", False, + "setup_failed: theme cards not in expected state", + depth=2, jump_kind="transition", tag="content") + return + + tap_card(nodes, target) + nodes = ui() + selected_now = card_enabled(nodes, target) # True + + # Kill + relaunch, then NAVIGATE back to Select theme (depth claimed there). + force_stop_and_relaunch() + and_reach_home_after_relaunch() + nodes = and_reach_theme_selector() + persisted = card_enabled(nodes, target) if nodes is not None else None + orig_now = card_enabled(nodes, original) if nodes is not None else None + + ok = selected_now is True and persisted is True and orig_now is False + record("interaction_theme_persists_process_death", ok, + "" if ok else f"behavior_wrong: {target} selection did not survive " + f"process death (selected={selected_now}, " + f"after_relaunch={persisted}, prev {original}={orig_now})", + depth=2, jump_kind="transition", + expect=f"{target} still selected after force-stop + relaunch") + + # VLM: the keyboard preview at the top now renders the chosen theme's colours. + if nodes is not None: + vlm_assert("interaction_theme_persists_process_death", + "There is a keyboard preview near the top of this theme-selection " + "screen. Below it, is there exactly one theme card marked with a " + "check-mark badge?", + RD, expect="YES", depth=2, jump_kind="transition", tag="content") + else: + record("interaction_theme_persists_process_death_vlm", False, + "setup_failed: could not reach Select theme after relaunch", + depth=2, jump_kind="transition", tag="content") + + # Restore the original theme. + if nodes is not None: + nodes = ui() + if card_enabled(nodes, original) is not True: + tap_card(nodes, original) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 9) 3-STEP SEQUENCE: UI -> themes -> select -> BACK -> reopen -> still selected +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("interaction_theme_survives_nav_away", + "interaction_theme_survives_nav_away_vlm")) +def test_theme_survives_nav_away(): + and_enter_home() + nodes = and_reach_theme_selector() + if nodes is None: + record("interaction_theme_survives_nav_away", False, + "setup_failed: could not reach Select theme", + depth=2, jump_kind="value", + expect="selected theme still checked after leaving + reopening") + record("interaction_theme_survives_nav_away_vlm", False, + "setup_failed: could not reach Select theme", + depth=2, jump_kind="value", tag="content") + return + + original = _pick_enabled(nodes, THEME_CARDS) + target = _pick_disabled(nodes, THEME_CARDS) + if original is None or target is None: + record("interaction_theme_survives_nav_away", False, + "feature_missing: could not find one selected + one unselected theme", + depth=2, jump_kind="value", + expect="selected theme still checked after leaving + reopening") + record("interaction_theme_survives_nav_away_vlm", False, + "setup_failed: theme cards not in expected state", + depth=2, jump_kind="value", tag="content") + return + + # Step 1: select the target theme. + tap_card(nodes, target) + nodes = ui() + step1 = card_enabled(nodes, target) # True + + # Step 2: navigate AWAY — BACK to the UI tab, then to a different tab (Home), + # so we truly leave the theme surface, not just pop one frame. + and_back() # Select theme -> UI tab + nodes = ui() + home = (node_by_id(nodes, "mainFragment") + or find_node(nodes, content_desc="Hello")) + if home is not None: + tap_node(home) + ui() + + # Step 3: re-enter Select theme from scratch and re-read. + nodes = ui() + uitab = (node_by_id(nodes, "userInterfaceSettingsFragment") + or find_node(nodes, content_desc="UI")) + reopened = None + if uitab is not None and tap_node(uitab): + nodes = ui() + row = find_node_ci(nodes, "Pick and configure keyboard themes.") + if row is not None and tap_node(row): + nodes = ui() + and_enter("select_theme_reopen") + reopened = card_enabled(nodes, target) + + ok = step1 is True and reopened is True + record("interaction_theme_survives_nav_away", ok, + "" if ok else f"behavior_wrong: {target} not still selected after " + f"leaving and reopening (step1={step1}, " + f"reopened={reopened})", + depth=2, jump_kind="value", + expect=f"{target} still checked after nav away + reopen") + + # VLM: after reopening, exactly one theme card is checked. + if reopened is not None: + vlm_assert("interaction_theme_survives_nav_away", + "This keyboard-theme selection screen was just reopened after " + "navigating away. Is exactly one theme card marked with a " + "check-mark badge?", + RD, expect="YES", depth=2, jump_kind="value", tag="content") + else: + record("interaction_theme_survives_nav_away_vlm", False, + "setup_failed: could not reopen Select theme", + depth=2, jump_kind="value", tag="content") + + # Restore the original theme. + nodes = ui() + if card_enabled(nodes, original) is not True: + tap_card(nodes, original) + + +TESTS = [ + test_emoji_toggle_off, + test_emoji_toggle_roundtrip, + test_emoji_multi_record_integrity, + test_emoji_persists_process_death, + test_keyboard_enable, + test_keyboard_primary_stays_enabled, + test_theme_single_select, + test_theme_persists_process_death, + test_theme_survives_nav_away, +] + + +if __name__ == "__main__": + run_suite(TESTS, "interaction") diff --git a/android/anysoftkeyboard-anysoftkeyboard/tests/test_android_navigation.py b/android/anysoftkeyboard-anysoftkeyboard/tests/test_android_navigation.py new file mode 100644 index 0000000000000000000000000000000000000000..86067b17a43d4401c52b64da88adb2d4e4458b12 --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/tests/test_android_navigation.py @@ -0,0 +1,634 @@ +#!/usr/bin/env python3 +"""NAVIGATION test suite for AnySoftKeyboard's settings UI. + +Lane: surface REACHABILITY + back-stack integrity. This file is the SOLE owner of +jump_kind="reach" and of the deep (depth>=2) chains for the suite. + +The app is a single Activity (MainSettingsActivity) hosting a NavHostFragment plus +a BottomNavigationView with 5 tabs, driven by the Navigation component. Because +navigation never changes the Activity, get_current_activity() cannot discriminate a +jump — every reach here is proven the ONLY honest way: the TARGET surface's +discriminating element APPEARED *and* the SOURCE surface's element DISAPPEARED +(and_reach / and_reach_surface). A screen that was in the dump all along was never +"reached". + +Ground truth (read from the running original + recon/*.xml, then re-verified live): + home (mainFragment) : title "Welcome to AnySoftKeyboard"; also carries an + "AnySoftKeyboard Dev" TextView — so that string is NOT an + About-only marker and cannot be a reach target. + About : About-unique text "Additional Software Licenses" and + "Version 1.13.1, version-code 1." (both absent on home). + overflow "More options": popup adds Backup / Restore / Tweaks. + Language tab : rows "Enable keyboards and languages.", + "Configure correction behavior and other dictionaries.", + "Tweaks and more.". + Language>Enable... : "Keyboards" browser — cards "QWERTY Latin keyboard", + "Dvorak", etc. NB the Language row itself contains the + substring "keyboards", so the browser is discriminated by a + CARD label ("QWERTY Latin keyboard") that is absent on the + Language tab, not by the loose token "Keyboards". + Language>Tweaks : language tweaks (category "Keyboard Behavior", + "Show suggestions"). Its title is again "Tweaks and more.", + so the sub-screen marker must be "Show suggestions". + UI tab : rows "Pick and configure keyboard themes.", + "Keyboard effects and experience.", "Tweaks and more.". + UI>Pick... : "Select theme" (theme cards "Yochees Dark" etc.). + UI>Keyboard effects...: effects screen (category "Effects", "Power-Saving settings"). + Gestures tab : rows "Swipe up" .. with summaries "Currently, Shift" etc. + Gestures>Swipe up : radio dialog "Select swipe up action". + Emojis tab : title "Quick Text groups and order" (cards Emoticons/People). + +Every navigation re-dumps with ui(). Dialogs/popups are dismissed with BACK. +Exploratory taps route through safe_tap; destructive controls (e.g. "Clear entire +text") are never tapped. VLM screenshots are captured while ON the reached surface, +and each question names an exact rendered property observed on the original. +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +# Home's discriminating title — the SOURCE element for every "leaving home" reach. +HOME_TITLE = "Welcome to AnySoftKeyboard" + +# The 5 bottom-nav tabs by stable content-desc, paired with a row/title text that is +# UNIQUE to that tab's surface (used as the reach TARGET; toolbar titles like "UI" +# collide with the nav label, so a row string is the honest discriminator). +TAB_TARGET = { + "Language": "Enable keyboards and languages.", + "UI": "Pick and configure keyboard themes.", + "Gestures": "Swipe up", + "Setup Emojis": "Quick Text groups and order", +} + + +# ── Shared entry point (own copy; sibling suites stay independent) ──────────────── +def and_enter_home(): + """Bring the app to its home surface, tolerating the first-run setup wizard. + + On a fresh data state the launch shows the setup wizard first (a node with + resource-id suffix `skip_setup_wizard` / text "Skip"); tap it if present and + re-dump. Returns the home node list. Home is depth 0 — this crosses no surface + (and deliberately does NOT call an and_enter*, so a relaunch never inflates a + reach claim). + """ + restart_app() + wait_for_foreground() + nodes = ui() + skip = node_by_id(nodes, "skip_setup_wizard") or find_node_ci(nodes, "Skip") + if skip and is_safe(skip): + tap_node(skip) + nodes = ui() + return nodes + + +def _tab_node(nodes, desc): + return find_node(nodes, content_desc=desc, clickable="true") + + +def _clickable_row_for(nodes, label_node): + """A preference title is a non-clickable TextView; the tap handler lives on an + ancestor row. Return the smallest clickable node whose bounds fully contain the + label, falling back to the label itself (its centre still lies inside the row).""" + if not label_node or "_bounds" not in label_node: + return label_node + lx1, ly1, lx2, ly2 = label_node["_bounds"] + best, best_area = None, None + for n in nodes: + if n.get("clickable") != "true" or "_bounds" not in n: + continue + x1, y1, x2, y2 = n["_bounds"] + if x1 <= lx1 and y1 <= ly1 and x2 >= lx2 and y2 >= ly2: + area = (x2 - x1) * (y2 - y1) + if best_area is None or area < best_area: + best, best_area = n, area + return best or label_node + + +# ── Depth-backed reach helpers (name prefix and_reach_/and_enter_ backs depth) ─── +def and_reach_tab(home_nodes, desc, target_text): + """From home, tap a bottom-nav tab and PROVE the jump: `target_text` (a row/ + title unique to that tab) appeared and the home title disappeared. A tab switch + swaps the NavHostFragment content — a real surface — counted via and_enter. + + Returns (ok, after_nodes). Uses an explicit before/after and_reach (rather than + and_reach_surface) so the SOURCE=home-title disappearance is asserted, not just + the target's appearance.""" + tab = _tab_node(home_nodes, desc) + if not tab: + return False, home_nodes + before = and_showing(home_nodes) + if not tap_node(tab): + return False, home_nodes + after_nodes = ui() + after = and_showing(after_nodes) + ok = and_reach(before, after, target_text, HOME_TITLE) + if ok: + and_enter(f"tab:{desc}") + return ok, after_nodes + + +def and_reach_about(home_nodes): + """From home, open the toolbar About screen and prove the jump: the About-only + row 'Additional Software Licenses' appeared and the home title disappeared. + (The 'AnySoftKeyboard Dev' string lives on home too, so it is NOT the target.) + Returns (ok, after_nodes).""" + btn = find_node(home_nodes, content_desc="About") \ + or node_by_id(home_nodes, "about_menu_option") + if not btn: + return False, home_nodes + before = and_showing(home_nodes) + if not safe_tap(btn): + return False, home_nodes + after_nodes = ui() + after = and_showing(after_nodes) + ok = and_reach(before, after, "Additional Software Licenses", HOME_TITLE) + if ok: + and_enter("About") + return ok, after_nodes + + +def and_reach_row(source_nodes, row_label, target_text, source_text): + """Generic depth step: tap the clickable row carrying `row_label` on the current + surface, then prove `target_text` appeared and `source_text` vanished. Returns + (ok, after_nodes). Backs a depth increment on success (and_reach_* naming).""" + label = find_node_ci(source_nodes, row_label) + if not label: + return False, source_nodes + row = _clickable_row_for(source_nodes, label) + if not is_safe(row): + return False, source_nodes + before = and_showing(source_nodes) + if not tap_node(row): + return False, source_nodes + after_nodes = ui() + after = and_showing(after_nodes) + ok = and_reach(before, after, target_text, source_text) + if ok: + and_enter(target_text) + return ok, after_nodes + + +def and_reach_keyboards(lang_nodes): + """Language -> 'Enable keyboards and languages.' -> Keyboards browser. Target is + a card label unique to the browser ('QWERTY Latin keyboard'); the source row + text disappears. (The loose token 'Keyboards' is a substring of the Language row + 'Enable keyboards and languages.', so it is NOT usable as a discriminator.)""" + return and_reach_row(lang_nodes, "Enable keyboards and languages.", + "QWERTY Latin keyboard", + "Enable keyboards and languages.") + + +def and_reach_select_theme(ui_nodes): + """UI -> 'Pick and configure keyboard themes.' -> Select-theme surface + (title 'Select theme' appears, the UI row disappears).""" + return and_reach_row(ui_nodes, "Pick and configure keyboard themes.", + "Select theme", "Pick and configure keyboard themes.") + + +def and_reach_effects(ui_nodes): + """UI -> 'Keyboard effects and experience.' -> effects screen (category-row + 'Power-Saving settings' appears, the UI row disappears).""" + return and_reach_row(ui_nodes, "Keyboard effects and experience.", + "Power-Saving settings", "Keyboard effects and experience.") + + +def and_reach_language_tweaks(lang_nodes): + """Language -> 'Tweaks and more.' -> language tweaks (toggle 'Show suggestions' + appears; source 'Enable keyboards and languages.' — a Language-tab-only row that + the tweaks screen does NOT show — disappears). The row title 'Tweaks and more.' + itself recurs on the sub-screen, so it cannot be the source.""" + label = find_node_ci(lang_nodes, "Tweaks and more.") + if not label: + return False, lang_nodes + row = _clickable_row_for(lang_nodes, label) + if not is_safe(row): + return False, lang_nodes + before = and_showing(lang_nodes) + if not tap_node(row): + return False, lang_nodes + after_nodes = ui() + after = and_showing(after_nodes) + ok = and_reach(before, after, "Show suggestions", + "Enable keyboards and languages.") + if ok: + and_enter("language_tweaks") + return ok, after_nodes + + +def and_reach_swipe_dialog(gest_nodes): + """Gestures -> 'Swipe up' -> radio dialog (title 'Select swipe up action' + appears; the 'Swipe down' row behind it is covered by the dialog window and + disappears from the dump).""" + label = find_node_ci(gest_nodes, "Swipe up") + if not label: + return False, gest_nodes + row = _clickable_row_for(gest_nodes, label) + if not is_safe(row): + return False, gest_nodes + before = and_showing(gest_nodes) + if not tap_node(row): + return False, gest_nodes + after_nodes = ui() + after = and_showing(after_nodes) + ok = and_reach(before, after, "Select swipe up action", "Swipe down") + if ok: + and_enter("swipe_up_dialog") + return ok, after_nodes + + +# ════════════════════════════════════════════════════════════════════════════════ +# 1) Home -> About (depth 1, reach) + BACK restores home +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_about", "nav_reach_about_vlm", + "nav_back_about_to_home")) +def test_reach_about_and_back(): + home = and_enter_home() + ok_home = find_node_ci(home, HOME_TITLE) is not None + ok_reach, about = and_reach_about(home) + + # VLM while ON the About surface: the About layout centres a large circular app + # icon with the title directly beneath it (a POSITION property). + vlm_assert("nav_reach_about", + "Is there a large circular icon positioned in the horizontal centre " + "of the screen, with a bold title text directly beneath it?", + RESULTS_DIR, depth=1, jump_kind="reach", tag="position") + + record("nav_reach_about", ok_home and ok_reach, + "" if (ok_home and ok_reach) else + ("setup_failed: home title not shown before navigating" if not ok_home + else "feature_missing: About not reached (its 'Additional Software " + "Licenses' row did not appear while the home title left)"), + depth=1, jump_kind="reach", + expect="About surface: 'Additional Software Licenses' appeared and " + "'Welcome to AnySoftKeyboard' disappeared") + + # BACK from About restores home (source About row gone, home title back). + before_back = and_showing(about) + and_back() + home2 = ui() + after_back = and_showing(home2) + back_ok = ok_reach and and_reach(before_back, after_back, HOME_TITLE, + "Additional Software Licenses") + record("nav_back_about_to_home", back_ok, + "" if back_ok else + "behavior_wrong: BACK from About did not restore the home surface", + depth=1, jump_kind="reach", + expect="After one BACK: home title 'Welcome to AnySoftKeyboard' restored " + "and About's 'Additional Software Licenses' gone") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 2) Home -> overflow "More options" popup (depth 1, reach) +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_overflow_menu",)) +def test_reach_overflow_menu(): + """The toolbar overflow opens a popup that ADDS Backup/Restore/Tweaks. A popup + makes uiautomator dump the popup ALONE, so the home title vanishes from the dump + — a genuine surface swap. Reach target 'Restore' appeared; source home title + gone. Backup/Restore are never TAPPED (they write files); dismissed with BACK.""" + home = and_enter_home() + overflow = find_node(home, content_desc="More options") + ok_reach = False + if overflow is not None: + before = and_showing(home) + if safe_tap(overflow): + popup = ui() + after = and_showing(popup) + ok_reach = and_reach(before, after, "Restore", HOME_TITLE) + if ok_reach: + and_enter("overflow_popup") + # also confirm the sibling items are present on the popup surface + three = all(find_node_ci(popup, t) is not None + for t in ("Backup", "Restore", "Tweaks")) + ok_reach = ok_reach and three + back() # dismiss popup, do not act on any destructive item + record("nav_reach_overflow_menu", ok_reach, + "" if ok_reach else + ("feature_missing: overflow 'More options' affordance absent" + if overflow is None else + "behavior_wrong: overflow popup did not expose Backup/Restore/Tweaks " + "as a new surface"), + depth=1, jump_kind="reach", + expect="Overflow popup surface: 'Restore' (with Backup & Tweaks) appeared " + "and 'Welcome to AnySoftKeyboard' left the dump") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 3-7) Each of the 5 top-level tabs reachable from Home (depth 1, reach) +# Home is itself a tab; reaching it from another tab is the 5th case. +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_tab_language",)) +def test_reach_tab_language(): + home = and_enter_home() + ok, _ = and_reach_tab(home, "Language", TAB_TARGET["Language"]) + record("nav_reach_tab_language", ok, + "" if ok else "feature_missing: Language tab did not surface its rows " + "while the home title left", + depth=1, jump_kind="reach", + expect="Language tab: 'Enable keyboards and languages.' appeared and " + "'Welcome to AnySoftKeyboard' disappeared") + + +@and_test(expects=("nav_reach_tab_ui", "nav_reach_tab_ui_vlm")) +def test_reach_tab_ui(): + home = and_enter_home() + ok, ui_nodes = and_reach_tab(home, "UI", TAB_TARGET["UI"]) + # VLM: the UI tab's app-bar is a light purple/violet strip across the full width + # at the very top (a COLOR property observed on the original). + vlm_assert("nav_reach_tab_ui", + "Is there a light purple / violet coloured bar spanning the full " + "width across the very top of the screen (just below the status bar)?", + RESULTS_DIR, depth=1, jump_kind="reach", tag="color") + record("nav_reach_tab_ui", ok, + "" if ok else "feature_missing: UI tab did not surface its rows while " + "the home title left", + depth=1, jump_kind="reach", + expect="UI tab: 'Pick and configure keyboard themes.' appeared and " + "'Welcome to AnySoftKeyboard' disappeared") + + +@and_test(expects=("nav_reach_tab_gestures", "nav_reach_tab_gestures_vlm")) +def test_reach_tab_gestures(): + home = and_enter_home() + ok, gest = and_reach_tab(home, "Gestures", TAB_TARGET["Gestures"]) + vlm_assert("nav_reach_tab_gestures", + "Is the screen a vertically-scrollable list of gesture settings " + "rows (such as Swipe up / Swipe down / Swipe left / Swipe right), " + "each with a title and a smaller grey description line below it?", + RESULTS_DIR, depth=1, jump_kind="reach", tag="layout") + record("nav_reach_tab_gestures", ok, + "" if ok else "feature_missing: Gestures tab did not surface its rows " + "while the home title left", + depth=1, jump_kind="reach", + expect="Gestures tab: 'Swipe up' appeared and 'Welcome to " + "AnySoftKeyboard' disappeared") + + +@and_test(expects=("nav_reach_tab_emojis",)) +def test_reach_tab_emojis(): + home = and_enter_home() + ok, _ = and_reach_tab(home, "Setup Emojis", TAB_TARGET["Setup Emojis"]) + record("nav_reach_tab_emojis", ok, + "" if ok else "feature_missing: Emojis tab did not surface its title " + "while the home title left", + depth=1, jump_kind="reach", + expect="Emojis tab: 'Quick Text groups and order' appeared and " + "'Welcome to AnySoftKeyboard' disappeared") + + +@and_test(expects=("nav_reach_tab_home_from_language",)) +def test_reach_tab_home_from_language(): + """The 5th tab (Home) reached by navigation, not relaunch: go to Language first, + then tap the Home tab and prove the home title reappeared and the Language row + left.""" + home = and_enter_home() + ok_lang, lang = and_reach_tab(home, "Language", TAB_TARGET["Language"]) + ok_home = False + if ok_lang: + home_tab = _tab_node(lang, "Hello") + if home_tab is not None: + before = and_showing(lang) + if tap_node(home_tab): + after = and_showing() + ok_home = and_reach(before, after, HOME_TITLE, + TAB_TARGET["Language"]) + if ok_home: + and_enter("tab:Home") + record("nav_reach_tab_home_from_language", ok_lang and ok_home, + "" if (ok_lang and ok_home) else + ("setup_failed: could not reach Language first" if not ok_lang else + "behavior_wrong: Home tab did not restore the home title from Language"), + depth=1, jump_kind="reach", + expect="Home tab from Language: 'Welcome to AnySoftKeyboard' appeared and " + "'Enable keyboards and languages.' disappeared") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 8) Home -> Language -> "Keyboards" browser (depth 2, reach) + BACK +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_keyboards_depth2", "nav_reach_keyboards_depth2_vlm", + "nav_back_keyboards_to_language")) +def test_reach_keyboards_depth2(): + home = and_enter_home() + ok_lang, lang = and_reach_tab(home, "Language", TAB_TARGET["Language"]) + ok_kbd, kbd = and_reach_keyboards(lang) if ok_lang else (False, lang) + + # VLM: the Keyboards browser lays its preview cards out in a two-column grid + # (a POSITION property observed on the original). + vlm_assert("nav_reach_keyboards_depth2", + "Are the keyboard-layout preview cards arranged in a two-column grid " + "(two cards positioned side by side per row)?", + RESULTS_DIR, depth=2, jump_kind="reach", tag="position") + + record("nav_reach_keyboards_depth2", ok_lang and ok_kbd, + "" if (ok_lang and ok_kbd) else + ("setup_failed: Language tab not reached" if not ok_lang else + "feature_missing: 'Keyboards' browser not reached from the Language row"), + depth=2, jump_kind="reach", + expect="Home->Language->Keyboards: card 'QWERTY Latin keyboard' appeared " + "and 'Enable keyboards and languages.' disappeared") + + # BACK once unwinds the deepest hop -> the Language tab is restored. Source is + # the browser-unique card label (the Language row would still contain the loose + # substring 'keyboards', so it cannot be the disappearing token). + before_back = and_showing(kbd) + and_back() + lang2 = ui() + after_back = and_showing(lang2) + back_ok = ok_kbd and and_reach(before_back, after_back, + "Enable keyboards and languages.", + "QWERTY Latin keyboard") + record("nav_back_keyboards_to_language", back_ok, + "" if back_ok else + "behavior_wrong: one BACK from Keyboards did not restore the Language tab", + depth=1, jump_kind="reach", + expect="After one BACK: 'Enable keyboards and languages.' restored and " + "the card 'QWERTY Latin keyboard' gone") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 9) Home -> UI -> "Select theme" (depth 2, reach) +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_select_theme_depth2", + "nav_reach_select_theme_depth2_vlm")) +def test_reach_select_theme_depth2(): + home = and_enter_home() + ok_ui, ui_nodes = and_reach_tab(home, "UI", TAB_TARGET["UI"]) + ok_theme, theme = and_reach_select_theme(ui_nodes) if ok_ui else (False, ui_nodes) + + # VLM: the theme preview cards sit in a two-column grid (POSITION property). + vlm_assert("nav_reach_select_theme_depth2", + "Are there keyboard THEME preview cards arranged in a two-column grid " + "(two cards positioned side by side per row)?", + RESULTS_DIR, depth=2, jump_kind="reach", tag="position") + + record("nav_reach_select_theme_depth2", ok_ui and ok_theme, + "" if (ok_ui and ok_theme) else + ("setup_failed: UI tab not reached" if not ok_ui else + "feature_missing: 'Select theme' not reached from the UI themes row"), + depth=2, jump_kind="reach", + expect="Home->UI->Select theme: 'Select theme' appeared and 'Pick and " + "configure keyboard themes.' disappeared") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 10) Gestures -> "Swipe up" dialog (depth 1, reach) + BACK restores Gestures +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_swipe_dialog", "nav_back_swipe_dialog_to_gestures")) +def test_reach_swipe_dialog_and_back(): + home = and_enter_home() + ok_gest, gest = and_reach_tab(home, "Gestures", TAB_TARGET["Gestures"]) + ok_dlg, dlg = and_reach_swipe_dialog(gest) if ok_gest else (False, gest) + + record("nav_reach_swipe_dialog", ok_gest and ok_dlg, + "" if (ok_gest and ok_dlg) else + ("setup_failed: Gestures tab not reached" if not ok_gest else + "feature_missing: 'Swipe up' radio dialog did not open"), + depth=1, jump_kind="reach", + expect="Gestures->Swipe up: dialog title 'Select swipe up action' " + "appeared and the 'Swipe down' row disappeared behind it") + + # Dismiss with BACK (never tap 'Clear entire text') -> Gestures list restored. + before_back = and_showing(dlg) + and_back() + gest2 = ui() + after_back = and_showing(gest2) + back_ok = ok_dlg and and_reach(before_back, after_back, "Swipe down", + "Select swipe up action") + record("nav_back_swipe_dialog_to_gestures", back_ok, + "" if back_ok else + "behavior_wrong: BACK did not dismiss the dialog back to the Gestures list", + depth=1, jump_kind="reach", + expect="After BACK: the 'Swipe down' row is visible again and the dialog " + "title 'Select swipe up action' is gone") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 11) Home -> Language -> "Tweaks and more." (depth 2, reach) +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_language_tweaks_depth2",)) +def test_reach_language_tweaks_depth2(): + home = and_enter_home() + ok_lang, lang = and_reach_tab(home, "Language", TAB_TARGET["Language"]) + ok_tw, _ = and_reach_language_tweaks(lang) if ok_lang else (False, lang) + record("nav_reach_language_tweaks_depth2", ok_lang and ok_tw, + "" if (ok_lang and ok_tw) else + ("setup_failed: Language tab not reached" if not ok_lang else + "feature_missing: language tweaks ('Show suggestions') not reached"), + depth=2, jump_kind="reach", + expect="Home->Language->Tweaks: 'Show suggestions' appeared and the " + "Language row 'Enable keyboards and languages.' disappeared") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 12) BACK-STACK unwind: Home -> UI -> Select theme, then BACK to UI, BACK to Home +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_backstack_theme_unwind",)) +def test_backstack_theme_unwind(): + """From the depth-2 Select-theme surface, BACK pops one hop to the UI tab (its + rows return, the theme title leaves), and a second BACK pops to Home (the home + title returns, the UI row leaves). Asserts each intermediate surface, hop by + hop — the back stack from the deepest surface back to home.""" + home = and_enter_home() + ok_ui, ui_nodes = and_reach_tab(home, "UI", TAB_TARGET["UI"]) + ok_theme, theme = and_reach_select_theme(ui_nodes) if ok_ui else (False, ui_nodes) + + # Pop 1: Select theme -> UI tab. + before1 = and_showing(theme) + and_back() + ui2 = ui() + after1 = and_showing(ui2) + pop1 = ok_theme and and_reach(before1, after1, TAB_TARGET["UI"], "Select theme") + + # Pop 2: UI tab -> Home. + before2 = and_showing(ui2) + and_back() + home2 = ui() + after2 = and_showing(home2) + pop2 = pop1 and and_reach(before2, after2, HOME_TITLE, TAB_TARGET["UI"]) + + ok = ok_ui and ok_theme and pop1 and pop2 + if not (ok_ui and ok_theme): + msg = "setup_failed: could not build the Home->UI->Select theme chain" + elif not pop1: + msg = "behavior_wrong: first BACK from Select theme did not restore the UI tab" + elif not pop2: + msg = "behavior_wrong: second BACK did not restore Home from the UI tab" + else: + msg = "" + record("nav_backstack_theme_unwind", ok, msg, + depth=2, jump_kind="reach", + expect="BACK #1: UI row 'Pick and configure keyboard themes.' restored & " + "'Select theme' gone; BACK #2: home title restored & UI row gone") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 13) DEEP CHAIN: Home -> UI -> "Keyboard effects and experience." -> effects +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_effects_depth2", "nav_reach_effects_depth2_vlm", + "nav_back_effects_to_ui")) +def test_reach_effects_depth2(): + home = and_enter_home() + ok_ui, ui_nodes = and_reach_tab(home, "UI", TAB_TARGET["UI"]) + ok_eff, eff = and_reach_effects(ui_nodes) if ok_ui else (False, ui_nodes) + + # VLM: the effects screen shows filled/ticked checkboxes on the right of some + # rows (e.g. 'Use system vibration', 'Vibrate on long-press') — a SHAPE property. + vlm_assert("nav_reach_effects_depth2", + "Is there at least one filled / ticked check-box on the right-hand " + "side of a settings row on this screen?", + RESULTS_DIR, depth=2, jump_kind="reach", tag="shape") + + record("nav_reach_effects_depth2", ok_ui and ok_eff, + "" if (ok_ui and ok_eff) else + ("setup_failed: UI tab not reached" if not ok_ui else + "feature_missing: effects screen ('Power-Saving settings') not reached"), + depth=2, jump_kind="reach", + expect="Home->UI->effects: 'Power-Saving settings' appeared and 'Keyboard " + "effects and experience.' disappeared") + + # BACK unwinds the deepest hop -> the UI tab is restored. + before_back = and_showing(eff) + and_back() + ui2 = ui() + after_back = and_showing(ui2) + back_ok = ok_eff and and_reach(before_back, after_back, + "Keyboard effects and experience.", + "Power-Saving settings") + record("nav_back_effects_to_ui", back_ok, + "" if back_ok else + "behavior_wrong: one BACK from effects did not restore the UI tab", + depth=1, jump_kind="reach", + expect="After one BACK: UI row 'Keyboard effects and experience.' restored " + "and 'Power-Saving settings' gone") + + +TESTS = [ + test_reach_about_and_back, + test_reach_overflow_menu, + test_reach_tab_language, + test_reach_tab_ui, + test_reach_tab_gestures, + test_reach_tab_emojis, + test_reach_tab_home_from_language, + test_reach_keyboards_depth2, + test_reach_select_theme_depth2, + test_reach_swipe_dialog_and_back, + test_reach_language_tweaks_depth2, + test_backstack_theme_unwind, + test_reach_effects_depth2, +] + +if __name__ == "__main__": + run_suite(TESTS, "navigation") diff --git a/android/anysoftkeyboard-anysoftkeyboard/tests/test_android_states.py b/android/anysoftkeyboard-anysoftkeyboard/tests/test_android_states.py new file mode 100644 index 0000000000000000000000000000000000000000..dfc155879d3adcba9841a513fe9ac7156b41eb26 --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/tests/test_android_states.py @@ -0,0 +1,763 @@ +#!/usr/bin/env python3 +"""STATES test suite for AnySoftKeyboard's settings UI. + +Lane: checked / selected / enabled / focused TRANSITIONS, each PAIRED with its +app-authored consequence, plus SETTINGS persistence across process death. This file +is the SOLE owner of `checked` and `selected` for the suite. + +The app is a single Activity (MainSettingsActivity) hosting a NavHostFragment plus a +BottomNavigationView with 5 tabs (Navigation component + PreferenceFragments). The +state surfaces exercised here (ground truth read from the running original and +re-verified against recon/*.xml): + + * Bottom-nav single-select: exactly ONE tab FrameLayout carries selected="true" + and shows its large text label; tapping another tab moves selected onto it AND + clears it from the previous tab (the label appears on the new one). This is the + page-level state machine — the consequence is the moved selection + label. + * Gestures tab (gesturesSettingsFragment): CheckBox "Enable gesture-typing [BETA]" + (rid suffix `checkbox`), default checked="false". Tapping the row flips it + false->true AND pops an app-authored "BETA Feature!" alert (button "GOT IT") + the first time — a stronger consequence than the flip alone. SharedPrefs- + persisted across a force-stop+relaunch. + * Language > "Tweaks and more." (PreferenceFragment): a Switch "Show suggestions" + (rid suffix `switchWidget`, default checked="true") and CheckBoxes "Suggestions + restart" / "Space switches keyboards" / "Double space to period" / "Remember + alphabet layout per App" (rid suffix `checkbox`, all default checked="true"). + Row tap flips the widget; persisted. + * UI > "Select theme": CheckBox "Change theme colors based on used app" + (rid suffix `apply_overlay`, default checked="false"), directly clickable. + +A preference row's checkable widget is a SIBLING of the title (in a `widget_frame`), +and several checkboxes share one screen, so the widget is located by finding the +title TextView and then the checkable node whose vertical centre falls inside the +title's ROW y-band (`_pref_checkable_for_title`). Every state is read from a FRESH +ui() after the tap; the stale node is re-found with find_closest_match. Depth>=1 +tests are backed by an and_enter_* helper that navigates there. Toggled prefs are +restored to their defaults after each test so later tests see a clean state. +Exploratory taps route through safe_tap; no destructive control is ever tapped. +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +# Bottom-nav tabs by stable resource-id suffix + content-desc. `selected` lives on +# the tab FrameLayout; the recreation's package prefix differs, so match the last id +# segment only (node_by_id) and the content-desc (find_node). +TAB_RID = { + "Home": "mainFragment", + "Language": "languageSettingsFragment", + "UI": "userInterfaceSettingsFragment", + "Gestures": "gesturesSettingsFragment", + "Emojis": "quickTextKeysBrowseFragment", +} +TAB_DESC = { + "Home": "Hello", "Language": "Language", "UI": "UI", + "Gestures": "Gestures", "Emojis": "Setup Emojis", +} + +GESTURE_TITLE = "Enable gesture-typing [BETA]" + + +# ════════════════════════════════════════════════════════════════════════════════ +# Shared entry point + navigation helpers (own copies; sibling suites independent) +# ════════════════════════════════════════════════════════════════════════════════ + +def and_enter_home(): + """Bring the app to its home surface, tolerating the first-run setup wizard. + + On a fresh data state the launch shows the setup wizard first (a node with + resource-id suffix `skip_setup_wizard` / text "Skip"); tap it if present and + re-dump. Home is depth 0 — this deliberately does NOT call an and_enter*, so a + relaunch never inflates a depth claim. Returns the home node list. + """ + restart_app() + wait_for_foreground() + nodes = ui() + skip = node_by_id(nodes, "skip_setup_wizard") or find_node_ci(nodes, "Skip") + if skip and is_safe(skip): + tap_node(skip) + nodes = ui() + return nodes + + +def _tab_node(nodes, name): + """The bottom-nav tab FrameLayout for `name` (the node that carries `selected`). + Prefer the resource-id suffix; fall back to the clickable content-desc node.""" + return (node_by_id(nodes, TAB_RID[name]) + or find_node(nodes, content_desc=TAB_DESC[name], clickable="true") + or find_node(nodes, content_desc=TAB_DESC[name])) + + +def _tab_selected(nodes, name): + """True iff the named tab's FrameLayout reports selected="true" in `nodes`.""" + t = _tab_node(nodes, name) + return bool(t) and t.get("selected") == "true" + + +def _switch_to_tab(home_nodes, name): + """Tap a bottom-nav tab and return the fresh node list after the switch. Counts + one surface (the NavHostFragment content swaps) via and_enter. Returns + (ok, after_nodes).""" + tab = _tab_node(home_nodes, name) + if not tab or not tap_node(tab): + return False, home_nodes + after = ui() + and_enter(f"tab:{name}") + return True, after + + +def _dismiss_beta_dialog(): + """Enabling gesture-typing (and re-entering the Gestures screen while it is ON) + pops an app-authored 'BETA Feature!' alert whose 'GOT IT' button (rid suffix + `button1`) covers the preference list. Dismiss it so the settled list — and the + checkbox in it — can be read. Returns True iff a BETA dialog was present.""" + nodes = ui() + if find_node_ci(nodes, "BETA Feature!") is None: + return False + btn = find_node_ci(nodes, "GOT IT") or node_by_id(nodes, "button1") + if btn: + tap_node(btn) + return True + + +def and_enter_gestures(): + """Home -> Gestures tab. Dismisses the 'BETA Feature!' alert if it appears (it + does when gesture-typing is already ON), confirms arrival by the gesture-typing + title, then counts the surface. Returns the Gestures node list (or None).""" + home = and_enter_home() + tab = _tab_node(home, "Gestures") + if not tab or not tap_node(tab): + return None + _dismiss_beta_dialog() + nodes = ui() + if find_node_ci(nodes, GESTURE_TITLE) is None: + return None + and_enter("Gestures") + return nodes + + +def and_reach_gestures(): + """Alias of and_enter_gestures used by the persistence probe AFTER a relaunch — + the and_reach_/and_enter_ prefix backs the depth increment either way.""" + return and_enter_gestures() + + +def and_enter_lang_tweaks(): + """Home -> Language tab -> row 'Tweaks and more.' -> language tweaks + PreferenceFragment. Confirms arrival by 'Show suggestions'. Two surfaces are + crossed, so and_enter is called twice (depth 2). Returns the tweaks node list + (or None).""" + home = and_enter_home() + lang = _tab_node(home, "Language") + if not lang or not tap_node(lang): + return None + nodes = ui() + and_enter("Language") + row = find_node_ci(nodes, "Tweaks and more.") + if not row or not is_safe(row): + return None + if not tap_node(row): + return None + nodes = ui() + if find_node_ci(nodes, "Show suggestions") is None: + return None + and_enter("language_tweaks") + return nodes + + +def and_reach_lang_tweaks(): + """Alias for the persistence probe after a relaunch (prefix backs depth).""" + return and_enter_lang_tweaks() + + +def and_enter_theme_selector(): + """Home -> UI tab -> row 'Pick and configure keyboard themes.' -> Select-theme + surface. Confirms arrival by the toolbar title 'Select theme'. Two surfaces + crossed (depth 2). Returns the Select-theme node list (or None).""" + home = and_enter_home() + ui_tab = _tab_node(home, "UI") + if not ui_tab or not tap_node(ui_tab): + return None + nodes = ui() + and_enter("UI") + row = find_node_ci(nodes, "Pick and configure keyboard themes.") + if not row or not is_safe(row): + return None + if not tap_node(row): + return None + nodes = ui() + if find_node_ci(nodes, "Select theme") is None: + return None + and_enter("select_theme") + return nodes + + +# ════════════════════════════════════════════════════════════════════════════════ +# Preference-row state helpers +# ════════════════════════════════════════════════════════════════════════════════ + +def _pref_row_for_title(nodes, title_text): + """The clickable preference ROW LinearLayout that contains `title_text`. + + A PreferenceFragment title is a non-clickable TextView (rid `android:id/title`); + the tap handler and the y-band both belong to an ancestor row. Return the + smallest clickable node whose bounds fully contain the title TextView. Falls back + to the title node itself (its centre still lies inside the row).""" + label = find_node_ci(nodes, title_text) + if not label or "_bounds" not in label: + return label, label + lx1, ly1, lx2, ly2 = label["_bounds"] + best, best_area = None, None + for n in nodes: + if n.get("clickable") != "true" or "_bounds" not in n: + continue + x1, y1, x2, y2 = n["_bounds"] + if x1 <= lx1 and y1 <= ly1 and x2 >= lx2 and y2 >= ly2: + area = (x2 - x1) * (y2 - y1) + if best_area is None or area < best_area: + best, best_area = n, area + return (best or label), label + + +def _pref_checkable_for_title(nodes, title_text, cls=None): + """The checkable widget (CheckBox/Switch) belonging to the preference titled + `title_text`. + + Several checkable rows can share one screen, so the widget is disambiguated by + the ROW: find the title's clickable row, then return the checkable="true" node + whose vertical centre falls inside that row's y-band. `cls` optionally narrows to + a widget class substring ("CheckBox" / "Switch"). Returns None if not found.""" + row, label = _pref_row_for_title(nodes, title_text) + if not label or not row or "_bounds" not in row: + return None + ry1, ry2 = row["_bounds"][1], row["_bounds"][3] + for n in nodes: + if n.get("checkable") != "true" or "_center" not in n: + continue + if cls and cls not in n.get("class", ""): + continue + cy = n["_center"][1] + if ry1 <= cy <= ry2: + return n + return None + + +def _read_checked(nodes_or_none, title_text, cls=None, retries=3): + """checked value ("true"/"false"/None) of the widget for `title_text`. + + Reads from `nodes_or_none` if given, otherwise from a fresh ui(). A preference + toggle rebuilds the RecyclerView row, so the title/widget can be briefly absent + while that animation is in flight — re-dump a few times before giving up.""" + if nodes_or_none is not None: + w = _pref_checkable_for_title(nodes_or_none, title_text, cls=cls) + if w is not None: + return w.get("checked") + for _ in range(retries): + w = _pref_checkable_for_title(ui(), title_text, cls=cls) + if w is not None: + return w.get("checked") + settle("tap") + return None + + +def _toggle_pref_row(nodes, title_text): + """Tap the preference row for `title_text` (route through safe_tap). Returns True + if the tap landed.""" + row, _label = _pref_row_for_title(nodes, title_text) + return bool(row) and safe_tap(row) + + +def _restore_checked(title_text, want, cls=None): + """Best-effort: tap the row until its checked matches `want` (max 2 taps), + dismissing the BETA dialog if enabling gesture-typing pops it.""" + for _ in range(2): + cur = _read_checked(None, title_text, cls=cls) + if cur == want or cur is None: + return + _toggle_pref_row(ui(), title_text) + _dismiss_beta_dialog() + + +# A reusable generic body for the language-tweaks CheckBox toggles (items 4-7). +def _run_lang_tweaks_toggle(record_name, title_text, vlm=None): + """Navigate to language tweaks, flip the named CheckBox true->false, assert the + new checked value, restore, and optionally capture one VLM screenshot in the + OFF state. depth=2, backed by and_enter_lang_tweaks.""" + nodes = and_enter_lang_tweaks() + if nodes is None: + record(record_name, False, + "setup_failed: could not reach Language > Tweaks and more.", + depth=2, jump_kind="transition", + expect=f"{title_text} checked true->false") + return + widget = _pref_checkable_for_title(nodes, title_text, cls="CheckBox") + if widget is None: + record(record_name, False, + f"feature_missing: no CheckBox row '{title_text}' on language tweaks", + depth=2, jump_kind="transition", + expect=f"{title_text} checked true->false") + return + before = widget.get("checked") + _toggle_pref_row(nodes, title_text) + after = _read_checked(None, title_text, cls="CheckBox") + ok = before == "true" and after == "false" + record(record_name, ok, + "" if ok else f"behavior_wrong: '{title_text}' checked {before}->{after} " + f"(expected true->false)", + depth=2, jump_kind="transition", + expect=f"{title_text} checked true->false") + if vlm is not None: + vname, question, tag = vlm + vlm_assert(vname, question, RESULTS_DIR, tag=tag) + _restore_checked(title_text, "true", cls="CheckBox") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 1) Gesture-typing CheckBox — false -> true, with the "BETA Feature!" consequence +# (+ VLM: check-mark rendering) +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_gesture_typing_on", + "states_gesture_typing_on_vlm")) +def test_gesture_typing_checkbox_on(): + nodes = and_enter_gestures() + if nodes is None: + record("states_gesture_typing_on", False, + "setup_failed: could not reach the Gestures tab", + depth=1, jump_kind="transition", + expect="gesture-typing checked false->true; BETA alert appears") + return + start = _read_checked(nodes, GESTURE_TITLE, cls="CheckBox") + if start is None: + record("states_gesture_typing_on", False, + "feature_missing: no 'Enable gesture-typing [BETA]' CheckBox", + depth=1, jump_kind="transition", + expect="gesture-typing checked false->true; BETA alert appears") + return + # Normalize to a known OFF baseline (a prior run may have left it ON). + if start == "true": + _toggle_pref_row(ui(), GESTURE_TITLE) + _dismiss_beta_dialog() + before = _read_checked(None, GESTURE_TITLE, cls="CheckBox") + # Flip OFF -> ON: this is what pops the BETA dialog. + _toggle_pref_row(ui(), GESTURE_TITLE) + beta_shown = _dismiss_beta_dialog() + after = _read_checked(None, GESTURE_TITLE, cls="CheckBox") + # Consequence = the checkbox flipped to true AND the app raised its BETA alert. + ok = before == "false" and after == "true" and beta_shown + record("states_gesture_typing_on", ok, + "" if ok else f"behavior_wrong: gesture-typing checked {before}->{after}, " + f"BETA alert shown={beta_shown} (expected false->true + alert)", + depth=1, jump_kind="transition", + expect="gesture-typing checked false->true; 'BETA Feature!' alert appears") + # VLM: the check mark must now be rendered filled (unreadable from the tree). + vlm_assert("states_gesture_typing_on", + "In the 'Gesture-Typing' section, does the 'Enable gesture-typing " + "[BETA]' checkbox now appear checked (a filled/ticked box) rather " + "than an empty square?", RESULTS_DIR, tag="shape") + _restore_checked(GESTURE_TITLE, "false", cls="CheckBox") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 2) Gesture-typing round-trip — ON then OFF returns to false +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_gesture_typing_roundtrip",)) +def test_gesture_typing_roundtrip(): + nodes = and_enter_gestures() + if nodes is None: + record("states_gesture_typing_roundtrip", False, + "setup_failed: could not reach the Gestures tab", + depth=1, jump_kind="transition", + expect="gesture-typing false->true->false") + return + cur = _read_checked(nodes, GESTURE_TITLE, cls="CheckBox") + if cur is None: + record("states_gesture_typing_roundtrip", False, + "feature_missing: no 'Enable gesture-typing [BETA]' CheckBox", + depth=1, jump_kind="transition", + expect="gesture-typing false->true->false") + return + # Normalize to OFF so the round-trip starts from the documented default. + if cur == "true": + _toggle_pref_row(ui(), GESTURE_TITLE) + _dismiss_beta_dialog() + start = _read_checked(None, GESTURE_TITLE, cls="CheckBox") + _toggle_pref_row(ui(), GESTURE_TITLE) # OFF -> ON (pops BETA alert) + _dismiss_beta_dialog() + mid = _read_checked(None, GESTURE_TITLE, cls="CheckBox") + _toggle_pref_row(ui(), GESTURE_TITLE) # ON -> OFF (no alert) + end = _read_checked(None, GESTURE_TITLE, cls="CheckBox") + ok = start == "false" and mid == "true" and end == "false" + record("states_gesture_typing_roundtrip", ok, + "" if ok else f"behavior_wrong: round-trip {start}->{mid}->{end} " + f"(expected false->true->false)", + depth=1, jump_kind="transition", + expect="gesture-typing false->true->false (round-trip restores off)") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 3) Language tweaks — "Show suggestions" SWITCH true -> false (+ VLM ON & OFF) +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_show_suggestions_switch", + "states_show_suggestions_switch_on_vlm", + "states_show_suggestions_switch_off_vlm")) +def test_show_suggestions_switch(): + nodes = and_enter_lang_tweaks() + if nodes is None: + record("states_show_suggestions_switch", False, + "setup_failed: could not reach Language > Tweaks and more.", + depth=2, jump_kind="transition", + expect="Show suggestions switch true->false") + return + sw = _pref_checkable_for_title(nodes, "Show suggestions", cls="Switch") + if sw is None: + record("states_show_suggestions_switch", False, + "feature_missing: no 'Show suggestions' Switch on language tweaks", + depth=2, jump_kind="transition", + expect="Show suggestions switch true->false") + return + before = sw.get("checked") + # VLM #1: capture the switch in its default ON state (thumb right / colored). + vlm_assert("states_show_suggestions_switch_on", + "Is the 'Show suggestions' toggle switch turned ON — its thumb to " + "the RIGHT with a colored (purple) track?", RESULTS_DIR, tag="color") + _toggle_pref_row(nodes, "Show suggestions") + after = _read_checked(None, "Show suggestions", cls="Switch") + ok = before == "true" and after == "false" + record("states_show_suggestions_switch", ok, + "" if ok else f"behavior_wrong: 'Show suggestions' switch {before}->{after} " + f"(expected true->false)", + depth=2, jump_kind="transition", + expect="Show suggestions switch checked true->false; thumb moves left") + # VLM #2: now OFF (thumb left / grey track). + vlm_assert("states_show_suggestions_switch_off", + "Is the 'Show suggestions' toggle switch turned OFF — its thumb to " + "the LEFT with a grey/uncolored track?", RESULTS_DIR, tag="shape") + _restore_checked("Show suggestions", "true", cls="Switch") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 4-7) Language tweaks — CheckBox toggles true -> false +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_suggestions_restart",)) +def test_suggestions_restart_checkbox(): + _run_lang_tweaks_toggle("states_suggestions_restart", "Suggestions restart") + + +@and_test(expects=("states_space_switches_keyboards", + "states_space_switches_keyboards_vlm")) +def test_space_switches_keyboards_checkbox(): + _run_lang_tweaks_toggle( + "states_space_switches_keyboards", "Space switches keyboards", + vlm=("states_space_switches_keyboards", + "Is the checkbox in the 'Space switches keyboards' row now UNCHECKED " + "(an empty square, no tick)?", "shape")) + + +@and_test(expects=("states_double_space_period",)) +def test_double_space_to_period_checkbox(): + _run_lang_tweaks_toggle("states_double_space_period", "Double space to period") + + +@and_test(expects=("states_remember_layout_per_app",)) +def test_remember_layout_per_app_checkbox(): + _run_lang_tweaks_toggle("states_remember_layout_per_app", + "Remember alphabet layout per App") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 8) UI > Select theme — "Change theme colors based on used app" false -> true +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_theme_app_checkbox", + "states_theme_app_checkbox_vlm")) +def test_theme_app_checkbox(): + nodes = and_enter_theme_selector() + if nodes is None: + record("states_theme_app_checkbox", False, + "setup_failed: could not reach UI > Select theme", + depth=2, jump_kind="transition", + expect="'Change theme colors' checked false->true") + return + # This checkbox is itself the clickable node (has text + clickable="true"), so + # locate it directly by title/id rather than via a row ancestor. + cb = (find_node_ci(nodes, "Change theme colors based on used app") + or node_by_id(nodes, "apply_overlay")) + if cb is None or cb.get("checkable") != "true": + record("states_theme_app_checkbox", False, + "feature_missing: no 'Change theme colors based on used app' CheckBox", + depth=2, jump_kind="transition", + expect="'Change theme colors' checked false->true") + return + before = cb.get("checked") + # Normalize to OFF baseline if a prior run left it ON. + if before == "true": + safe_tap(cb) + cb = (find_node_ci(ui(), "Change theme colors based on used app") + or node_by_id(ui(), "apply_overlay")) + before = cb.get("checked") if cb else None + safe_tap(cb) + fresh = ui() + after_node = (find_node_ci(fresh, "Change theme colors based on used app") + or node_by_id(fresh, "apply_overlay") + or find_closest_match(fresh, cb)) + after = after_node.get("checked") if after_node else None + ok = before == "false" and after == "true" + record("states_theme_app_checkbox", ok, + "" if ok else f"behavior_wrong: 'Change theme colors' checked " + f"{before}->{after} (expected false->true)", + depth=2, jump_kind="transition", + expect="'Change theme colors based on used app' checked false->true") + vlm_assert("states_theme_app_checkbox", + "Does the 'Change theme colors based on used app' checkbox now appear " + "checked (a filled/ticked box) rather than an empty square?", + RESULTS_DIR, tag="shape") + # Restore to default OFF. + restore = (find_node_ci(ui(), "Change theme colors based on used app") + or node_by_id(ui(), "apply_overlay")) + if restore and restore.get("checked") == "true": + safe_tap(restore) + + +# ════════════════════════════════════════════════════════════════════════════════ +# 9) Bottom-nav SELECTED transition — Home -> Language (+ VLM: highlight color) +# Assert BOTH halves of the single-select: new tab selected=true, old=false. +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_nav_select_home_to_language", + "states_nav_select_language_vlm")) +def test_nav_selected_home_to_language(): + home = and_enter_home() + home_sel_before = _tab_selected(home, "Home") + lang_sel_before = _tab_selected(home, "Language") + ok_switch, after = _switch_to_tab(home, "Language") + if not ok_switch: + record("states_nav_select_home_to_language", False, + "setup_failed: could not tap the Language tab", + depth=1, jump_kind="transition", + expect="selected moves Home->Language (Language true, Home false)") + return + lang_sel_after = _tab_selected(after, "Language") + home_sel_after = _tab_selected(after, "Home") + # New tab now selected AND the previously-selected Home cleared — the app-authored + # single-select consequence (Language label also appears on the newly selected). + ok = (home_sel_before and not lang_sel_before + and lang_sel_after and not home_sel_after) + record("states_nav_select_home_to_language", ok, + "" if ok else f"behavior_wrong: selected did not move Home->Language " + f"(Home {home_sel_before}->{home_sel_after}, " + f"Language {lang_sel_before}->{lang_sel_after})", + depth=1, jump_kind="transition", + expect="selected moves Home->Language: Language true & Home false") + vlm_assert("states_nav_select_language", + "In the bottom navigation bar, is the Language (globe) tab " + "highlighted/colored and showing its 'Language' text label, while the " + "other tabs are dark/grey icons with no label?", + RESULTS_DIR, tag="color") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 10) Bottom-nav SELECTED — Home -> UI (single-select invariant across tabs) +# + VLM: UI palette icon turns purple. +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_nav_select_home_to_ui", + "states_nav_select_ui_vlm")) +def test_nav_selected_home_to_ui(): + home = and_enter_home() + home_sel_before = _tab_selected(home, "Home") + ui_sel_before = _tab_selected(home, "UI") + ok_switch, after = _switch_to_tab(home, "UI") + if not ok_switch: + record("states_nav_select_home_to_ui", False, + "setup_failed: could not tap the UI tab", + depth=1, jump_kind="transition", + expect="selected moves Home->UI (UI true, Home false)") + return + ui_sel_after = _tab_selected(after, "UI") + home_sel_after = _tab_selected(after, "Home") + # Single-select invariant: exactly one selected tab across the whole bar. + n_selected = sum(1 for name in TAB_RID if _tab_selected(after, name)) + ok = (home_sel_before and not ui_sel_before + and ui_sel_after and not home_sel_after and n_selected == 1) + record("states_nav_select_home_to_ui", ok, + "" if ok else f"behavior_wrong: single-select broke Home->UI " + f"(Home {home_sel_before}->{home_sel_after}, " + f"UI {ui_sel_before}->{ui_sel_after}, " + f"total selected={n_selected})", + depth=1, jump_kind="transition", + expect="selected moves Home->UI: UI true, Home false, exactly 1 selected") + vlm_assert("states_nav_select_ui", + "In the bottom navigation bar, is the UI (palette) tab icon " + "highlighted in purple/colored and showing a 'UI' text label, while " + "the other tab icons are dark/grey?", RESULTS_DIR, tag="color") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 11) Bottom-nav SELECTED — Language -> Gestures (a second, non-Home pair) +# + VLM: layout — selected tab shows a label under its icon. +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_nav_select_language_to_gestures", + "states_nav_select_label_layout_vlm")) +def test_nav_selected_language_to_gestures(): + home = and_enter_home() + ok_lang, lang_nodes = _switch_to_tab(home, "Language") + if not ok_lang: + record("states_nav_select_language_to_gestures", False, + "setup_failed: could not reach the Language tab", + depth=1, jump_kind="transition", + expect="selected moves Language->Gestures (Gestures true, Language false)") + return + lang_sel_before = _tab_selected(lang_nodes, "Language") + gest_sel_before = _tab_selected(lang_nodes, "Gestures") + gest = _tab_node(lang_nodes, "Gestures") + if not gest or not tap_node(gest): + record("states_nav_select_language_to_gestures", False, + "setup_failed: could not tap the Gestures tab", + depth=1, jump_kind="transition", + expect="selected moves Language->Gestures (Gestures true, Language false)") + return + _dismiss_beta_dialog() + after = ui() + gest_sel_after = _tab_selected(after, "Gestures") + lang_sel_after = _tab_selected(after, "Language") + ok = (lang_sel_before and not gest_sel_before + and gest_sel_after and not lang_sel_after) + record("states_nav_select_language_to_gestures", ok, + "" if ok else f"behavior_wrong: selected did not move Language->Gestures " + f"(Language {lang_sel_before}->{lang_sel_after}, " + f"Gestures {gest_sel_before}->{gest_sel_after})", + depth=1, jump_kind="transition", + expect="selected moves Language->Gestures: Gestures true & Language false") + vlm_assert("states_nav_select_label_layout", + "In the bottom navigation bar, does exactly ONE tab (the Gestures " + "tab) show a text label beneath its icon while every other tab shows " + "only an icon with no label?", RESULTS_DIR, tag="layout") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 12) SETTINGS PERSISTENCE — gesture-typing ON survives a force-stop+relaunch +# (the in-memory-only killer). +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_gesture_typing_persists",)) +def test_gesture_typing_persists(): + nodes = and_enter_gestures() + if nodes is None: + record("states_gesture_typing_persists", False, + "setup_failed: could not reach the Gestures tab", + depth=1, jump_kind="transition", + expect="gesture-typing stays ON after process kill") + return + start = _read_checked(nodes, GESTURE_TITLE, cls="CheckBox") + if start is None: + record("states_gesture_typing_persists", False, + "feature_missing: no 'Enable gesture-typing [BETA]' CheckBox", + depth=1, jump_kind="transition", + expect="gesture-typing stays ON after process kill") + return + if start != "true": + _toggle_pref_row(ui(), GESTURE_TITLE) + _dismiss_beta_dialog() + on_now = _read_checked(None, GESTURE_TITLE, cls="CheckBox") + if on_now != "true": + record("states_gesture_typing_persists", False, + f"behavior_wrong: could not turn gesture-typing ON (got {on_now})", + depth=1, jump_kind="transition", + expect="gesture-typing stays ON after process kill") + _restore_checked(GESTURE_TITLE, "false", cls="CheckBox") + return + # Kill the process and relaunch, then navigate back to Gestures and re-read. + force_stop_and_relaunch() + after_nodes = and_reach_gestures() + if after_nodes is None: + record("states_gesture_typing_persists", False, + "setup_failed: could not re-reach Gestures after relaunch", + depth=1, jump_kind="transition", + expect="gesture-typing stays ON after process kill") + return + after = _read_checked(after_nodes, GESTURE_TITLE, cls="CheckBox") + ok = after == "true" + record("states_gesture_typing_persists", ok, + "" if ok else f"behavior_wrong: gesture-typing not persisted " + f"(after relaunch checked={after}, expected true)", + depth=1, jump_kind="transition", + expect="gesture-typing checked stays true after force-stop+relaunch") + # Restore default OFF. + _restore_checked(GESTURE_TITLE, "false", cls="CheckBox") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 13) SETTINGS PERSISTENCE #2 — a language-tweaks CheckBox OFF survives relaunch +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_double_space_persists",)) +def test_double_space_off_persists(): + title = "Double space to period" + nodes = and_enter_lang_tweaks() + if nodes is None: + record("states_double_space_persists", False, + "setup_failed: could not reach Language > Tweaks and more.", + depth=2, jump_kind="transition", + expect=f"'{title}' stays OFF after process kill") + return + start = _read_checked(nodes, title, cls="CheckBox") + if start is None: + record("states_double_space_persists", False, + f"feature_missing: no CheckBox '{title}' on language tweaks", + depth=2, jump_kind="transition", + expect=f"'{title}' stays OFF after process kill") + return + if start != "false": + _toggle_pref_row(nodes, title) + off_now = _read_checked(None, title, cls="CheckBox") + if off_now != "false": + record("states_double_space_persists", False, + f"behavior_wrong: could not turn '{title}' OFF (got {off_now})", + depth=2, jump_kind="transition", + expect=f"'{title}' stays OFF after process kill") + _restore_checked(title, "true", cls="CheckBox") + return + force_stop_and_relaunch() + after_nodes = and_reach_lang_tweaks() + if after_nodes is None: + record("states_double_space_persists", False, + "setup_failed: could not re-reach language tweaks after relaunch", + depth=2, jump_kind="transition", + expect=f"'{title}' stays OFF after process kill") + return + after = _read_checked(after_nodes, title, cls="CheckBox") + ok = after == "false" + record("states_double_space_persists", ok, + "" if ok else f"behavior_wrong: '{title}' not persisted " + f"(after relaunch checked={after}, expected false)", + depth=2, jump_kind="transition", + expect=f"'{title}' checked stays false after force-stop+relaunch") + # Restore default ON. + _restore_checked(title, "true", cls="CheckBox") + + +TESTS = [ + test_gesture_typing_checkbox_on, + test_gesture_typing_roundtrip, + test_show_suggestions_switch, + test_suggestions_restart_checkbox, + test_space_switches_keyboards_checkbox, + test_double_space_to_period_checkbox, + test_remember_layout_per_app_checkbox, + test_theme_app_checkbox, + test_nav_selected_home_to_language, + test_nav_selected_home_to_ui, + test_nav_selected_language_to_gestures, + test_gesture_typing_persists, + test_double_space_off_persists, +] + +if __name__ == "__main__": + run_suite(TESTS, "states") diff --git a/android/anysoftkeyboard-anysoftkeyboard/tests/test_android_structure.py b/android/anysoftkeyboard-anysoftkeyboard/tests/test_android_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..448f90ad7432fd157695c653de95d3ca000d85f9 --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/tests/test_android_structure.py @@ -0,0 +1,478 @@ +#!/usr/bin/env python3 +"""STRUCTURE test suite for AnySoftKeyboard's settings UI. + +Lane: the launch GATE (top-level surfaces present) + tree-SHAPE deltas (an +interaction changes the view tree's SHAPE — a class of widget appears, a dialog +adds a window layer, a grid subtree grows the node count — reversed to assert it +restores). SHAPE only: content/values/states belong to other lanes. + +Ground truth was read from the running original + recon dumps: + home (mainFragment) : ScrollView cards, demo_keyboard_view, NO Recycler/Grid, + ~59 tree nodes, bottom_navigation with 5 nav items. + gestures : a RecyclerView preference list, ~84 nodes. + emojis : a GridView of category cards, ~114 nodes (nearly 2x home). + swipe-up radio dialog : 15 CheckedTextView rows + CANCEL (new window layer). + About : different fragment tree, bottom_nav still present. + overflow "More options" : popup adds 3 menu items (Backup/Restore/Tweaks). NOTE: + a popup window makes uiautomator dump the popup ALONE, + so the shape signal is item-presence, not total count. + +Every state change re-dumps with ui(). Exploratory taps go through safe_tap. +Dialogs/popups are dismissed with BACK — never by tapping a destructive option. +VLM screenshots are taken while still on the target surface, before reversing. +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +# The 5 bottom-nav tabs, by their stable content-desc (recon table). +NAV_DESCS = ("Hello", "Language", "UI", "Gestures", "Setup Emojis") + + +# ── Shared entry point ────────────────────────────────────────────────────────── +def and_enter_home(): + """Bring the app to its home surface, tolerating the first-run setup wizard. + + On a fresh data state the launch shows the setup wizard first (a node with + resource-id suffix `skip_setup_wizard` / text "Skip"); tap it if present and + re-dump. Returns the home node list (never crosses a surface — home is depth 0). + """ + restart_app() + wait_for_foreground() + nodes = ui() + skip = node_by_id(nodes, "skip_setup_wizard") or find_node_ci(nodes, "Skip") + if skip and is_safe(skip): + tap_node(skip) + nodes = ui() + return nodes + + +def _bottom_nav_items(nodes): + """The nav-item nodes: the FrameLayouts inside bottom_navigation that carry + one of the 5 known tab content-descs.""" + return [n for n in nodes + if n.get("content-desc", "") in NAV_DESCS + and "FrameLayout" in n.get("class", "")] + + +def _tab_node(nodes, desc): + return find_node(nodes, content_desc=desc, clickable="true") + + +def _clickable_row_for(nodes, label_node): + """A preference title is a non-clickable TextView; the tap handler lives on an + ancestor row. Return the smallest clickable node whose bounds fully contain the + label, falling back to the label itself (its centre still lies inside the row).""" + if not label_node or "_bounds" not in label_node: + return label_node + lx1, ly1, lx2, ly2 = label_node["_bounds"] + best, best_area = None, None + for n in nodes: + if n.get("clickable") != "true" or "_bounds" not in n: + continue + x1, y1, x2, y2 = n["_bounds"] + if x1 <= lx1 and y1 <= ly1 and x2 >= lx2 and y2 >= ly2: + area = (x2 - x1) * (y2 - y1) + if best_area is None or area < best_area: + best, best_area = n, area + return best or label_node + + +# ── Depth-backed surface openers (name prefix `and_enter_` backs a depth>=1) ───── +def and_enter_tab(home_nodes, desc): + """Tap a bottom-nav tab and re-dump. Returns (after_nodes, ok). A tab switch + swaps the NavHostFragment content — a real surface — so it counts one.""" + tab = _tab_node(home_nodes, desc) + if not tab or not tap_node(tab): + return home_nodes, False + after = ui() + and_enter(f"tab:{desc}") + return after, True + + +def and_enter_about(home_nodes): + """From home, open the toolbar About screen. Returns (after_nodes, ok). + Counts one surface on a confirmed change so depth=1 is backed by a real + navigation call (and_enter).""" + btn = find_node(home_nodes, content_desc="About") \ + or node_by_id(home_nodes, "about_menu_option") + if not btn or not safe_tap(btn): + return home_nodes, False + after = ui() + if node_by_id(after, "about_app_version") is None \ + and find_node_ci(after, "Additional Software Licenses") is None: + return after, False + and_enter("About") + return after, True + + +def and_enter_swipe_dialog(gestures_nodes): + """From the Gestures tab, open the 'Swipe up' list-preference radio dialog. + Returns (dialog_nodes, ok). Taps the clickable preference row (the title + TextView itself is not clickable). Counts one surface on a confirmed dialog so + the depth=1 claim is backed.""" + label = find_node_ci(gestures_nodes, "Swipe up") + if not label: + return gestures_nodes, False + row = _clickable_row_for(gestures_nodes, label) + if not is_safe(row) or not tap_node(row): + return gestures_nodes, False + settle("tap") + dlg = ui() + opened = bool(find_node_ci(dlg, "Select swipe up action") + or len(find_by_class(dlg, "CheckedTextView")) >= 8) + if not opened: + return dlg, False + and_enter("swipe_up_dialog") + return dlg, True + + +# ════════════════════════════════════════════════════════════════════════════════ +# GATE (existence) — kept to 2 records (<= 30% of the suite) +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_gate_bottom_nav",)) +def test_gate_bottom_nav(): + """GATE: app reaches home with the bottom_navigation host AND its 5 known + nav-item tabs (by class + content-desc, not internal id).""" + nodes = and_enter_home() + fg = wait_for_foreground() + nav = node_by_id(nodes, "bottom_navigation") + items = _bottom_nav_items(nodes) + descs = {n.get("content-desc", "") for n in items} + ok = bool(fg) and nav is not None and len(items) == 5 and descs == set(NAV_DESCS) + if not fg: + msg = "setup_failed: app did not reach the foreground" + elif nav is None: + msg = "feature_missing: bottom_navigation host not present on home" + elif descs != set(NAV_DESCS): + msg = (f"behavior_wrong: bottom-nav tabs {sorted(descs)} != " + f"expected {sorted(NAV_DESCS)}") + else: + msg = "" + record("structure_gate_bottom_nav", ok, msg, depth=0, jump_kind="none") + + +@and_test(expects=("structure_gate_demo_keyboard", "structure_gate_demo_keyboard_vlm")) +def test_gate_demo_keyboard(): + """GATE: home hosts the keyboard-preview surface (demo_keyboard_view), a + canvas View that anchors the home layout.""" + nodes = and_enter_home() + preview = node_by_id(nodes, "demo_keyboard_view") + ok = preview is not None + record("structure_gate_demo_keyboard", ok, + "" if ok else "feature_missing: demo_keyboard_view preview absent on home", + depth=0, jump_kind="none") + vlm_assert("structure_gate_demo_keyboard", + "Is a keyboard (multiple rows of letter keys q w e r t y ...) shown " + "in the upper part of the screen?", + RESULTS_DIR, depth=0, jump_kind="none", tag="shape") + + +# ════════════════════════════════════════════════════════════════════════════════ +# SHAPE deltas (jump_kind="transition", with a real before/after) +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_gestures_shape", "structure_gestures_shape_vlm")) +def test_gestures_changes_shape(): + """SHAPE: Home is a ScrollView of cards with NO list/grid; the Gestures tab is + a RecyclerView preference list. Tapping Gestures adds a RecyclerView subtree + and materially changes the surface key-set; returning Home restores it.""" + home = and_enter_home() + before = and_showing(home) + home_lists = len(find_by_class(home, "RecyclerView")) + + gest, ok_tab = and_enter_tab(home, "Gestures") + after = and_showing(gest) + gest_lists = len(find_by_class(gest, "RecyclerView")) + changed = surface_changed(before, after, min_delta=5) + list_appeared = gest_lists >= 1 and home_lists == 0 + + # VLM while still on the Gestures surface (before reversing). + vlm_assert("structure_gestures_shape", + "Is the screen a vertically-stacked list of settings rows, each with " + "a title and a smaller grey description line, and NOT a grid of " + "picture cards?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="layout") + + # Reverse: back to Home restores the no-list shape. + home2 = and_enter_home() + restored = len(find_by_class(home2, "RecyclerView")) == 0 \ + and node_by_id(home2, "demo_keyboard_view") is not None + + ok = ok_tab and changed and list_appeared and restored + if not ok_tab: + msg = "setup_failed: Gestures tab not tappable" + elif not list_appeared: + msg = (f"behavior_wrong: RecyclerView count home={home_lists} " + f"gestures={gest_lists} (expected 0 -> >=1)") + elif not changed: + msg = "behavior_wrong: surface key-set unchanged Home->Gestures" + elif not restored: + msg = "behavior_wrong: Home shape not restored after leaving Gestures" + else: + msg = "" + record("structure_gestures_shape", ok, msg, depth=0, jump_kind="transition", + expect="Home(no list)->Gestures adds a RecyclerView subtree " + "(surface key-set changes >=5 keys); restored on return to Home") + + +@and_test(expects=("structure_emojis_shape", "structure_emojis_shape_vlm")) +def test_emojis_grows_tree(): + """SHAPE: the Emojis tab renders a GridView of category cards, so its tree is + materially larger than home's (~114 vs ~59 nodes) and adds a GridView subtree. + Returning Home shrinks it back.""" + home = and_enter_home() + home_n = len(home) + home_grids = len(find_by_class(home, "GridView")) + + emj, ok_tab = and_enter_tab(home, "Setup Emojis") + emj_n = len(emj) + emj_grids = len(find_by_class(emj, "GridView")) + grew = emj_n >= home_n + 20 # observed delta ~55; 20 is a safe floor + grid_appeared = emj_grids >= 1 and home_grids == 0 + + # VLM while still on the Emojis surface (before reversing). + vlm_assert("structure_emojis_shape", + "Does the screen show a grid of multiple picture cards arranged in " + "two columns and several rows?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="layout") + + # Reverse: Home has no GridView and a smaller tree again. + home2 = and_enter_home() + restored = len(find_by_class(home2, "GridView")) == 0 and len(home2) <= home_n + 10 + + ok = ok_tab and grew and grid_appeared and restored + if not ok_tab: + msg = "setup_failed: Emojis tab not tappable" + elif not grid_appeared: + msg = (f"behavior_wrong: GridView count home={home_grids} " + f"emojis={emj_grids} (expected 0 -> >=1)") + elif not grew: + msg = (f"behavior_wrong: node count did not grow materially " + f"home={home_n} emojis={emj_n} (expected +>=20)") + elif not restored: + msg = "behavior_wrong: Home tree not restored after leaving Emojis" + else: + msg = "" + record("structure_emojis_shape", ok, msg, depth=0, jump_kind="transition", + expect="Emojis adds a GridView subtree; tree grows by >=20 nodes vs Home; " + "restored on return to Home") + + +@and_test(expects=("structure_swipe_dialog_shape", "structure_swipe_dialog_shape_vlm")) +def test_swipe_dialog_adds_subtree(): + """SHAPE: opening the 'Swipe up' list-preference on Gestures ADDS a new dialog + window layer whose subtree contains a set of radio rows (CheckedTextView). + depth=1 is backed by and_enter_swipe_dialog(); dismissed with BACK (never by + selecting a destructive option), and the dialog subtree is asserted removed.""" + home = and_enter_home() + gest, ok_tab = and_enter_tab(home, "Gestures") + before_rows = len(find_by_class(gest, "CheckedTextView")) + before = and_showing(gest) + + dlg, ok_dlg = and_enter_swipe_dialog(gest) + dlg_rows = len(find_by_class(dlg, "CheckedTextView")) + after = and_showing(dlg) + added = ok_dlg and before_rows == 0 and dlg_rows >= 8 + changed = surface_changed(before, after, min_delta=5) + + # VLM while the dialog is open (before dismissing). + vlm_assert("structure_swipe_dialog_shape", + "Is a dialog open showing a vertical list of options, each with a " + "round radio-button circle on its left side?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="layout") + + # Reverse: BACK dismisses the dialog; the radio subtree disappears. + and_back() + gest2 = ui() + removed = len(find_by_class(gest2, "CheckedTextView")) == 0 \ + and find_node_ci(gest2, "Swipe up") is not None + + ok = ok_tab and added and changed and removed + if not ok_tab: + msg = "setup_failed: Gestures tab not tappable" + elif not ok_dlg: + msg = "feature_missing: 'Swipe up' radio dialog did not open" + elif not added: + msg = (f"behavior_wrong: radio rows before={before_rows} " + f"dialog={dlg_rows} (expected 0 -> >=8)") + elif not removed: + msg = "behavior_wrong: dialog subtree not removed after BACK" + else: + msg = "" + record("structure_swipe_dialog_shape", ok, msg, depth=1, jump_kind="transition", + expect="'Swipe up' adds a dialog layer with >=8 CheckedTextView radio " + "rows (0 -> >=8); removed on BACK, Gestures list restored") + + +@and_test(expects=("structure_about_shape", "structure_about_shape_vlm")) +def test_about_differs_from_home(): + """SHAPE: the toolbar About screen is a different fragment tree than home — + the home cards (demo_keyboard_view, changelog card) are gone and About's + link rows appear — while the bottom_navigation host stays. depth=1 backed by + and_enter_about(); BACK restores home.""" + home = and_enter_home() + before = and_showing(home) + home_had_changelog = node_by_id(home, "latest_change_log_card") is not None + + about, ok_open = and_enter_about(home) + after = and_showing(about) + changed = surface_changed(before, after, min_delta=5) + # About-specific subtree present, home-specific subtree gone, nav host kept. + about_markers = node_by_id(about, "about_app_version") is not None \ + or find_node_ci(about, "Additional Software Licenses") is not None + home_gone = node_by_id(about, "latest_change_log_card") is None + nav_kept = node_by_id(about, "bottom_navigation") is not None + + # VLM while still on the About surface (before reversing). + vlm_assert("structure_about_shape", + "Is there a purple app-bar / header strip spanning the full width " + "across the very top of the screen?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="layout") + + # Reverse: BACK returns to home shape. + and_back() + home2 = ui() + restored = node_by_id(home2, "demo_keyboard_view") is not None + + ok = (ok_open and changed and about_markers and home_gone and nav_kept + and home_had_changelog and restored) + if not ok_open: + msg = "setup_failed: About affordance not found/opened" + elif not about_markers: + msg = "feature_missing: About screen markers (version/licenses) absent" + elif not (changed and home_gone): + msg = "behavior_wrong: tree shape did not change from Home to About" + elif not nav_kept: + msg = "behavior_wrong: bottom_navigation host missing on About" + elif not restored: + msg = "behavior_wrong: Home shape not restored after BACK from About" + else: + msg = "" + record("structure_about_shape", ok, msg, depth=1, jump_kind="transition", + expect="About swaps the home fragment (changelog card gone, About " + "version/licenses appear; surface changes >=5 keys) but keeps " + "bottom_navigation; restored on BACK") + + +@and_test(expects=("structure_overflow_menu_shape", + "structure_overflow_menu_shape_vlm")) +def test_overflow_menu_adds_items(): + """SHAPE: the toolbar overflow 'More options' opens a popup that ADDS a menu + subtree (Backup / Restore / Tweaks). A popup window makes uiautomator dump the + popup ALONE, so the honest shape signal is item-presence: none of the three are + on home, all three appear in the popup, and all vanish after BACK. depth=0 (a + popup, not a fragment surface). Backup/Restore are never tapped (they write + files).""" + home = and_enter_home() + home_had_items = any(find_node_ci(home, t) is not None + for t in ("Backup", "Restore", "Tweaks")) + overflow = find_node(home, content_desc="More options") + ok_open = overflow is not None and safe_tap(overflow) + + popup = ui() if ok_open else home + tweaks = find_node_ci(popup, "Tweaks") + backup = find_node_ci(popup, "Backup") + restore = find_node_ci(popup, "Restore") + n_items = sum(x is not None for x in (tweaks, backup, restore)) + added = ok_open and (not home_had_items) and n_items == 3 + + # VLM while the popup is open (before dismissing). + vlm_assert("structure_overflow_menu_shape", + "Is a small dropdown / pop-up menu of stacked text options open near " + "the top-right area of the screen?", + RESULTS_DIR, depth=0, jump_kind="transition", tag="layout") + + # Reverse: BACK closes the popup; the 3 items disappear. + back() + home2 = ui() + removed = find_node_ci(home2, "Backup") is None \ + and find_node_ci(home2, "Restore") is None + + ok = added and removed + if not ok_open: + msg = "setup_failed: overflow 'More options' affordance not found" + elif home_had_items: + msg = "behavior_wrong: Backup/Restore/Tweaks already present before opening" + elif n_items != 3: + msg = (f"behavior_wrong: overflow popup exposed {n_items}/3 of " + f"Backup/Restore/Tweaks") + elif not removed: + msg = "behavior_wrong: overflow items not removed after BACK" + else: + msg = "" + record("structure_overflow_menu_shape", ok, msg, depth=0, jump_kind="transition", + expect="overflow popup adds a menu subtree with exactly 3 items " + "(Backup/Restore/Tweaks, absent on home -> present); removed on BACK") + + +@and_test(expects=("structure_theme_grid_shape", "structure_theme_grid_shape_vlm")) +def test_theme_selector_grid(): + """SHAPE: from the UI tab, 'Pick and configure keyboard themes.' opens a + Select-theme surface that adds a grid of theme preview cards, a different tree + shape than the UI tab list. depth=2 backed by two and_enter_* calls (tab, then + the theme surface); BACK restores the UI tab. Card grid is the shape signal.""" + home = and_enter_home() + ui_nodes, ok_tab = and_enter_tab(home, "UI") + before = and_showing(ui_nodes) + + label = find_node_ci(ui_nodes, "Pick and configure keyboard themes.") + row = _clickable_row_for(ui_nodes, label) if label else None + ok_open = row is not None and safe_tap(row) + theme = ui() if ok_open else ui_nodes + on_theme = find_node_ci(theme, "Select theme") is not None \ + or find_node_ci(theme, "Change theme colors based on used app") is not None + if ok_open and on_theme: + and_enter("select_theme") + after = and_showing(theme) + changed = surface_changed(before, after, min_delta=5) + # The theme surface stacks multiple preview cards (each with its own demo + # keyboard sub-view) — a materially bigger tree than the 3-row UI list. + grew = len(theme) >= len(ui_nodes) + 10 + + # VLM while still on the Select-theme surface (before reversing). + vlm_assert("structure_theme_grid_shape", + "Below a large keyboard preview, are there several smaller keyboard " + "theme preview cards laid out in a two-column grid?", + RESULTS_DIR, depth=2, jump_kind="transition", tag="layout") + + # Reverse: BACK to the UI tab. + and_back() + ui2 = ui() + back_ok = find_node_ci(ui2, "Pick and configure keyboard themes.") is not None + + ok = ok_tab and ok_open and on_theme and changed and grew and back_ok + if not ok_tab: + msg = "setup_failed: UI tab not tappable" + elif not ok_open: + msg = "feature_missing: 'Pick and configure keyboard themes.' row absent" + elif not on_theme: + msg = "behavior_wrong: Select-theme surface markers absent after tap" + elif not (changed and grew): + msg = (f"behavior_wrong: theme surface not a bigger/different tree " + f"(ui={len(ui_nodes)} theme={len(theme)})") + elif not back_ok: + msg = "behavior_wrong: UI tab not restored after BACK from theme surface" + else: + msg = "" + record("structure_theme_grid_shape", ok, msg, depth=2, jump_kind="transition", + expect="UI list -> Select-theme adds a grid of keyboard preview cards " + "(tree grows >=10 nodes, surface changes >=5 keys); restored on BACK") + + +TESTS = [ + test_gate_bottom_nav, + test_gate_demo_keyboard, + test_gestures_changes_shape, + test_emojis_grows_tree, + test_swipe_dialog_adds_subtree, + test_about_differs_from_home, + test_overflow_menu_adds_items, + test_theme_selector_grid, +] + +if __name__ == "__main__": + run_suite(TESTS, "structure") diff --git a/android/anysoftkeyboard-anysoftkeyboard/tests/test_android_text.py b/android/anysoftkeyboard-anysoftkeyboard/tests/test_android_text.py new file mode 100644 index 0000000000000000000000000000000000000000..13bbb1e3fde80fc2121044a43b284913ffb53bde --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/tests/test_android_text.py @@ -0,0 +1,601 @@ +#!/usr/bin/env python3 +"""TEXT lane for AnySoftKeyboard settings UI. + +This lane owns exact-string equality for CONTENT that an interaction PRODUCES: +the toolbar title that changes when you switch tabs, the strings the About +screen reveals, the changelog title, gesture-summary strings, the radio-dialog +title and its option labels, and the not-fully-set-up / testing-build cards. + +Every test performs a TRIGGER (navigate to a tab / open About / open a dialog), +then re-dumps and asserts a SPECIFIC content string that appeared as a +consequence — matched by a whitespace/case tolerant substring so a faithful +recreation may differ in punctuation but not in words. + +Three VLM records only: the keyboard-preview is a canvas-drawn custom View whose +glyphs never reach the view tree, so its letters are the one legitimately opaque +text core here. +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ── text helpers ──────────────────────────────────────────────────────────── +def all_text(nodes): + """All non-empty visible text joined, for a tolerant 'contains' check.""" + return " | ".join(n.get("text", "") for n in nodes if n.get("text")) + + +def norm(s): + return " ".join((s or "").split()).strip().casefold() + + +def has_text(nodes, needle): + """Case/whitespace-tolerant substring search across every text node.""" + return norm(needle) in norm(all_text(nodes)) + + +def toolbar_title(nodes): + """The action-bar title string. + + The toolbar title is a TextView with an EMPTY resource-id pinned to the top + strip (x1 ~= 42, y1 in the status-bar+toolbar band). The same words also + appear as a bottom-nav label near y ~= 2298, so we must exclude that: we take + the top-most qualifying TextView, and only from the toolbar band. + """ + s = get_screen_info() + band = max(300, int(s["height"] * 0.16)) # ~[status bar .. below toolbar] + best = None + for n in nodes: + if "TextView" not in n.get("class", ""): + continue + txt = n.get("text", "").strip() + if not txt: + continue + b = n.get("_bounds") + if not b: + continue + x1, y1, _x2, _y2 = b + if y1 > band or x1 > int(s["width"] * 0.5): + continue + if best is None or y1 < best[0]: + best = (y1, txt) + return best[1] if best else "" + + +# ── first-run + navigation helpers (back a declared depth>=1) ──────────────── +def and_enter_home(): + """Launch fresh, skip the setup wizard if it shows, return the home dump.""" + restart_app() + wait_for_foreground() + nodes = ui() + skip = node_by_id(nodes, "skip_setup_wizard") or find_node_ci(nodes, "Skip") + if skip: + tap_node(skip) + settle("tap") + nodes = ui() + return nodes + + +def and_enter_tab(desc): + """Tap a bottom-nav tab by content-desc; count one surface. Returns dump.""" + nodes = and_enter_home() + tab = find_node(nodes, content_desc=desc) + if not tab: + return None + tap_node(tab) + settle("tap") + and_enter(desc) + return ui() + + +def and_enter_about(): + """Open the toolbar About screen; count one surface. Returns dump.""" + nodes = and_enter_home() + opt = node_by_id(nodes, "about_menu_option") or find_node(nodes, content_desc="About") + if not opt: + return None + tap_node(opt) + settle("tap") + and_enter("About") + return ui() + + +def and_enter_gestures(): + """Reach the Gestures tab; count one surface. Returns dump.""" + return and_enter_tab("Gestures") + + +def _clickable_row_for(nodes, text): + """The clickable container whose bounds enclose the center of `text`.""" + label = find_node(nodes, text=text) or find_node_ci(nodes, text) + if not label or "_center" not in label: + return None + cx, cy = label["_center"] + best, best_area = None, None + for n in nodes: + if n.get("clickable") != "true": + continue + b = n.get("_bounds") + if not b: + continue + x1, y1, x2, y2 = b + if x1 <= cx <= x2 and y1 <= cy <= y2: + area = (x2 - x1) * (y2 - y1) + if best_area is None or area < best_area: + best, best_area = n, area + return best or label + + +def and_enter_swipe_up_dialog(): + """From Gestures, open the 'Swipe up' radio dialog; count one surface.""" + if and_enter_gestures() is None: + return None + row = scroll_into_view("Swipe up") + if row is None: + return None + nodes = ui() + target = _clickable_row_for(nodes, "Swipe up") + tap_node(target) + settle("tap") + and_enter("Select swipe up action") + return ui() + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1. Toolbar title per tab — dynamic string produced by switching tabs +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_title_home",)) +def test_title_home(): + nodes = and_enter_tab("Hello") + if nodes is None: + record("text_title_home", False, + "setup_failed: could not reach the Home tab", + depth=1, jump_kind="value", expect="toolbar title 'Welcome to AnySoftKeyboard'") + return + title = toolbar_title(nodes) + ok = norm("Welcome to AnySoftKeyboard") in norm(title) + record("text_title_home", ok, + "" if ok else f"behavior_wrong: Home toolbar title was {title!r}, " + f"expected 'Welcome to AnySoftKeyboard'", + depth=1, jump_kind="value", + expect="toolbar title 'Welcome to AnySoftKeyboard'") + + +@and_test(expects=("text_title_language",)) +def test_title_language(): + # source: Home title 'Welcome to AnySoftKeyboard' must be gone after switching. + home = and_enter_home() + src_present = norm("Welcome to AnySoftKeyboard") in norm(toolbar_title(home)) + tab = find_node(home, content_desc="Language") + if not tab: + record("text_title_language", False, + "setup_failed: Language tab not found on the bottom nav", + depth=1, jump_kind="value", expect="toolbar title 'Language'") + return + tap_node(tab) + settle("tap") + and_enter("Language") + nodes = ui() + title = toolbar_title(nodes) + src_gone = norm("Welcome to AnySoftKeyboard") not in norm(title) + ok = (norm(title) == norm("Language")) and src_present and src_gone + record("text_title_language", ok, + "" if ok else f"behavior_wrong: Language toolbar title was {title!r}, " + f"expected 'Language' (src_present={src_present}, src_gone={src_gone})", + depth=1, jump_kind="value", expect="toolbar title 'Language'") + + +@and_test(expects=("text_title_ui",)) +def test_title_ui(): + home = and_enter_home() + src_present = norm("Welcome to AnySoftKeyboard") in norm(toolbar_title(home)) + tab = find_node(home, content_desc="UI") + if not tab: + record("text_title_ui", False, + "setup_failed: UI tab not found on the bottom nav", + depth=1, jump_kind="value", expect="toolbar title 'UI'") + return + tap_node(tab) + settle("tap") + and_enter("UI") + nodes = ui() + title = toolbar_title(nodes) + src_gone = norm("Welcome to AnySoftKeyboard") not in norm(title) + ok = (norm(title) == norm("UI")) and src_present and src_gone + record("text_title_ui", ok, + "" if ok else f"behavior_wrong: UI toolbar title was {title!r}, expected 'UI'", + depth=1, jump_kind="value", expect="toolbar title 'UI'") + + +@and_test(expects=("text_title_gestures",)) +def test_title_gestures(): + home = and_enter_home() + src_present = norm("Welcome to AnySoftKeyboard") in norm(toolbar_title(home)) + tab = find_node(home, content_desc="Gestures") + if not tab: + record("text_title_gestures", False, + "setup_failed: Gestures tab not found on the bottom nav", + depth=1, jump_kind="value", expect="toolbar title 'Gestures'") + return + tap_node(tab) + settle("tap") + and_enter("Gestures") + nodes = ui() + title = toolbar_title(nodes) + src_gone = norm("Welcome to AnySoftKeyboard") not in norm(title) + ok = (norm(title) == norm("Gestures")) and src_present and src_gone + record("text_title_gestures", ok, + "" if ok else f"behavior_wrong: Gestures toolbar title was {title!r}, " + f"expected 'Gestures'", + depth=1, jump_kind="value", expect="toolbar title 'Gestures'") + + +@and_test(expects=("text_title_emojis",)) +def test_title_emojis(): + home = and_enter_home() + src_present = norm("Welcome to AnySoftKeyboard") in norm(toolbar_title(home)) + tab = find_node(home, content_desc="Setup Emojis") + if not tab: + record("text_title_emojis", False, + "setup_failed: Emojis tab (desc 'Setup Emojis') not found on the bottom nav", + depth=1, jump_kind="value", + expect="toolbar title 'Quick Text groups and order'") + return + tap_node(tab) + settle("tap") + and_enter("Quick Text groups and order") + nodes = ui() + title = toolbar_title(nodes) + src_gone = norm("Welcome to AnySoftKeyboard") not in norm(title) + ok = (norm("Quick Text groups and order") in norm(title)) and src_present and src_gone + record("text_title_emojis", ok, + "" if ok else f"behavior_wrong: Emojis toolbar title was {title!r}, " + f"expected 'Quick Text groups and order'", + depth=1, jump_kind="value", + expect="toolbar title 'Quick Text groups and order'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2. About screen — strings produced by opening About +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_about_heading",)) +def test_about_heading(): + nodes = and_enter_about() + if nodes is None: + record("text_about_heading", False, + "setup_failed: could not open the About screen", + depth=1, jump_kind="value", expect="'AnySoftKeyboard Dev' heading on About") + return + src_gone = norm("Welcome to AnySoftKeyboard") not in norm(all_text(nodes)) + ok = has_text(nodes, "AnySoftKeyboard Dev") and src_gone + record("text_about_heading", ok, + "" if ok else "behavior_wrong: About did not show 'AnySoftKeyboard Dev' " + "(or Home title still present)", + depth=1, jump_kind="value", expect="'AnySoftKeyboard Dev' heading on About") + + +@and_test(expects=("text_about_version",)) +def test_about_version(): + nodes = and_enter_about() + if nodes is None: + record("text_about_version", False, + "setup_failed: could not open the About screen", + depth=1, jump_kind="value", expect="'Version 1.13.1' on About") + return + # Read the live version line; assert the version substring it renders. + ok = has_text(nodes, "Version 1.13.1") + record("text_about_version", ok, + "" if ok else "behavior_wrong: About did not render 'Version 1.13.1'", + depth=1, jump_kind="value", expect="'Version 1.13.1' on About") + + +@and_test(expects=("text_about_copyright",)) +def test_about_copyright(): + nodes = and_enter_about() + if nodes is None: + record("text_about_copyright", False, + "setup_failed: could not open the About screen", + depth=1, jump_kind="value", + expect="copyright line with 'Menny Even-Danan'") + return + # Year is not asserted (a recreation cannot know it); the © mark + author are. + ok = has_text(nodes, "Copyright ©") and has_text(nodes, "Menny Even-Danan") + record("text_about_copyright", ok, + "" if ok else "behavior_wrong: About did not show 'Copyright ©' + " + "'Menny Even-Danan'", + depth=1, jump_kind="value", expect="copyright line with 'Menny Even-Danan'") + + +@and_test(expects=("text_about_licenses_link",)) +def test_about_licenses_link(): + nodes = and_enter_about() + if nodes is None: + record("text_about_licenses_link", False, + "setup_failed: could not open the About screen", + depth=1, jump_kind="value", expect="'Additional Software Licenses' link") + return + ok = has_text(nodes, "Additional Software Licenses") + record("text_about_licenses_link", ok, + "" if ok else "behavior_wrong: About missing 'Additional Software Licenses' link", + depth=1, jump_kind="value", expect="'Additional Software Licenses' link") + + +@and_test(expects=("text_about_privacy_link",)) +def test_about_privacy_link(): + nodes = and_enter_about() + if nodes is None: + record("text_about_privacy_link", False, + "setup_failed: could not open the About screen", + depth=1, jump_kind="value", expect="'Privacy Policy' link on About") + return + # Tolerant on the trailing ellipsis: match the meaningful words only. + ok = has_text(nodes, "Privacy Policy") + record("text_about_privacy_link", ok, + "" if ok else "behavior_wrong: About missing the 'Privacy Policy' link", + depth=1, jump_kind="value", expect="'Privacy Policy' link on About") + + +@and_test(expects=("text_about_website_link",)) +def test_about_website_link(): + nodes = and_enter_about() + if nodes is None: + record("text_about_website_link", False, + "setup_failed: could not open the About screen", + depth=1, jump_kind="value", expect="'web-site' link on About") + return + ok = has_text(nodes, "web-site") or has_text(nodes, "web site") or has_text(nodes, "website") + record("text_about_website_link", ok, + "" if ok else "behavior_wrong: About missing the 'Visit our web-site' link", + depth=1, jump_kind="value", expect="'Visit our web-site' link on About") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3. Changelog title + a known bullet (Home content) — kept as existence (<=2) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_changelog_title",)) +def test_changelog_title(): + nodes = and_enter_home() + if not nodes: + record("text_changelog_title", False, + "setup_failed: home surface never loaded", + depth=0, jump_kind="none", expect="'Latest changes for v1.13' on Home") + return + ok = has_text(nodes, "Latest changes for v1.13") + record("text_changelog_title", ok, + "" if ok else "feature_missing: Home did not show the changelog title " + "'Latest changes for v1.13'", + depth=0, jump_kind="none", expect="'Latest changes for v1.13' on Home") + + +@and_test(expects=("text_changelog_bullet",)) +def test_changelog_bullet(): + nodes = and_enter_home() + if not nodes: + record("text_changelog_bullet", False, + "setup_failed: home surface never loaded", + depth=0, jump_kind="none", expect="changelog bullet 'Improved gesture-typing'") + return + ok = has_text(nodes, "Improved gesture-typing") + record("text_changelog_bullet", ok, + "" if ok else "feature_missing: Home changelog missing the " + "'Improved gesture-typing' bullet", + depth=0, jump_kind="none", expect="changelog bullet 'Improved gesture-typing'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4. "Not fully set-up" card — a produced state string (IME not enabled) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_not_setup_card",)) +def test_not_setup_card(): + home = and_enter_home() + # source: this card is reached from the same home surface it lives on; we frame + # it as a value assertion of the card's produced wording. + if not home: + record("text_not_setup_card", False, + "setup_failed: home surface never loaded", + depth=0, jump_kind="value", expect="'not fully set-up for use' card") + return + ok = has_text(home, "not fully set-up for use") and has_text(home, "Click here") + record("text_not_setup_card", ok, + "" if ok else "behavior_wrong: Home missing the 'not fully set-up for use / " + "Click here' card", + depth=0, jump_kind="value", expect="'not fully set-up for use' + 'Click here'") + + +@and_test(expects=("text_testing_build_card",)) +def test_testing_build_card(): + home = and_enter_home() + if not home: + record("text_testing_build_card", False, + "setup_failed: home surface never loaded", + depth=0, jump_kind="value", expect="'This is a testing build' card") + return + ok = has_text(home, "This is a testing build") + record("text_testing_build_card", ok, + "" if ok else "behavior_wrong: Home missing the 'This is a testing build' card", + depth=0, jump_kind="value", expect="'This is a testing build' card") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5. Gesture summary strings (Gestures tab) — dynamic default summaries +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_gesture_swipe_up_summary",)) +def test_gesture_swipe_up_summary(): + nodes = and_enter_gestures() + if nodes is None: + record("text_gesture_swipe_up_summary", False, + "setup_failed: could not reach the Gestures tab", + depth=1, jump_kind="value", expect="swipe-up summary 'Currently, Shift'") + return + # source: Home title gone once we are on Gestures. + src_gone = norm("Welcome to AnySoftKeyboard") not in norm(all_text(nodes)) + found = has_text(nodes, "Currently, Shift") + if not found: # summary may be below the fold + row = scroll_into_view("Swipe up") + if row: + found = has_text(ui(), "Currently, Shift") + ok = found and src_gone + record("text_gesture_swipe_up_summary", ok, + "" if ok else "behavior_wrong: Gestures 'Swipe up' summary is not " + "'Currently, Shift'", + depth=1, jump_kind="value", expect="swipe-up summary 'Currently, Shift'") + + +@and_test(expects=("text_gesture_swipe_down_summary",)) +def test_gesture_swipe_down_summary(): + nodes = and_enter_gestures() + if nodes is None: + record("text_gesture_swipe_down_summary", False, + "setup_failed: could not reach the Gestures tab", + depth=1, jump_kind="value", expect="swipe-down summary 'Currently, Hide keyboard'") + return + found = has_text(nodes, "Currently, Hide keyboard") + if not found: + row = scroll_into_view("Swipe down") + if row: + found = has_text(ui(), "Currently, Hide keyboard") + record("text_gesture_swipe_down_summary", found, + "" if found else "behavior_wrong: Gestures 'Swipe down' summary is not " + "'Currently, Hide keyboard'", + depth=1, jump_kind="value", + expect="swipe-down summary 'Currently, Hide keyboard'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 6/7. Swipe-up radio dialog — title + option labels (dismiss with BACK) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_dialog_title",)) +def test_dialog_title(): + before = None + g = and_enter_gestures() + if g is not None: + before = all_text(g) + nodes = and_enter_swipe_up_dialog() + try: + if nodes is None: + record("text_dialog_title", False, + "setup_failed: could not open the swipe-up dialog", + depth=1, jump_kind="value", expect="dialog title 'Select swipe up action'") + return + # source: the "Swipe up" ROW summary line is a Gestures-surface element that + # the modal dialog covers; title is the target that appeared. + title_ok = has_text(nodes, "Select swipe up action") + record("text_dialog_title", title_ok, + "" if title_ok else "behavior_wrong: swipe-up dialog title is not " + "'Select swipe up action'", + depth=1, jump_kind="value", expect="dialog title 'Select swipe up action'") + finally: + back() # dismiss the dialog without touching any option + settle("tap") + + +@and_test(expects=("text_dialog_options",)) +def test_dialog_options(): + nodes = and_enter_swipe_up_dialog() + try: + if nodes is None: + record("text_dialog_options", False, + "setup_failed: could not open the swipe-up dialog", + depth=1, jump_kind="value", + expect="options 'Hide keyboard' and 'Move cursor left'") + return + # Assert two SAFE option labels are listed (never tap 'Clear entire text'). + ok = has_text(nodes, "Hide keyboard") and has_text(nodes, "Move cursor left") + record("text_dialog_options", ok, + "" if ok else "behavior_wrong: swipe-up dialog missing option labels " + "'Hide keyboard' / 'Move cursor left'", + depth=1, jump_kind="value", + expect="options 'Hide keyboard' and 'Move cursor left'") + finally: + back() + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# VLM (exactly 3) — keyboard-preview CANVAS glyphs, unreadable from the view tree +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_preview_qwerty_vlm",)) +def test_preview_qwerty_vlm(): + nodes = and_enter_home() + preview = node_by_id(nodes, "demo_keyboard_view") + if not preview: + record("text_preview_qwerty_vlm", False, + "setup_failed: no demo_keyboard_view on Home", + depth=0, jump_kind="none", tag="content") + return + vlm_assert("text_preview_qwerty", + "Does the on-screen keyboard preview display letter keys with the " + "letters q w e r t y visible along its top row?", + RESULTS_DIR, tag="content") + + +@and_test(expects=("text_preview_spacebar_vlm",)) +def test_preview_spacebar_vlm(): + nodes = and_enter_home() + preview = node_by_id(nodes, "demo_keyboard_view") + if not preview: + record("text_preview_spacebar_vlm", False, + "setup_failed: no demo_keyboard_view on Home", + depth=0, jump_kind="none", tag="content") + return + vlm_assert("text_preview_spacebar", + "In the keyboard preview, does the wide space bar in the bottom row " + "show the word 'English'?", + RESULTS_DIR, tag="content") + + +@and_test(expects=("text_preview_lowercase_vlm",)) +def test_preview_lowercase_vlm(): + nodes = and_enter_tab("UI") + if nodes is None: + nodes = and_enter_home() + preview = node_by_id(nodes, "demo_keyboard_view") + if not preview: + record("text_preview_lowercase_vlm", False, + "setup_failed: no demo_keyboard_view on the surface", + depth=0, jump_kind="none", tag="content") + return + vlm_assert("text_preview_lowercase", + "Are the letter keys in the keyboard preview showing lowercase " + "letters (such as a s d f) rather than uppercase letters or digits?", + RESULTS_DIR, tag="content") + + +TESTS = [ + test_title_home, + test_title_language, + test_title_ui, + test_title_gestures, + test_title_emojis, + test_about_heading, + test_about_version, + test_about_copyright, + test_about_licenses_link, + test_about_privacy_link, + test_about_website_link, + test_changelog_title, + test_changelog_bullet, + test_not_setup_card, + test_testing_build_card, + test_gesture_swipe_up_summary, + test_gesture_swipe_down_summary, + test_dialog_title, + test_dialog_options, + test_preview_qwerty_vlm, + test_preview_spacebar_vlm, + test_preview_lowercase_vlm, +] + + +if __name__ == "__main__": + run_suite(TESTS, "text") diff --git a/android/anysoftkeyboard-anysoftkeyboard/tests/test_manifest.json b/android/anysoftkeyboard-anysoftkeyboard/tests/test_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..59a49a12caac6712e31f9d721a88c7120419dd4f --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/tests/test_manifest.json @@ -0,0 +1,737 @@ +{ + "manifest_version": 1, + "kit_api_version": 1, + "task_id": "AnySoftKeyboard", + "baseline_model": "claude-opus-4-8", + "baseline_package": "", + "total": 110, + "manifest_sha": "32d4620b2d57", + "tests": [ + { + "name": "computation::computation_home_preview_letters_not_numbers_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_home_preview_qwerty_row_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_spacebar_left_space", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_swipe_down_space", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_swipe_down_split", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_swipe_left_hide", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_swipe_right_shift", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_swipe_up_changes_from_default", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_swipe_up_restore_default", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_swipe_up_shift", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_swipe_up_space", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_swipe_up_value_survives_nav", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_ui_preview_qwerty_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_emoji_multi_record_integrity", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_emoji_multi_record_integrity_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_emoji_persists_process_death", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_emoji_persists_process_death_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_emoji_toggle_off", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_emoji_toggle_off_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_emoji_toggle_roundtrip", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_keyboard_enable", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_keyboard_enable_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_keyboard_primary_stays_enabled", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_theme_persists_process_death", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_theme_persists_process_death_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_theme_single_select", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_theme_single_select_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_theme_survives_nav_away", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_theme_survives_nav_away_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_back_about_to_home", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_back_effects_to_ui", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_back_keyboards_to_language", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_back_swipe_dialog_to_gestures", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_theme_unwind", + "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_effects_depth2", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_effects_depth2_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_keyboards_depth2", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_keyboards_depth2_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_language_tweaks_depth2", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_overflow_menu", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_select_theme_depth2", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_select_theme_depth2_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_swipe_dialog", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_tab_emojis", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_tab_gestures", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_tab_gestures_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_tab_home_from_language", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_tab_language", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_tab_ui", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_tab_ui_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "states::states_double_space_period", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_double_space_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_gesture_typing_on", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_gesture_typing_on_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_gesture_typing_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_gesture_typing_roundtrip", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_nav_select_home_to_language", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_nav_select_home_to_ui", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_nav_select_label_layout_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_nav_select_language_to_gestures", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_nav_select_language_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_nav_select_ui_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_remember_layout_per_app", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_show_suggestions_switch", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_show_suggestions_switch_off_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_show_suggestions_switch_on_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_space_switches_keyboards", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_space_switches_keyboards_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_suggestions_restart", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_theme_app_checkbox", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_theme_app_checkbox_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "structure::structure_about_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_about_shape_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_emojis_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_emojis_shape_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_bottom_nav", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_demo_keyboard", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_demo_keyboard_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gestures_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gestures_shape_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_overflow_menu_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_overflow_menu_shape_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_swipe_dialog_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_swipe_dialog_shape_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_theme_grid_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_theme_grid_shape_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "text::text_about_copyright", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_about_heading", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_about_licenses_link", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_about_privacy_link", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_about_version", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_about_website_link", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_changelog_bullet", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_changelog_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_dialog_options", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_dialog_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_gesture_swipe_down_summary", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_gesture_swipe_up_summary", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_not_setup_card", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_preview_lowercase_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_preview_qwerty_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_preview_spacebar_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_testing_build_card", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_title_emojis", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_title_gestures", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_title_home", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_title_language", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_title_ui", + "module": "text", + "baseline_status": "passed" + } + ], + "ignored": [], + "vlm_assertions": [ + { + "name": "computation::computation_home_preview_qwerty_row_vlm", + "module": "computation", + "tag": "content" + }, + { + "name": "computation::computation_home_preview_letters_not_numbers_vlm", + "module": "computation", + "tag": "content" + }, + { + "name": "computation::computation_ui_preview_qwerty_vlm", + "module": "computation", + "tag": "content" + }, + { + "name": "interaction::interaction_emoji_toggle_off_vlm", + "module": "interaction", + "tag": "shape" + }, + { + "name": "interaction::interaction_emoji_multi_record_integrity_vlm", + "module": "interaction", + "tag": "shape" + }, + { + "name": "interaction::interaction_emoji_persists_process_death_vlm", + "module": "interaction", + "tag": "color" + }, + { + "name": "interaction::interaction_keyboard_enable_vlm", + "module": "interaction", + "tag": "shape" + }, + { + "name": "interaction::interaction_theme_single_select_vlm", + "module": "interaction", + "tag": "shape" + }, + { + "name": "interaction::interaction_theme_persists_process_death_vlm", + "module": "interaction", + "tag": "content" + }, + { + "name": "interaction::interaction_theme_survives_nav_away_vlm", + "module": "interaction", + "tag": "content" + }, + { + "name": "navigation::nav_reach_about_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_reach_tab_ui_vlm", + "module": "navigation", + "tag": "color" + }, + { + "name": "navigation::nav_reach_tab_gestures_vlm", + "module": "navigation", + "tag": "layout" + }, + { + "name": "navigation::nav_reach_keyboards_depth2_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_reach_select_theme_depth2_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_reach_effects_depth2_vlm", + "module": "navigation", + "tag": "shape" + }, + { + "name": "states::states_gesture_typing_on_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_show_suggestions_switch_on_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_show_suggestions_switch_off_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_space_switches_keyboards_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_theme_app_checkbox_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_nav_select_language_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_nav_select_ui_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_nav_select_label_layout_vlm", + "module": "states", + "tag": "layout" + }, + { + "name": "structure::structure_gate_demo_keyboard_vlm", + "module": "structure", + "tag": "shape" + }, + { + "name": "structure::structure_gestures_shape_vlm", + "module": "structure", + "tag": "layout" + }, + { + "name": "structure::structure_emojis_shape_vlm", + "module": "structure", + "tag": "layout" + }, + { + "name": "structure::structure_swipe_dialog_shape_vlm", + "module": "structure", + "tag": "layout" + }, + { + "name": "structure::structure_about_shape_vlm", + "module": "structure", + "tag": "layout" + }, + { + "name": "structure::structure_overflow_menu_shape_vlm", + "module": "structure", + "tag": "layout" + }, + { + "name": "structure::structure_theme_grid_shape_vlm", + "module": "structure", + "tag": "layout" + }, + { + "name": "text::text_preview_qwerty_vlm", + "module": "text", + "tag": "content" + }, + { + "name": "text::text_preview_spacebar_vlm", + "module": "text", + "tag": "content" + }, + { + "name": "text::text_preview_lowercase_vlm", + "module": "text", + "tag": "content" + } + ], + "vlm_total": 34, + "n_vlm_unverified": 0, + "vlm_log_found": true +} \ No newline at end of file diff --git a/android/anysoftkeyboard-anysoftkeyboard/vlm_assertions.json b/android/anysoftkeyboard-anysoftkeyboard/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..5cc115b99ead9267ddccdfa39e893e1fec1d0dbd --- /dev/null +++ b/android/anysoftkeyboard-anysoftkeyboard/vlm_assertions.json @@ -0,0 +1,703 @@ +{ + "schema_version": 2, + "instance_id": "android/anysoftkeyboard-anysoftkeyboard", + "grading": { + "mode": "inline", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 34, + "with_verdict": 34, + "calibrated": 0, + "usable": null, + "scored_records": 34, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "states_gesture_typing_on_vlm", + "screenshot": "states_gesture_typing_on_vlm.png", + "assertion": "In the 'Gesture-Typing' section, does the 'Enable gesture-typing [BETA]' checkbox now appear checked (a filled/ticked box) rather than an empty square?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_gesture_typing_on", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_gate_demo_keyboard_vlm", + "screenshot": "structure_gate_demo_keyboard_vlm.png", + "assertion": "Is a keyboard (multiple rows of letter keys q w e r t y ...) shown in the upper part of the screen?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "structure_gate_demo_keyboard", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_gestures_shape_vlm", + "screenshot": "structure_gestures_shape_vlm.png", + "assertion": "Is the screen a vertically-stacked list of settings rows, each with a title and a smaller grey description line, and NOT a grid of picture cards?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "structure_gestures_shape", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_emojis_shape_vlm", + "screenshot": "structure_emojis_shape_vlm.png", + "assertion": "Does the screen show a grid of multiple picture cards arranged in two columns and several rows?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "structure_emojis_shape", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_swipe_dialog_shape_vlm", + "screenshot": "structure_swipe_dialog_shape_vlm.png", + "assertion": "Is a dialog open showing a vertical list of options, each with a round radio-button circle on its left side?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "structure_swipe_dialog_shape", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_about_shape_vlm", + "screenshot": "structure_about_shape_vlm.png", + "assertion": "Is there a purple app-bar / header strip spanning the full width across the very top of the screen?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "structure_about_shape", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_overflow_menu_shape_vlm", + "screenshot": "structure_overflow_menu_shape_vlm.png", + "assertion": "Is a small dropdown / pop-up menu of stacked text options open near the top-right area of the screen?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "structure_overflow_menu_shape", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_theme_grid_shape_vlm", + "screenshot": "structure_theme_grid_shape_vlm.png", + "assertion": "Below a large keyboard preview, are there several smaller keyboard theme preview cards laid out in a two-column grid?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "structure_theme_grid_shape", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_about_vlm", + "screenshot": "nav_reach_about_vlm.png", + "assertion": "Is there a large circular icon positioned in the horizontal centre of the screen, with a bold title text directly beneath it?", + "form": "question", + "expected": true, + "aspect": "position", + "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_tab_ui_vlm", + "screenshot": "nav_reach_tab_ui_vlm.png", + "assertion": "Is there a light purple / violet coloured bar spanning the full width across the very top of the screen (just below the status bar)?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "nav_reach_tab_ui", + "rigor": { + "jump_kind": "reach", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_tab_gestures_vlm", + "screenshot": "nav_reach_tab_gestures_vlm.png", + "assertion": "Is the screen a vertically-scrollable list of gesture settings rows (such as Swipe up / Swipe down / Swipe left / Swipe right), each with a title and a smaller grey description line below it?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "nav_reach_tab_gestures", + "rigor": { + "jump_kind": "reach", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_keyboards_depth2_vlm", + "screenshot": "nav_reach_keyboards_depth2_vlm.png", + "assertion": "Are the keyboard-layout preview cards arranged in a two-column grid (two cards positioned side by side per row)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_reach_keyboards_depth2", + "rigor": { + "jump_kind": "reach", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_select_theme_depth2_vlm", + "screenshot": "nav_reach_select_theme_depth2_vlm.png", + "assertion": "Are there keyboard THEME preview cards arranged in a two-column grid (two cards positioned side by side per row)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_reach_select_theme_depth2", + "rigor": { + "jump_kind": "reach", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_effects_depth2_vlm", + "screenshot": "nav_reach_effects_depth2_vlm.png", + "assertion": "Is there at least one filled / ticked check-box on the right-hand side of a settings row on this screen?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "nav_reach_effects_depth2", + "rigor": { + "jump_kind": "reach", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_emoji_toggle_off_vlm", + "screenshot": "interaction_emoji_toggle_off_vlm.png", + "assertion": "These are emoji category cards, each normally showing a small check-mark badge near its top edge. Is there at least ONE card that is now MISSING that check-mark badge while the others still have it?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "interaction_emoji_toggle_off", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_emoji_multi_record_integrity_vlm", + "screenshot": "interaction_emoji_multi_record_integrity_vlm.png", + "assertion": "This is a grid of emoji category cards. Do MOST cards still show a check-mark badge (i.e. only a single card is missing its badge, not all of them)?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "interaction_emoji_multi_record_integrity", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_emoji_persists_process_death_vlm", + "screenshot": "interaction_emoji_persists_process_death_vlm.png", + "assertion": "After the app was force-stopped and relaunched, this is the emoji category grid. Is at least one card still MISSING its check-mark badge while other cards clearly show one?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "interaction_emoji_persists_process_death", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_keyboard_enable_vlm", + "screenshot": "interaction_keyboard_enable_vlm.png", + "assertion": "This is a grid of keyboard-layout cards. Does the card labelled 'Dvorak' now show a check-mark badge indicating it is enabled?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "interaction_keyboard_enable", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_theme_single_select_vlm", + "screenshot": "interaction_theme_single_select_vlm.png", + "assertion": "This is a grid of keyboard-theme cards. Does EXACTLY ONE theme card show a check-mark badge (not zero and not more than one)?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "interaction_theme_single_select", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_theme_persists_process_death_vlm", + "screenshot": "interaction_theme_persists_process_death_vlm.png", + "assertion": "There is a keyboard preview near the top of this theme-selection screen. Below it, is there exactly one theme card marked with a check-mark badge?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "interaction_theme_persists_process_death", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_theme_survives_nav_away_vlm", + "screenshot": "interaction_theme_survives_nav_away_vlm.png", + "assertion": "This keyboard-theme selection screen was just reopened after navigating away. Is exactly one theme card marked with a check-mark badge?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "interaction_theme_survives_nav_away", + "rigor": { + "jump_kind": "value", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_home_preview_qwerty_row_vlm", + "screenshot": "computation_home_preview_qwerty_row_vlm.png", + "assertion": "In the on-screen keyboard preview, does the top row of letter keys read q, w, e, r, t, y from left to right?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "computation_home_preview_qwerty_row", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_home_preview_letters_not_numbers_vlm", + "screenshot": "computation_home_preview_letters_not_numbers_vlm.png", + "assertion": "Is the on-screen keyboard preview showing a QWERTY letter layout (alphabetic letter keys), not a numeric keypad?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "computation_home_preview_letters_not_numbers", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_ui_preview_qwerty_vlm", + "screenshot": "computation_ui_preview_qwerty_vlm.png", + "assertion": "Does the keyboard preview shown on this screen display a row of letter keys beginning with q, w, e, r, t, y?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "computation_ui_preview_qwerty", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_show_suggestions_switch_on_vlm", + "screenshot": "states_show_suggestions_switch_on_vlm.png", + "assertion": "Is the 'Show suggestions' toggle switch turned ON — its thumb to the RIGHT with a colored (purple) track?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_show_suggestions_switch_on", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_show_suggestions_switch_off_vlm", + "screenshot": "states_show_suggestions_switch_off_vlm.png", + "assertion": "Is the 'Show suggestions' toggle switch turned OFF — its thumb to the LEFT with a grey/uncolored track?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_show_suggestions_switch_off", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_space_switches_keyboards_vlm", + "screenshot": "states_space_switches_keyboards_vlm.png", + "assertion": "Is the checkbox in the 'Space switches keyboards' row now UNCHECKED (an empty square, no tick)?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_space_switches_keyboards", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_theme_app_checkbox_vlm", + "screenshot": "states_theme_app_checkbox_vlm.png", + "assertion": "Does the 'Change theme colors based on used app' checkbox now appear checked (a filled/ticked box) rather than an empty square?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_theme_app_checkbox", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_nav_select_language_vlm", + "screenshot": "states_nav_select_language_vlm.png", + "assertion": "In the bottom navigation bar, is the Language (globe) tab highlighted/colored and showing its 'Language' text label, while the other tabs are dark/grey icons with no label?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_nav_select_language", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_nav_select_ui_vlm", + "screenshot": "states_nav_select_ui_vlm.png", + "assertion": "In the bottom navigation bar, is the UI (palette) tab icon highlighted in purple/colored and showing a 'UI' text label, while the other tab icons are dark/grey?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_nav_select_ui", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_nav_select_label_layout_vlm", + "screenshot": "states_nav_select_label_layout_vlm.png", + "assertion": "In the bottom navigation bar, does exactly ONE tab (the Gestures tab) show a text label beneath its icon while every other tab shows only an icon with no label?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "states_nav_select_label_layout", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_preview_qwerty_vlm", + "screenshot": "text_preview_qwerty_vlm.png", + "assertion": "Does the on-screen keyboard preview display letter keys with the letters q w e r t y visible along its top row?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "text_preview_qwerty", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_preview_spacebar_vlm", + "screenshot": "text_preview_spacebar_vlm.png", + "assertion": "In the keyboard preview, does the wide space bar in the bottom row show the word 'English'?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "text_preview_spacebar", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_preview_lowercase_vlm", + "screenshot": "text_preview_lowercase_vlm.png", + "assertion": "Are the letter keys in the keyboard preview showing lowercase letters (such as a s d f) rather than uppercase letters or digits?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "text_preview_lowercase", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + } + ], + "merged_from_files": 1, + "source_shapes": { + "list": 1 + } +} \ No newline at end of file diff --git a/android/beemdevelopment-aegis/LICENSE b/android/beemdevelopment-aegis/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..94a9ed024d3859793618152ea559a168bbcbb5e2 --- /dev/null +++ b/android/beemdevelopment-aegis/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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 for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know 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 License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of 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 of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification 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 of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. 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 work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a 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 visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation 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 to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients 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 to +produce it from the Program, in the form of source code under the +terms 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 independent +works, 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 not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-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 excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the 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 install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional 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 you +add to a covered work, you may (if authorized by the copyright holders of +that 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 "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form 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 expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered 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 automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent 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 anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain 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 limiting +any implied license or other defenses to infringement that may +otherwise 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 or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License 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 have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License 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 the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES 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 OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy 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 greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + 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 appropriate +parts of the General Public License. Of course, your program's commands +might 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 +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/android/beemdevelopment-aegis/instance.json b/android/beemdevelopment-aegis/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..05d0f95a90e16abb67929e7da965e45e9ba2bc58 --- /dev/null +++ b/android/beemdevelopment-aegis/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "android/beemdevelopment-aegis", + "platform": "android", + "repo": "https://github.com/beemdevelopment/Aegis", + "commit": "59d5c640d6a2d0d16f243dbdd735758eed65bc63", + "patches": [], + "package": "com.beemdevelopment.aegis.debug", + "license": null +} diff --git a/android/beemdevelopment-aegis/reference/launch.sh b/android/beemdevelopment-aegis/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8 --- /dev/null +++ b/android/beemdevelopment-aegis/reference/launch.sh @@ -0,0 +1,9 @@ +#!/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 1 diff --git a/android/beemdevelopment-aegis/tests/android_computation_eval.json b/android/beemdevelopment-aegis/tests/android_computation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..d11558bbe1d43a09e873ea80c652c54700d70624 --- /dev/null +++ b/android/beemdevelopment-aegis/tests/android_computation_eval.json @@ -0,0 +1,225 @@ +{ + "module": "computation", + "total": 21, + "passed": 21, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 17, + "passed": 17, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 4, + "passed": 4, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.2353, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 21, + "depth_ge1": 12, + "depth_ge2": 3, + "value": 20, + "vlm_fine": 4 + }, + "results": [ + { + "test": "computation_same_secret_same_code", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "iSameA code == iSameB code" + }, + { + "test": "computation_diff_secret_diff_code", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "iDiffA code != iDiffB code" + }, + { + "test": "computation_default_six_digits", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "code has exactly 6 digits" + }, + { + "test": "computation_default_grouping_format", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "code text matches 'DDD DDD'" + }, + { + "test": "computation_digits_eight", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "code has exactly 8 digits" + }, + { + "test": "computation_eight_grouping_format", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "code text matches 'DDD DDD DD'" + }, + { + "test": "computation_digits_contrast", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "iC6->6 digits, iC8->8 digits" + }, + { + "test": "computation_code_charset", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "code is /^[0-9 ]+$/ with 6 digits" + }, + { + "test": "computation_code_stable_in_period", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "two close reads give the same code" + }, + { + "test": "computation_copy_matches_display", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "clipboard digits == a displayed code" + }, + { + "test": "computation_search_matches_one", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Showing 1 entry + only AppleCorp" + }, + { + "test": "computation_search_matches_none", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Showing 0 entries + no rows" + }, + { + "test": "computation_search_case_insensitive", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "'banana' -> Showing 1 entry + BananaInc" + }, + { + "test": "computation_search_present_then_absent", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "SoloIssuer present->absent on no-match" + }, + { + "test": "computation_type_default_totp", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "dropdown_type == 'TOTP'" + }, + { + "test": "computation_digits_field_default_six", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "text_digits == '6'" + }, + { + "test": "computation_period_field_default_thirty", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "text_period_counter == '30'" + }, + { + "test": "computation_code_accent_color_vlm", + "passed": true, + "message": "VLM: Q='On the single authenticator entry row, are the large numeric TOTP code digits rendered in a distinct coloured accent (for example a blue/teal tint) that is clearly DIFFERENT from the plain black/dark issuer and account-name text on the same row?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: On the single authenticator entry row, are the large numeric TOTP code digits rendered in a distinct coloured accent (for example a blue/teal tint) that is clearly DIFFERENT from the plain black/dark issuer and account-name text on the same row?", + "tag": "color" + }, + { + "test": "computation_code_large_font_vlm", + "passed": true, + "message": "VLM: Q='On the single authenticator entry row, are the numeric TOTP code digits rendered in a noticeably LARGER font than the smaller issuer/account-name text on the same row (i.e. the code is the most prominent text)?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: On the single authenticator entry row, are the numeric TOTP code digits rendered in a noticeably LARGER font than the smaller issuer/account-name text on the same row (i.e. the code is the most prominent text)?", + "tag": "size" + }, + { + "test": "computation_code_grouped_vlm", + "passed": true, + "message": "VLM: Q='Look at the six-digit TOTP code on the entry row. Is it displayed as TWO groups of three digits separated by a visible gap/space (for example '123 456'), rather than six digits with no gap?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Look at the six-digit TOTP code on the entry row. Is it displayed as TWO groups of three digits separated by a visible gap/space (for example '123 456'), rather than six digits with no gap?", + "tag": "position" + }, + { + "test": "computation_eight_wider_than_six_vlm", + "passed": true, + "message": "VLM: Q='This authenticator list has two entries. One shows a six-digit code and the other shows an eight-digit code. Is the eight-digit code visibly WIDER (occupies more horizontal space) than the six-digit code?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: This authenticator list has two entries. One shows a six-digit code and the other shows an eight-digit code. Is the eight-digit code visibly WIDER (occupies more horizontal space) than the six-digit code?", + "tag": "size" + } + ] +} \ No newline at end of file diff --git a/android/beemdevelopment-aegis/tests/android_interaction_eval.json b/android/beemdevelopment-aegis/tests/android_interaction_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..6104a1cda68e9d2e0751a8e7c1f4902173bfb5a3 --- /dev/null +++ b/android/beemdevelopment-aegis/tests/android_interaction_eval.json @@ -0,0 +1,248 @@ +{ + "module": "interaction", + "total": 23, + "passed": 23, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 14, + "passed": 14, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 9, + "passed": 9, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.6429, + "audit": { + "kit_api_version": 1, + "existence": 4, + "liveness": 0, + "interactive": 19, + "depth_ge1": 15, + "depth_ge2": 4, + "value": 10, + "vlm_fine": 7 + }, + "results": [ + { + "test": "interaction_create_entry", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Showing 1 entry + issuer 'iCreate'" + }, + { + "test": "interaction_create_absent_then_present", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "issuer 'iFlip' absent->present" + }, + { + "test": "interaction_multi_two_entries", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Showing 2 entries + iMultiA + iMultiB" + }, + { + "test": "interaction_edit_middle_keeps_others", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "rows [iOne, iTwoEDIT, iThree]" + }, + { + "test": "interaction_longpress_action_mode", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Done/Copy/Edit/Favorite appear (absent before)" + }, + { + "test": "interaction_longpress_highlight_vlm", + "passed": true, + "message": "VLM: Q='A single entry row in this authenticator list is long-press selected. Is exactly one list row visually highlighted with a different (tinted/darker) background colour than the rest of the screen?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: A single entry row in this authenticator list is long-press selected. Is exactly one list row visually highlighted with a different (tinted/darker) background colour than the rest of the screen?", + "tag": "color" + }, + { + "test": "interaction_context_more_menu", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "menu 'Select all'/'Assign to group'/'Delete'" + }, + { + "test": "interaction_edit_prefilled", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "editor prefilled issuer 'iEdOLD'" + }, + { + "test": "interaction_edit_saves_new_name", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "row issuer 'iEdB' present, 'iEdA' gone" + }, + { + "test": "interaction_favorite_pins_top", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "favorited iFavC becomes first row" + }, + { + "test": "interaction_favorite_marker_vlm", + "passed": true, + "message": "VLM: Q='One entry in this authenticator list was just marked as a favorite. Is there a small star-shaped indicator (a star icon or a coloured vertical bar) marking one of the entry rows as favorited?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: One entry in this authenticator list was just marked as a favorite. Is there a small star-shaped indicator (a star icon or a coloured vertical bar) marking one of the entry rows as favorited?", + "tag": "shape" + }, + { + "test": "interaction_persist_single", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "issuer 'iPersist' + Showing 1 entry after relaunch" + }, + { + "test": "interaction_persist_multi_integrity", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "rows [iPa, iPb, iPc] + Showing 3 entries after relaunch" + }, + { + "test": "interaction_edit_persists", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "issuer 'iEpNEW' after relaunch, 'iEpOLD' gone" + }, + { + "test": "interaction_cancel_create_no_phantom", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "count stays 'Showing 1 entry', no iPhantom" + }, + { + "test": "interaction_action_mode_done_exits", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "action mode -> Done -> back to list" + }, + { + "test": "interaction_row_avatar_vlm", + "passed": true, + "message": "VLM: Q='In this authenticator list, does the entry whose issuer is 'Zebra' have a round circular avatar tile on its left side (a coloured circle, typically showing a letter)?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In this authenticator list, does the entry whose issuer is 'Zebra' have a round circular avatar tile on its left side (a coloured circle, typically showing a letter)?", + "tag": "shape" + }, + { + "test": "interaction_row_avatar_letter_vlm", + "passed": true, + "message": "VLM: Q='The single entry in this authenticator list has issuer 'Quartz'. Does its round avatar tile on the left contain the capital letter 'Q' (the first letter of the issuer)?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: The single entry in this authenticator list has issuer 'Quartz'. Does its round avatar tile on the left contain the capital letter 'Q' (the first letter of the issuer)?", + "tag": "content" + }, + { + "test": "interaction_row_card_shape_vlm", + "passed": true, + "message": "VLM: Q='In this authenticator list, is the single entry drawn inside its own rounded-corner rectangular card/tile whose fill colour differs from the plain page background around it?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In this authenticator list, is the single entry drawn inside its own rounded-corner rectangular card/tile whose fill colour differs from the plain page background around it?", + "tag": "shape" + }, + { + "test": "interaction_row_code_color_vlm", + "passed": true, + "message": "VLM: Q='Look at the large TOTP code digits on the entry row. Are the code digits rendered in a single solid colour (a coloured accent such as red/green/blue) rather than plain black or grey body text?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Look at the large TOTP code digits on the entry row. Are the code digits rendered in a single solid colour (a coloured accent such as red/green/blue) rather than plain black or grey body text?", + "tag": "color" + }, + { + "test": "interaction_fab_menu_layout_vlm", + "passed": true, + "message": "VLM: Q='The add-entry menu is open. Are its options stacked vertically as a column of labelled items positioned above the floating action button in the bottom-right area of the screen?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: The add-entry menu is open. Are its options stacked vertically as a column of labelled items positioned above the floating action button in the bottom-right area of the screen?", + "tag": "position" + }, + { + "test": "interaction_action_toolbar_layout_vlm", + "passed": true, + "message": "VLM: Q='The contextual action bar is showing at the top after a long-press. Does the top bar display a horizontal row of several action icons (such as copy, edit, favourite, share/QR)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: The contextual action bar is showing at the top after a long-press. Does the top bar display a horizontal row of several action icons (such as copy, edit, favourite, share/QR)?", + "tag": "layout" + }, + { + "test": "interaction_persist_highlight_gone_vlm", + "passed": true, + "message": "VLM: Q='This authenticator list was just relaunched from a killed process. Is the list in its normal state with NO row highlighted or selected (i.e. every row shares the same background colour)?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: This authenticator list was just relaunched from a killed process. Is the list in its normal state with NO row highlighted or selected (i.e. every row shares the same background colour)?", + "tag": "color" + } + ] +} \ No newline at end of file diff --git a/android/beemdevelopment-aegis/tests/android_navigation_eval.json b/android/beemdevelopment-aegis/tests/android_navigation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..c1b9235574969cf29150bf8a94f7372d0d39c028 --- /dev/null +++ b/android/beemdevelopment-aegis/tests/android_navigation_eval.json @@ -0,0 +1,254 @@ +{ + "module": "navigation", + "total": 24, + "passed": 24, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 18, + "passed": 18, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 6, + "passed": 6, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.3333, + "audit": { + "kit_api_version": 1, + "existence": 6, + "liveness": 0, + "interactive": 18, + "depth_ge1": 18, + "depth_ge2": 10, + "value": 0, + "vlm_fine": 4 + }, + "results": [ + { + "test": "navigation_open_overflow_menu", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Overflow popup 'Settings'/'About' appeared; Main 'AegisDev' title gone" + }, + { + "test": "navigation_reach_settings", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "PreferencesActivity 'Navigate up' appeared; overflow 'About' item gone" + }, + { + "test": "navigation_reach_settings_vlm", + "passed": true, + "message": "VLM: Q='Is there a back/up arrow icon at the far top-left of the top app bar (to the left of the 'Settings' title)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is there a back/up arrow icon at the far top-left of the top app bar (to the left of the 'Settings' title)?", + "tag": "position" + }, + { + "test": "navigation_reach_about", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "AboutActivity 'Aegis Authenticator' appeared; overflow 'Settings' item gone" + }, + { + "test": "navigation_reach_about_vlm", + "passed": true, + "message": "VLM: Q='Is there a small app logo icon immediately to the LEFT of the 'Aegis Authenticator' text, near the top of the screen?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is there a small app logo icon immediately to the LEFT of the 'Aegis Authenticator' text, near the top of the screen?", + "tag": "position" + }, + { + "test": "navigation_fab_menu_open", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "FAB menu options 'Enter manually' and 'Scan QR code' appeared over Main" + }, + { + "test": "navigation_fab_menu_open_vlm", + "passed": true, + "message": "VLM: Q='Are there three labelled rounded option cards ('Scan QR code', 'Scan image', 'Enter manually') stacked vertically in the lower-right area of the screen?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Are there three labelled rounded option cards ('Scan QR code', 'Scan image', 'Enter manually') stacked vertically in the lower-right area of the screen?", + "tag": "position" + }, + { + "test": "navigation_reach_add_entry", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "EditEntryActivity 'Add new entry' shown; Main 'AegisDev' gone" + }, + { + "test": "navigation_reach_add_entry_vlm", + "passed": true, + "message": "VLM: Q='Is there a 'SAVE' action button in the top-right area of the top app bar?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is there a 'SAVE' action button in the top-right area of the top app bar?", + "tag": "position" + }, + { + "test": "navigation_search_open", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "SearchView 'Clear query' affordance appeared; toolbar 'AegisDev' gone" + }, + { + "test": "navigation_search_open_vlm", + "passed": true, + "message": "VLM: Q='Does the top app bar now contain a wide text input field that spans most of the bar's width (a search box)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does the top app bar now contain a wide text input field that spans most of the bar's width (a search box)?", + "tag": "layout" + }, + { + "test": "navigation_reach_appearance", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Appearance sub-screen 'Dynamic colors' appeared; Settings root title gone" + }, + { + "test": "navigation_reach_appearance_vlm", + "passed": true, + "message": "VLM: Q='Is there a vertical list of settings rows, where each row has a label with a smaller grey description line beneath it?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is there a vertical list of settings rows, where each row has a label with a smaller grey description line beneath it?", + "tag": "layout" + }, + { + "test": "navigation_reach_behavior", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Behavior sub-screen 'Haptic feedback' appeared; Settings root title gone" + }, + { + "test": "navigation_reach_security", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Security sub-screen 'Encryption' appeared; Settings root title gone" + }, + { + "test": "navigation_reach_audit_log", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Audit log sub-screen 'No reported events' appeared; Settings root title gone" + }, + { + "test": "navigation_reach_import_export", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Import & Export sub-screen 'Import from file' appeared; Settings root title gone" + }, + { + "test": "navigation_reach_backups", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Backups sub-screen 'Automatic backups' appeared; Settings root title gone" + }, + { + "test": "navigation_reach_icon_packs", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Icon packs sub-screen 'No icon packs' appeared; Settings root title gone" + }, + { + "test": "navigation_settings_back_to_main", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Main 'AegisDev' restored and 'Settings' title gone after one BACK" + }, + { + "test": "navigation_appearance_back_to_settings", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Settings root ('Behavior' row) restored after one BACK; 'Dynamic colors' gone; not Main" + }, + { + "test": "navigation_backstack_2hop_unwind", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "BACK #1 restores Settings root ('Appearance' row); BACK #2 restores Main 'AegisDev'" + }, + { + "test": "navigation_reach_edit_entry", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "EditEntryActivity 'Edit entry' shown; Main 'AegisDev' gone" + }, + { + "test": "navigation_edit_entry_back_to_main", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Main 'AegisDev' restored and 'Edit entry' gone after one BACK" + } + ] +} \ No newline at end of file diff --git a/android/beemdevelopment-aegis/tests/android_states_eval.json b/android/beemdevelopment-aegis/tests/android_states_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..7904799bf6e33dce0ebb61f47b26494f552438bc --- /dev/null +++ b/android/beemdevelopment-aegis/tests/android_states_eval.json @@ -0,0 +1,286 @@ +{ + "module": "states", + "total": 27, + "passed": 27, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 16, + "passed": 16, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 11, + "passed": 11, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.6875, + "audit": { + "kit_api_version": 1, + "existence": 1, + "liveness": 0, + "interactive": 26, + "depth_ge1": 24, + "depth_ge2": 16, + "value": 13, + "vlm_fine": 8 + }, + "results": [ + { + "test": "states_behavior_focus_search_toggle", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "'Focus search on app start' checked false->true" + }, + { + "test": "states_behavior_minimize_toggle", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "'Minimize on copy' checked false->true" + }, + { + "test": "states_behavior_haptic_toggle", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "'Haptic feedback' checked true->false" + }, + { + "test": "states_behavior_haptic_toggle_vlm", + "passed": true, + "message": "VLM: Q='In this settings list, look at the on/off toggle switch on the 'Haptic feedback' row. Is that switch in the OFF position, i.e. its thumb is on the LEFT and its track is grey/uncoloured (not a filled green/accent colour)?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In this settings list, look at the on/off toggle switch on the 'Haptic feedback' row. Is that switch in the OFF position, i.e. its thumb is on the LEFT and its track is grey/uncoloured (not a filled green/accent colour)?", + "tag": "color" + }, + { + "test": "states_behavior_minimize_persists", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "'Minimize on copy' checked persists as true after relaunch" + }, + { + "test": "states_behavior_multiselect_persists", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "'Multiselect groups' checked persists as true after relaunch" + }, + { + "test": "states_dynamic_colors_toggle", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "'Dynamic colors' checked false->true" + }, + { + "test": "states_theme_select_light", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Theme summary 'Selected: Light theme'" + }, + { + "test": "states_theme_select_light_vlm", + "passed": true, + "message": "VLM: Q='Light theme was just selected. Is the overall screen background light/white (a bright page) with dark text, rather than a dark or black background?' A=YES expect=YES", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Light theme was just selected. Is the overall screen background light/white (a bright page) with dark text, rather than a dark or black background?", + "tag": "color" + }, + { + "test": "states_theme_persists_vlm", + "passed": true, + "message": "VLM: Q='This authenticator app was just relaunched after Dark theme was chosen. Is its main screen still shown with a dark background (near-black / dark grey, light-coloured text) rather than a bright white page?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: This authenticator app was just relaunched after Dark theme was chosen. Is its main screen still shown with a dark background (near-black / dark grey, light-coloured text) rather than a bright white page?", + "tag": "color" + }, + { + "test": "states_theme_persists_summary", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Theme stays 'Selected: Dark theme' after relaunch" + }, + { + "test": "states_theme_dialog_checkmark_vlm", + "passed": true, + "message": "VLM: Q='This is a single-choice theme picker dialog listing Light theme, Dark theme, AMOLED theme and System default options. Is exactly ONE option marked with a filled/selected radio button (a round selected indicator) while the others are unselected?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: This is a single-choice theme picker dialog listing Light theme, Dark theme, AMOLED theme and System default options. Is exactly ONE option marked with a filled/selected radio button (a round selected indicator) while the others are unselected?", + "tag": "shape" + }, + { + "test": "states_view_mode_compact", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "View mode summary 'Selected: Compact'" + }, + { + "test": "states_show_account_name_select", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Show-account-name summary 'Selected: Next to the issuer' -> 'Selected: Below the issuer'" + }, + { + "test": "states_sort_issuer_reorders", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "first issuer 'Bravo'->'Alpha' after sort" + }, + { + "test": "states_sort_issuer_reorders_vlm", + "passed": true, + "message": "VLM: Q='This authenticator list has two entries, one for issuer 'Alpha' and one for issuer 'Bravo', after sorting by issuer A to Z. Is the 'Alpha' entry positioned ABOVE the 'Bravo' entry in the list?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: This authenticator list has two entries, one for issuer 'Alpha' and one for issuer 'Bravo', after sorting by issuer A to Z. Is the 'Alpha' entry positioned ABOVE the 'Bravo' entry in the list?", + "tag": "position" + }, + { + "test": "states_sort_order_persists", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "first issuer stays 'Alpha' after relaunch" + }, + { + "test": "states_secret_masked_vlm", + "passed": true, + "message": "VLM: Q='On this add-entry form, look at the 'Secret' input field. Is its value shown as masked characters (a row of dots or bullets / asterisks) rather than readable plain-text letters and digits?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: On this add-entry form, look at the 'Secret' input field. Is its value shown as masked characters (a row of dots or bullets / asterisks) rather than readable plain-text letters and digits?", + "tag": "content" + }, + { + "test": "states_secret_mask_toggle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "secret password=true->false (revealed)" + }, + { + "test": "states_secret_mask_toggle_vlm", + "passed": true, + "message": "VLM: Q='On this add-entry form, the 'Secret' field's reveal (eye) button was just tapped. Is the secret now shown as readable plain-text characters (the value 'JBSWY3DPEHPK3PXP') rather than as masked dots?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: On this add-entry form, the 'Secret' field's reveal (eye) button was just tapped. Is the secret now shown as readable plain-text characters (the value 'JBSWY3DPEHPK3PXP') rather than as masked dots?", + "tag": "content" + }, + { + "test": "states_advanced_accordion_expand", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Advanced fields (type/digits/period) absent->present on expand" + }, + { + "test": "states_advanced_accordion_expand_vlm", + "passed": true, + "message": "VLM: Q='The 'Advanced' section of this add-entry form was just expanded. Are extra input rows now visible below the Advanced header (such as a token 'Type', an 'Algorithm', a 'Period' and a 'Digits' field) that were hidden before?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: The 'Advanced' section of this add-entry form was just expanded. Are extra input rows now visible below the Advanced header (such as a token 'Type', an 'Algorithm', a 'Period' and a 'Digits' field) that were hidden before?", + "tag": "layout" + }, + { + "test": "states_search_field_focused", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "search field focused=true after opening search" + }, + { + "test": "states_focus_search_on_start", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "search field focused=true on next app start" + }, + { + "test": "states_switch_off_track_vlm", + "passed": true, + "message": "VLM: Q='In this settings list, look at the on/off toggle switch on the 'Minimize on copy' row. Is that switch OFF — its thumb on the LEFT and its track a plain grey/uncoloured tone (not a filled green or coloured accent)?' A=YES expect=YES", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In this settings list, look at the on/off toggle switch on the 'Minimize on copy' row. Is that switch OFF — its thumb on the LEFT and its track a plain grey/uncoloured tone (not a filled green or coloured accent)?", + "tag": "color" + }, + { + "test": "states_switch_on_track_vlm", + "passed": true, + "message": "VLM: Q='In this settings list, look at the on/off toggle switch on the 'Haptic feedback' row. Is that switch ON — its thumb on the RIGHT and its track filled with a coloured/accent tone (e.g. green/blue) rather than plain grey?' A=YES expect=YES", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In this settings list, look at the on/off toggle switch on the 'Haptic feedback' row. Is that switch ON — its thumb on the RIGHT and its track filled with a coloured/accent tone (e.g. green/blue) rather than plain grey?", + "tag": "color" + }, + { + "test": "states_default_theme_light_vlm", + "passed": true, + "message": "VLM: Q='This authenticator app is on its default (freshly installed) theme. Is its main screen background light — a bright white / very light page with dark text — rather than a dark or black background?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: This authenticator app is on its default (freshly installed) theme. Is its main screen background light — a bright white / very light page with dark text — rather than a dark or black background?", + "tag": "color" + } + ] +} \ No newline at end of file diff --git a/android/beemdevelopment-aegis/tests/android_structure_eval.json b/android/beemdevelopment-aegis/tests/android_structure_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..446b6d63f116f1c6c38baf1f9061fdb5d37ceb89 --- /dev/null +++ b/android/beemdevelopment-aegis/tests/android_structure_eval.json @@ -0,0 +1,247 @@ +{ + "module": "structure", + "total": 23, + "passed": 23, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 15, + "passed": 15, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 8, + "passed": 8, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.5333, + "audit": { + "kit_api_version": 1, + "existence": 3, + "liveness": 0, + "interactive": 20, + "depth_ge1": 7, + "depth_ge2": 0, + "value": 0, + "vlm_fine": 4 + }, + "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_fab", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_fab_menu_shape", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "FAB menu subtree appears: CardView 0->3 + fab_menu_item_enter" + }, + { + "test": "structure_fab_menu_shape_vlm", + "passed": true, + "message": "VLM: Q='Is there a vertical stack of menu item cards positioned above the circular floating action button in the lower-right area?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is there a vertical stack of menu item cards positioned above the circular floating action button in the lower-right area?", + "tag": "layout" + }, + { + "test": "structure_fab_menu_reverse", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "FAB menu cards removed on back; surface restored to base" + }, + { + "test": "structure_search_shape", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Toolbar -> SearchView: search_src_text/search_close_btn appear, search_button gone" + }, + { + "test": "structure_search_shape_vlm", + "passed": true, + "message": "VLM: Q='Is there a search input field across the top with a magnifier icon on the left and an X (clear) icon on the right?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is there a search input field across the top with a magnifier icon on the left and an X (clear) icon on the right?", + "tag": "position" + }, + { + "test": "structure_search_reverse", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "SearchView collapses: search_src_text gone, search_button+fab restored" + }, + { + "test": "structure_sort_popup_shape", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Sort popup subtree appears: RadioButton count increases (0->>0)" + }, + { + "test": "structure_overflow_menu_shape", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Overflow popup subtree appears with Settings + About rows" + }, + { + "test": "structure_overflow_menu_shape_vlm", + "passed": true, + "message": "VLM: Q='Is there a small popup menu of text options anchored near the top-right corner of the screen?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is there a small popup menu of text options anchored near the top-right corner of the screen?", + "tag": "position" + }, + { + "test": "structure_editentry_form_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "EditEntryActivity: >=4 EditText + accordian_header + action_save" + }, + { + "test": "structure_accordion_expand", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Accordion expands: dropdown_type/dropdown_algo/text_digits appear, node count grows" + }, + { + "test": "structure_accordion_expand_vlm", + "passed": true, + "message": "VLM: Q='In the expanded Advanced section, are there two dropdown/spinner controls placed side by side on the same row?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In the expanded Advanced section, are there two dropdown/spinner controls placed side by side on the same row?", + "tag": "position" + }, + { + "test": "structure_settings_list_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "PreferencesActivity: RecyclerView with >=3 category rows" + }, + { + "test": "structure_settings_list_shape_vlm", + "passed": true, + "message": "VLM: Q='Is the settings screen a single vertical column of stacked category rows, each with a title and a short description line?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is the settings screen a single vertical column of stacked category rows, each with a title and a short description line?", + "tag": "layout" + }, + { + "test": "structure_create_populates_list", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "empty textView5 removed; profile_code row + entries_shown_count appear" + }, + { + "test": "structure_create_populates_list_vlm", + "passed": true, + "message": "VLM: Q='Does the list now show an entry row with a circular avatar tile on the left and two lines of text stacked to its right?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Does the list now show an entry row with a circular avatar tile on the left and two lines of text stacked to its right?", + "tag": "layout" + }, + { + "test": "structure_longpress_action_mode", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "action-mode bar: action_mode_close_button + action_copy + action_edit appear" + }, + { + "test": "structure_longpress_action_mode_vlm", + "passed": true, + "message": "VLM: Q='Is the top bar a row of several action icons (such as star, copy, edit) with a back or close arrow icon at the far left?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is the top bar a row of several action icons (such as star, copy, edit) with a back or close arrow icon at the far left?", + "tag": "layout" + }, + { + "test": "structure_multi_entry_shape", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "profile_code rows: 1 -> 2 after second create" + }, + { + "test": "structure_main_overview_vlm", + "passed": true, + "message": "VLM: Q='Is the main screen a single-column list of entries with a round floating action button in the bottom-right corner?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is the main screen a single-column list of entries with a round floating action button in the bottom-right corner?", + "tag": "position" + } + ] +} \ No newline at end of file diff --git a/android/beemdevelopment-aegis/tests/android_testgen_kit.py b/android/beemdevelopment-aegis/tests/android_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6 --- /dev/null +++ b/android/beemdevelopment-aegis/tests/android_testgen_kit.py @@ -0,0 +1,1910 @@ +#!/usr/bin/env python3 +"""Android TestGen Kit — the single source of every test helper, so a test's +NAVIGATION 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 package +name differs): always use the module-level PACKAGE (argv[1]). Never write a package +name, an .apk path, a /data/data path, or a pixel coordinate as a literal. + python3 android_testgen_kit.py lint_sources # flags all of those + +SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery): + python3 android_testgen_kit.py audit + python3 android_testgen_kit.py lint + python3 android_testgen_kit.py lint_sources + python3 android_testgen_kit.py audit_depth [results_dir] +""" +from __future__ import annotations + +import ast +import base64 +import functools +import glob +import hashlib +import json +import math +import os +import re +import shlex +import subprocess +import sys +import time +import urllib.error +import 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.0 +SETTLE = { + "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 /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 " list[dict]: + """XML -> list of attribute dicts, each with _bounds and _center.""" + nodes = [] + for m in re.finditer(r"]+?)/?>", 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} \n" + " android_testgen_kit.py audit_depth [results_dir]\n" + " android_testgen_kit.py score [manifest_dir]") diff --git a/android/beemdevelopment-aegis/tests/android_text_eval.json b/android/beemdevelopment-aegis/tests/android_text_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..80c8e59f765eacc50ecae586b26a3d26e89b69d2 --- /dev/null +++ b/android/beemdevelopment-aegis/tests/android_text_eval.json @@ -0,0 +1,86 @@ +{ + "module": "text", + "total": 6, + "passed": 5, + "failed": 1, + "pass_rate": 0.8333, + "rule": { + "total": 6, + "passed": 5, + "failed": 1, + "pass_rate": 0.8333 + }, + "vlm": { + "total": 0, + "passed": 0, + "failed": 0, + "pass_rate": 0 + }, + "vlm_ratio": 0.0, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 6, + "depth_ge1": 2, + "depth_ge2": 0, + "value": 6, + "vlm_fine": 0 + }, + "results": [ + { + "test": "text_count_empty_state", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "'No entries found' + no count bar" + }, + { + "test": "text_count_singular_one", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "count 'Showing 1 entry' (singular)" + }, + { + "test": "text_count_plural_two", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "count 'Showing 2 entries' (plural)" + }, + { + "test": "text_new_entry_issuer_name", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "profile_issuer 'TextCheckIssuer', profile_account_name '(TextCheckName)'" + }, + { + "test": "text_search_count_strings", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "match 'Showing 1 entry', no-match 'Showing 0 entries'" + }, + { + "test": "text_title_add_new_entry", + "passed": false, + "message": "behavior_wrong: create form title is not 'Add new entry'", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "editor title 'Add new entry'" + } + ] +} \ No newline at end of file diff --git a/android/beemdevelopment-aegis/tests/conftest.py b/android/beemdevelopment-aegis/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27 --- /dev/null +++ b/android/beemdevelopment-aegis/tests/conftest.py @@ -0,0 +1 @@ +pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"] diff --git a/android/beemdevelopment-aegis/tests/requirements.txt b/android/beemdevelopment-aegis/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c --- /dev/null +++ b/android/beemdevelopment-aegis/tests/requirements.txt @@ -0,0 +1,2 @@ +pytest +pillow diff --git a/android/beemdevelopment-aegis/tests/test_android_computation.py b/android/beemdevelopment-aegis/tests/test_android_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..a441ebce147e72224f0bebfc9ec84540e8d0b864 --- /dev/null +++ b/android/beemdevelopment-aegis/tests/test_android_computation.py @@ -0,0 +1,880 @@ +#!/usr/bin/env python3 +"""COMPUTATION lane — the app's CORE FUNCTION (input -> output) for the Aegis +Authenticator (TOTP/HOTP 2FA). Sole owner of jump_kind="value". + +The core transform is TOTP code generation. Absolute code values are NOT asserted +against wall-clock time — there is a ~30 s clock skew between adb and the app, so +an absolute code is flaky. Every value test here is DETERMINISTIC and +clock-independent: + + * same secret -> identical code (RFC-6238 is a pure function) + * different secret -> (almost surely) differ + * digits setting -> code length (6 default, 8 configured) + * code format -> digits + spaces only, len(strip) == configured digits + * search filter -> "Showing N entries" + which issuers remain visible + +All expected values were OBSERVED on the running original, never computed here. + +Nothing is keyed on package / paths / coordinates: the same file scores a +from-scratch recreation at a different package name. + +Run: + python3 test_android_computation.py +""" +import os +import re +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +# Distinctive markers + valid base32 secrets (from recon; verified live). +SEC_A = "JBSWY3DPEHPK3PXP" +SEC_B = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" + + +# ── shared plumbing (own copies — NOT imported from the interaction lane) ──────── + +def _kb_off(): + """Lower the soft keyboard on the edit form WITHOUT navigating. + + The kit's hide_keyboard() can fall back to BACK, and on EditEntryActivity BACK + raises the "changes have not been saved" discard dialog which corrupts a + multi-field fill. KEYCODE_ESCAPE lowers the IME with no navigation (verified). + """ + if keyboard_visible(): + press_key("KEYCODE_ESCAPE") + settle("keyboard") + return not keyboard_visible() + + +def and_enter_main(clear=False): + """Get to MainActivity. clear=True wipes the vault first (virgin DB). + + Runs the 4-tap onboarding skip by resource-id only, choosing rb_none so the + vault opens directly on every relaunch (no unlock screen). Returns the last + fresh node list, or None if Main was never reached. + """ + if clear: + clear_data() + restart_app() + wait_for_foreground() + n = ui() + if node_by_id(n, "btnNext"): + for rid in ("btnNext", "rb_none", "btnNext", "btnNext"): + t = node_by_id(n, rid) + if t is None or not tap_node(t): + return None + n = ui() + if node_by_id(n, "fab") is None: + return None + return n + + +def _count_text(nodes=None): + nodes = ui() if nodes is None else nodes + c = node_by_id(nodes, "entries_shown_count") + return (c or {}).get("text") + + +def _issuers(nodes=None): + """Top-to-bottom list of profile_issuer strings currently shown.""" + nodes = ui() if nodes is None else nodes + rows = [(x["_bounds"][1], x.get("text", "")) + for x in nodes + if x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_issuer" + and "_bounds" in x] + return [t for _y, t in sorted(rows)] + + +def _code_for(issuer, nodes=None): + """profile_code of the row whose profile_issuer == `issuer` (space-stripped). + + Matches by y-band: the issuer label and its code sit on the same row, so the + code is the profile_code node closest below the issuer's top edge. Returns "" + when not found. + """ + nodes = ui() if nodes is None else nodes + iss_y = None + for x in nodes: + if (x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_issuer" + and x.get("text") == issuer and "_bounds" in x): + iss_y = x["_bounds"][1] + break + if iss_y is None: + return "" + best, best_dy = "", 10 ** 9 + for x in nodes: + if (x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_code" + and "_bounds" in x): + dy = abs(x["_bounds"][1] - iss_y) + if dy < best_dy: + best, best_dy = x.get("text", ""), dy + # Only accept a code on the same row (rows are ~300px tall on this device). + return best.replace(" ", "") if best_dy < 260 else "" + + +def _all_codes(nodes=None): + """Every profile_code on screen (space-stripped), top-to-bottom.""" + nodes = ui() if nodes is None else nodes + rows = [(x["_bounds"][1], x.get("text", "")) + for x in nodes + if x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_code" + and "_bounds" in x] + return [t.replace(" ", "") for _y, t in sorted(rows)] + + +def _raw_code_text(issuer, nodes=None): + """The profile_code text WITH spaces (to check the grouping format).""" + nodes = ui() if nodes is None else nodes + iss_y = None + for x in nodes: + if (x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_issuer" + and x.get("text") == issuer and "_bounds" in x): + iss_y = x["_bounds"][1] + break + if iss_y is None: + return "" + best, best_dy = "", 10 ** 9 + for x in nodes: + if (x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_code" + and "_bounds" in x): + dy = abs(x["_bounds"][1] - iss_y) + if dy < best_dy: + best, best_dy = x.get("text", ""), dy + return best if best_dy < 260 else "" + + +def _row_node(issuer, nodes=None): + """The profile_issuer node with text == issuer, from a fresh/given dump.""" + nodes = ui() if nodes is None else nodes + for x in nodes: + if (x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_issuer" + and x.get("text") == issuer): + return x + return None + + +def and_enter_editor(): + """Main -> FAB menu -> Enter manually -> EditEntryActivity. Backs a depth>=1 + claim via the and_enter_* NAME + an and_enter() call once the surface changes.""" + n = ui() + fab = node_by_id(n, "fab") + if fab is None or not tap_node(fab): + return False + n = ui() + enter = node_by_id(n, "fab_menu_item_enter") + if enter is None or not tap_node(enter): + return False + settle("tap") + if not get_current_activity().endswith("EditEntryActivity"): + return False + and_enter("editor") + return True + + +def _clear_field(node, rid): + """Select-to-end + delete an EditText, then return the fresh node.""" + if not tap_node(node): + return None + settle("keyboard") + press_key("KEYCODE_MOVE_END") + for _ in range(14): + press_key("KEYCODE_DEL") + settle("text") + return node_by_id(ui(), rid) + + +def and_expand_advanced(): + """On EditEntryActivity, expand the Advanced accordion so text_digits / + dropdown_type become visible. Counts as crossing into that section.""" + n = ui() + if node_by_id(n, "text_digits") is not None: + return True # already expanded + hdr = node_by_id(n, "accordian_header") or find_node_ci(n, "Advanced") + if hdr is None or not tap_node(hdr): + return False + settle("tap") + if node_by_id(ui(), "text_digits") is None: + return False + and_enter("advanced") + return True + + +def and_create_entry(name, issuer, secret, *, digits=None, type_name=None): + """FAB -> Enter manually -> fill name/issuer/secret (+ optional Advanced + digits / type) -> SAVE. Returns True only when we land on Main with the new + issuer visible.""" + if not and_enter_editor(): + return False + n = ui() + nm = node_by_id(n, "text_name") + if nm is None or not type_text(nm, name): + return False + _kb_off() + n = ui() + iss = node_by_id(n, "text_issuer") + if iss is None or not type_text(iss, issuer): + return False + _kb_off() + n = ui() + sec = node_by_id(n, "text_secret") + if sec is None or not type_text(sec, secret): + return False + _kb_off() + if digits is not None or type_name is not None: + if not and_expand_advanced(): + return False + if type_name is not None: + n = ui() + dd = node_by_id(n, "dropdown_type") + if dd is None or not tap_node(dd): + return False + settle("tap") + opt = find_node_ci(ui(), type_name) + if opt is None or not tap_node(opt): + return False + settle("tap") + _kb_off() + if digits is not None: + n = ui() + dg = node_by_id(n, "text_digits") + dg = _clear_field(dg, "text_digits") + if dg is None or not type_text(dg, str(digits)): + return False + _kb_off() + n = ui() + save = node_by_id(n, "action_save") + if save is None or not tap_node(save): + return False + n = ui() + if find_node_ci(n, "Error saving profile"): + return False + if find_node_ci(n, "Your changes have not been saved"): + sv = find_node(n, text="Save") + if sv: + tap_node(sv) + n = ui() + if not get_current_activity().endswith("MainActivity"): + return False + return find_node_ci(ui(), issuer) is not None + + +def and_open_search(): + """Main -> Search icon -> in-toolbar SearchView. Counts one surface.""" + n = ui() + sb = node_by_id(n, "search_button") + if sb is None or not tap_node(sb): + return False + settle("tap") + if node_by_id(ui(), "search_src_text") is None: + return False + and_enter("search") + return True + + +def _type_search(query): + """Clear the search field then type `query`. Returns the visible field text.""" + st = node_by_id(ui(), "search_src_text") + if st is None: + return None + tap_node(st) + settle("keyboard") + press_key("KEYCODE_MOVE_END") + for _ in range(16): + press_key("KEYCODE_DEL") + settle("text") + st = node_by_id(ui(), "search_src_text") + if st is None or not type_text(st, query): + return None + return (node_by_id(ui(), "search_src_text") or {}).get("text") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1. PRIMARY value test — same secret -> IDENTICAL code (RFC-6238 is a function) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_same_secret_same_code",)) +def test_same_secret_same_code(): + if and_enter_main(clear=True) is None: + record("computation_same_secret_same_code", False, + "setup_failed: could not reach MainActivity", + depth=0, jump_kind="value", expect="iSameA code == iSameB code") + return + if not (and_create_entry("nSameA", "iSameA", SEC_B) + and and_create_entry("nSameB", "iSameB", SEC_B)): + record("computation_same_secret_same_code", False, + "feature_missing: could not create two entries", + depth=0, jump_kind="value", expect="iSameA code == iSameB code") + return + n = ui() + ca, cb = _code_for("iSameA", n), _code_for("iSameB", n) + ok = bool(ca) and bool(cb) and ca == cb + record("computation_same_secret_same_code", ok, + "" if ok else f"behavior_wrong: identical secret gave codes " + f"{ca!r} vs {cb!r} (must be equal)", + depth=0, jump_kind="value", expect="iSameA code == iSameB code") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2. Different secrets -> different codes (almost surely) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_diff_secret_diff_code",)) +def test_diff_secret_diff_code(): + if and_enter_main(clear=True) is None: + record("computation_diff_secret_diff_code", False, + "setup_failed: could not reach MainActivity", + depth=0, jump_kind="value", expect="iDiffA code != iDiffB code") + return + if not (and_create_entry("nDiffA", "iDiffA", SEC_A) + and and_create_entry("nDiffB", "iDiffB", SEC_B)): + record("computation_diff_secret_diff_code", False, + "feature_missing: could not create two entries", + depth=0, jump_kind="value", expect="iDiffA code != iDiffB code") + return + n = ui() + ca, cb = _code_for("iDiffA", n), _code_for("iDiffB", n) + ok = bool(ca) and bool(cb) and ca != cb + record("computation_diff_secret_diff_code", ok, + "" if ok else f"behavior_wrong: different secrets gave equal code " + f"{ca!r} == {cb!r}", + depth=0, jump_kind="value", expect="iDiffA code != iDiffB code") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3. Default code length == 6 digits (format "XXX XXX") +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_default_six_digits",)) +def test_default_six_digits(): + if and_enter_main(clear=True) is None or not and_create_entry("n6", "iSix", SEC_A): + record("computation_default_six_digits", False, + "setup_failed: could not create a default entry", + depth=0, jump_kind="value", expect="code has exactly 6 digits") + return + n = ui() + code = _code_for("iSix", n) + ok = bool(code) and len(code) == 6 and code.isdigit() + record("computation_default_six_digits", ok, + "" if ok else f"behavior_wrong: default code {code!r} has " + f"{len(code)} digits (expected 6)", + depth=0, jump_kind="value", expect="code has exactly 6 digits") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4. Default grouping format is exactly "XXX XXX" +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_default_grouping_format",)) +def test_default_grouping_format(): + if and_enter_main(clear=True) is None or not and_create_entry("ng", "iGrp", SEC_A): + record("computation_default_grouping_format", False, + "setup_failed: could not create a default entry", + depth=0, jump_kind="value", expect="code text matches 'DDD DDD'") + return + raw = _raw_code_text("iGrp", ui()) + ok = bool(re.fullmatch(r"\d{3} \d{3}", raw)) + record("computation_default_grouping_format", ok, + "" if ok else f"behavior_wrong: code text {raw!r} is not 'DDD DDD'", + depth=0, jump_kind="value", expect="code text matches 'DDD DDD'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5. Digits setting -> code length == 8 (Advanced accordion; depth>=1) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_digits_eight",)) +def test_digits_eight(): + if and_enter_main(clear=True) is None: + record("computation_digits_eight", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="value", expect="code has exactly 8 digits") + return + if not and_create_entry("n8", "iEight", SEC_A, digits=8): + record("computation_digits_eight", False, + "feature_missing: could not set Advanced digits=8 and save", + depth=1, jump_kind="value", expect="code has exactly 8 digits") + return + code = _code_for("iEight", ui()) + ok = bool(code) and len(code) == 8 and code.isdigit() + record("computation_digits_eight", ok, + "" if ok else f"behavior_wrong: digits=8 gave code {code!r} with " + f"{len(code)} digits (expected 8)", + depth=1, jump_kind="value", expect="code has exactly 8 digits") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 6. 8-digit grouping format is exactly "XXX XXX XX" +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_eight_grouping_format",)) +def test_eight_grouping_format(): + if and_enter_main(clear=True) is None: + record("computation_eight_grouping_format", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="value", expect="code text matches 'DDD DDD DD'") + return + if not and_create_entry("n8g", "iEightG", SEC_A, digits=8): + record("computation_eight_grouping_format", False, + "feature_missing: could not set Advanced digits=8 and save", + depth=1, jump_kind="value", expect="code text matches 'DDD DDD DD'") + return + raw = _raw_code_text("iEightG", ui()) + ok = bool(re.fullmatch(r"\d{3} \d{3} \d{2}", raw)) + record("computation_eight_grouping_format", ok, + "" if ok else f"behavior_wrong: 8-digit code text {raw!r} is not " + f"'DDD DDD DD'", + depth=1, jump_kind="value", expect="code text matches 'DDD DDD DD'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 7. Digits contrast: a 6-digit row and an 8-digit row coexist with the right lens +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_digits_contrast",)) +def test_digits_contrast(): + if and_enter_main(clear=True) is None: + record("computation_digits_contrast", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="value", expect="iC6->6 digits, iC8->8 digits") + return + if not (and_create_entry("nc6", "iC6", SEC_A) + and and_create_entry("nc8", "iC8", SEC_A, digits=8)): + record("computation_digits_contrast", False, + "feature_missing: could not create a 6- and an 8-digit entry", + depth=1, jump_kind="value", expect="iC6->6 digits, iC8->8 digits") + return + n = ui() + c6, c8 = _code_for("iC6", n), _code_for("iC8", n) + ok = (bool(c6) and bool(c8) and len(c6) == 6 and len(c8) == 8 + and c6.isdigit() and c8.isdigit()) + record("computation_digits_contrast", ok, + "" if ok else f"behavior_wrong: iC6={c6!r}({len(c6)}) iC8={c8!r}" + f"({len(c8)}) (expected 6 and 8)", + depth=1, jump_kind="value", expect="iC6->6 digits, iC8->8 digits") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 8. Code format: only digits + spaces, and len(strip) == configured digits (6) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_code_charset",)) +def test_code_charset(): + if and_enter_main(clear=True) is None or not and_create_entry("ncs", "iCharset", SEC_B): + record("computation_code_charset", False, + "setup_failed: could not create an entry", + depth=0, jump_kind="value", expect="code is /^[0-9 ]+$/ with 6 digits") + return + raw = _raw_code_text("iCharset", ui()) + only_digits_spaces = bool(raw) and bool(re.fullmatch(r"[0-9 ]+", raw)) + ndig = len(raw.replace(" ", "")) + ok = only_digits_spaces and ndig == 6 + record("computation_code_charset", ok, + "" if ok else f"behavior_wrong: code text {raw!r} not digits+spaces " + f"or digit-count {ndig} != 6", + depth=0, jump_kind="value", expect="code is /^[0-9 ]+$/ with 6 digits") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 9. Code is STABLE within a 30 s period (two close reads must match) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_code_stable_in_period",)) +def test_code_stable_in_period(): + if and_enter_main(clear=True) is None or not and_create_entry("nst", "iStable", SEC_B): + record("computation_code_stable_in_period", False, + "setup_failed: could not create an entry", + depth=0, jump_kind="value", expect="two close reads give the same code") + return + c1 = _code_for("iStable", ui()) + c2 = _code_for("iStable", ui()) # a fresh dump, only ~1 s later + ok = bool(c1) and c1 == c2 + record("computation_code_stable_in_period", ok, + "" if ok else f"behavior_wrong: code changed within one read pair " + f"{c1!r} -> {c2!r}", + depth=0, jump_kind="value", expect="two close reads give the same code") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 10. Copy code -> the clipboard holds the code that was displayed AT COPY TIME. +# We read the clipboard THROUGH the app: copy, then paste into the search +# field and read its text back. depth>=1 (action mode + search surface). +# +# The copy + navigate-to-search sequence can straddle a 30 s TOTP period +# boundary, so a single displayed-code snapshot goes stale. We therefore +# accept the clipboard iff it equals a code the app ACTUALLY showed for this +# row during the copy window (the read right before AND the read right after +# the copy tap). This stays strict — the clipboard must match an OBSERVED +# displayed code, never an arbitrary 6-digit string — while tolerating the +# one boundary the slow navigation can cross. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_copy_matches_display",)) +def test_copy_matches_display(): + if and_enter_main(clear=True) is None or not and_create_entry("ncp", "iCopy", SEC_A): + record("computation_copy_matches_display", False, + "setup_failed: could not create an entry to copy", + depth=1, jump_kind="value", expect="clipboard digits == a displayed code") + return + # Read the code and locate the row from the SAME dump, so the copy happens + # immediately after the snapshot. + n = ui() + disp_before = _code_for("iCopy", n) + row = _row_node("iCopy", n) + if not disp_before or row is None: + record("computation_copy_matches_display", False, + "setup_failed: could not read the displayed code / row", + depth=1, jump_kind="value", expect="clipboard digits == a displayed code") + return + # Long-press the row -> action mode -> Copy. + if not long_press(row): + record("computation_copy_matches_display", False, + "feature_missing: long-press did not open action mode", + depth=1, jump_kind="value", expect="clipboard digits == a displayed code") + return + and_enter("action_mode") + cp = node_by_id(ui(), "action_copy") + if cp is None or not tap_node(cp): + record("computation_copy_matches_display", False, + "feature_missing: no Copy control in action mode", + depth=1, jump_kind="value", expect="clipboard digits == a displayed code") + return + settle("tap") + # Leave action mode if still up, then read the code AGAIN from Main — this + # brackets the copy so a boundary crossing is captured either side. + done = node_by_id(ui(), "action_mode_close_button") + if done: + tap_node(done) + settle("tap") + disp_after = _code_for("iCopy", ui()) + valid_codes = {c for c in (disp_before, disp_after) if c} + # Paste the clipboard into the search field and read it back. + if not and_open_search(): + record("computation_copy_matches_display", False, + "setup_failed: could not open search to read the clipboard back", + depth=1, jump_kind="value", expect="clipboard digits == a displayed code") + return + st = node_by_id(ui(), "search_src_text") + tap_node(st) + settle("keyboard") + press_key(279) # KEYCODE_PASTE + settle("text") + pasted = (node_by_id(ui(), "search_src_text") or {}).get("text", "") or "" + clip_digits = re.sub(r"\D", "", pasted) + ok = bool(clip_digits) and clip_digits in valid_codes + record("computation_copy_matches_display", ok, + "" if ok else f"behavior_wrong: pasted clipboard {pasted!r} " + f"(digits {clip_digits!r}) not in displayed codes " + f"{sorted(valid_codes)}", + depth=1, jump_kind="value", expect="clipboard digits == a displayed code") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 11. Search filter: exact issuer query -> "Showing 1 entry" + only that issuer +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_search_matches_one",)) +def test_search_matches_one(): + if and_enter_main(clear=True) is None: + record("computation_search_matches_one", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="value", expect="Showing 1 entry + only AppleCorp") + return + if not (and_create_entry("na", "AppleCorp", SEC_A) + and and_create_entry("nb", "BananaInc", SEC_B)): + record("computation_search_matches_one", False, + "feature_missing: could not create two entries", + depth=1, jump_kind="value", expect="Showing 1 entry + only AppleCorp") + return + if not and_open_search(): + record("computation_search_matches_one", False, + "feature_missing: could not open Search", + depth=1, jump_kind="value", expect="Showing 1 entry + only AppleCorp") + return + _type_search("Apple") + n = ui() + cnt = _count_text(n) + iss = _issuers(n) + ok = cnt == "Showing 1 entry" and iss == ["AppleCorp"] + record("computation_search_matches_one", ok, + "" if ok else f"behavior_wrong: query 'Apple' -> count {cnt!r} " + f"issuers {iss!r} (expected 'Showing 1 entry' + ['AppleCorp'])", + depth=1, jump_kind="value", expect="Showing 1 entry + only AppleCorp") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 12. Search filter: no-match query -> "Showing 0 entries", no rows +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_search_matches_none",)) +def test_search_matches_none(): + if and_enter_main(clear=True) is None: + record("computation_search_matches_none", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="value", expect="Showing 0 entries + no rows") + return + if not (and_create_entry("na", "AppleCorp", SEC_A) + and and_create_entry("nb", "BananaInc", SEC_B)): + record("computation_search_matches_none", False, + "feature_missing: could not create two entries", + depth=1, jump_kind="value", expect="Showing 0 entries + no rows") + return + if not and_open_search(): + record("computation_search_matches_none", False, + "feature_missing: could not open Search", + depth=1, jump_kind="value", expect="Showing 0 entries + no rows") + return + _type_search("ZZZQQ") + n = ui() + cnt = _count_text(n) + iss = _issuers(n) + ok = cnt == "Showing 0 entries" and iss == [] + record("computation_search_matches_none", ok, + "" if ok else f"behavior_wrong: query 'ZZZQQ' -> count {cnt!r} " + f"issuers {iss!r} (expected 'Showing 0 entries' + [])", + depth=1, jump_kind="value", expect="Showing 0 entries + no rows") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 13. Search is case-insensitive substring: lowercase query still matches issuer +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_search_case_insensitive",)) +def test_search_case_insensitive(): + if and_enter_main(clear=True) is None: + record("computation_search_case_insensitive", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="value", expect="'banana' -> Showing 1 entry + BananaInc") + return + if not (and_create_entry("na", "AppleCorp", SEC_A) + and and_create_entry("nb", "BananaInc", SEC_B)): + record("computation_search_case_insensitive", False, + "feature_missing: could not create two entries", + depth=1, jump_kind="value", expect="'banana' -> Showing 1 entry + BananaInc") + return + if not and_open_search(): + record("computation_search_case_insensitive", False, + "feature_missing: could not open Search", + depth=1, jump_kind="value", expect="'banana' -> Showing 1 entry + BananaInc") + return + _type_search("banana") # lowercase substring of "BananaInc" + n = ui() + cnt = _count_text(n) + iss = _issuers(n) + ok = cnt == "Showing 1 entry" and iss == ["BananaInc"] + record("computation_search_case_insensitive", ok, + "" if ok else f"behavior_wrong: query 'banana' -> count {cnt!r} " + f"issuers {iss!r} (expected 'Showing 1 entry' + ['BananaInc'])", + depth=1, jump_kind="value", expect="'banana' -> Showing 1 entry + BananaInc") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 14. Search transition: a matching row is PRESENT, then a no-match query makes +# it ABSENT — the discriminator's positive/negative pairing. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_search_present_then_absent",)) +def test_search_present_then_absent(): + if and_enter_main(clear=True) is None or not and_create_entry("nsp", "SoloIssuer", SEC_A): + record("computation_search_present_then_absent", False, + "setup_failed: could not create an entry", + depth=1, jump_kind="transition", expect="SoloIssuer present->absent on no-match") + return + if not and_open_search(): + record("computation_search_present_then_absent", False, + "feature_missing: could not open Search", + depth=1, jump_kind="transition", expect="SoloIssuer present->absent on no-match") + return + _type_search("Solo") + present = find_node_ci(ui(), "SoloIssuer") is not None + _type_search("ZZZQQ") + absent = find_node_ci(ui(), "SoloIssuer") is None + ok = present and absent + record("computation_search_present_then_absent", ok, + "" if ok else f"behavior_wrong: SoloIssuer present_on_match={present} " + f"absent_on_nomatch={absent}", + depth=1, jump_kind="transition", expect="SoloIssuer present->absent on no-match") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 15. TOTP type default is "TOTP" (Advanced spinner default) — value in editor +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_type_default_totp",)) +def test_type_default_totp(): + if and_enter_main(clear=True) is None or not and_enter_editor(): + record("computation_type_default_totp", False, + "setup_failed: could not open the editor", + depth=2, jump_kind="value", expect="dropdown_type == 'TOTP'") + return + if not and_expand_advanced(): + record("computation_type_default_totp", False, + "feature_missing: could not expand Advanced", + depth=2, jump_kind="value", expect="dropdown_type == 'TOTP'") + return + dd = node_by_id(ui(), "dropdown_type") + got = (dd or {}).get("text") + ok = got == "TOTP" + record("computation_type_default_totp", ok, + "" if ok else f"behavior_wrong: default type spinner is {got!r} " + f"(expected 'TOTP')", + depth=2, jump_kind="value", expect="dropdown_type == 'TOTP'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 16. Default digits field default is "6" (Advanced) — value in editor +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_digits_field_default_six",)) +def test_digits_field_default_six(): + if and_enter_main(clear=True) is None or not and_enter_editor(): + record("computation_digits_field_default_six", False, + "setup_failed: could not open the editor", + depth=2, jump_kind="value", expect="text_digits == '6'") + return + if not and_expand_advanced(): + record("computation_digits_field_default_six", False, + "feature_missing: could not expand Advanced", + depth=2, jump_kind="value", expect="text_digits == '6'") + return + dg = node_by_id(ui(), "text_digits") + got = (dg or {}).get("text") + ok = got == "6" + record("computation_digits_field_default_six", ok, + "" if ok else f"behavior_wrong: default digits field is {got!r} " + f"(expected '6')", + depth=2, jump_kind="value", expect="text_digits == '6'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 17. Period field default is "30" (Advanced) — value in editor +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_period_field_default_thirty",)) +def test_period_field_default_thirty(): + if and_enter_main(clear=True) is None or not and_enter_editor(): + record("computation_period_field_default_thirty", False, + "setup_failed: could not open the editor", + depth=2, jump_kind="value", expect="text_period_counter == '30'") + return + if not and_expand_advanced(): + record("computation_period_field_default_thirty", False, + "feature_missing: could not expand Advanced", + depth=2, jump_kind="value", expect="text_period_counter == '30'") + return + pc = node_by_id(ui(), "text_period_counter") + got = (pc or {}).get("text") + ok = got == "30" + record("computation_period_field_default_thirty", ok, + "" if ok else f"behavior_wrong: default period field is {got!r} " + f"(expected '30')", + depth=2, jump_kind="value", expect="text_period_counter == '30'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# ── VLM cluster (exactly 4): genuinely RENDERED code properties ───────────────── +# All questions authored from screenshots captured on the running original. +# Fine tags used: color, size, position, size (>= 2 distinct fine tags). +# NOTE observed on the original: this build shows NO per-row countdown pie/ring, +# so that property is deliberately NOT asserted (it would fail on the ground +# truth). Instead VLM #1 asserts the code's distinct accent colour, which IS +# rendered (the code sits in a clear blue, unlike the black issuer text). +# ══════════════════════════════════════════════════════════════════════════════ + +# VLM #1 — the generated code digits are rendered in a distinct ACCENT COLOUR. +@and_test(expects=("computation_code_accent_color_vlm",)) +def test_code_accent_color_vlm(): + if and_enter_main(clear=True) is None or not and_create_entry("nac", "iAccent", SEC_B): + record("computation_code_accent_color_vlm", False, + "setup_failed: could not create an entry", + depth=0, jump_kind="value", tag="color") + return + vlm_assert("computation_code_accent_color", + "On the single authenticator entry row, are the large numeric TOTP " + "code digits rendered in a distinct coloured accent (for example a " + "blue/teal tint) that is clearly DIFFERENT from the plain black/dark " + "issuer and account-name text on the same row?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="color") + + +# VLM #2 — the TOTP code digits are rendered large (prominent size). +@and_test(expects=("computation_code_large_font_vlm",)) +def test_code_large_font_vlm(): + if and_enter_main(clear=True) is None or not and_create_entry("nlf", "iLargeFont", SEC_B): + record("computation_code_large_font_vlm", False, + "setup_failed: could not create an entry", + depth=0, jump_kind="value", tag="size") + return + vlm_assert("computation_code_large_font", + "On the single authenticator entry row, are the numeric TOTP code " + "digits rendered in a noticeably LARGER font than the smaller " + "issuer/account-name text on the same row (i.e. the code is the " + "most prominent text)?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="size") + + +# VLM #3 — the 6-digit code is split into two space-separated groups of 3. +@and_test(expects=("computation_code_grouped_vlm",)) +def test_code_grouped_vlm(): + if and_enter_main(clear=True) is None or not and_create_entry("ngp", "iGrouped", SEC_A): + record("computation_code_grouped_vlm", False, + "setup_failed: could not create an entry", + depth=0, jump_kind="value", tag="position") + return + vlm_assert("computation_code_grouped", + "Look at the six-digit TOTP code on the entry row. Is it displayed " + "as TWO groups of three digits separated by a visible gap/space " + "(for example '123 456'), rather than six digits with no gap?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="position") + + +# VLM #4 — an 8-digit code is visibly WIDER than a 6-digit code on the same list. +@and_test(expects=("computation_eight_wider_than_six_vlm",)) +def test_eight_wider_than_six_vlm(): + if and_enter_main(clear=True) is None: + record("computation_eight_wider_than_six_vlm", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="value", tag="size") + return + # Name them so their alphabetical relation makes the 6-digit row sit above. + if not (and_create_entry("na", "Alpha6", SEC_A) + and and_create_entry("nz", "Zulu8", SEC_A, digits=8)): + record("computation_eight_wider_than_six_vlm", False, + "feature_missing: could not create a 6- and an 8-digit entry", + depth=1, jump_kind="value", tag="size") + return + vlm_assert("computation_eight_wider_than_six", + "This authenticator list has two entries. One shows a six-digit " + "code and the other shows an eight-digit code. Is the eight-digit " + "code visibly WIDER (occupies more horizontal space) than the " + "six-digit code?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="value", tag="size") + + +TESTS = [ + test_same_secret_same_code, + test_diff_secret_diff_code, + test_default_six_digits, + test_default_grouping_format, + test_digits_eight, + test_eight_grouping_format, + test_digits_contrast, + test_code_charset, + test_code_stable_in_period, + test_copy_matches_display, + test_search_matches_one, + test_search_matches_none, + test_search_case_insensitive, + test_search_present_then_absent, + test_type_default_totp, + test_digits_field_default_six, + test_period_field_default_thirty, + test_code_accent_color_vlm, + test_code_large_font_vlm, + test_code_grouped_vlm, + test_eight_wider_than_six_vlm, +] + +if __name__ == "__main__": + run_suite(TESTS, "computation") diff --git a/android/beemdevelopment-aegis/tests/test_android_interaction.py b/android/beemdevelopment-aegis/tests/test_android_interaction.py new file mode 100644 index 0000000000000000000000000000000000000000..211a6886ff2c59ccd92728e76bafa82ad3bb5c1f --- /dev/null +++ b/android/beemdevelopment-aegis/tests/test_android_interaction.py @@ -0,0 +1,907 @@ +#!/usr/bin/env python3 +"""INTERACTION lane — effect-by-consequence on user DATA for the Aegis +Authenticator app (TOTP/HOTP 2FA). Sole owner of long-press / context menus and +of DATA persistence across process death. + +Every test drives the app to Main via the portable resource-id path, performs a +data operation, and reads the consequence back out of a FRESH ui(). Nothing is +keyed on the package / paths / coordinates — the same file scores a from-scratch +recreation at a different package name. + +Run: + python3 test_android_interaction.py +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +# Distinctive markers so a read-back cannot accidentally match pre-existing data. +SEC_A = "JBSWY3DPEHPK3PXP" +SEC_B = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" + + +# ── shared plumbing ───────────────────────────────────────────────────────────── + +def _kb_off(): + """Dismiss the soft keyboard on the edit form WITHOUT navigating. + + The kit's hide_keyboard() falls back to BACK, and on EditEntryActivity BACK + raises the "Your changes have not been saved" discard dialog instead of just + lowering the keyboard — which corrupts a multi-field fill. KEYCODE_ESCAPE + lowers the IME with no navigation and no dialog (verified on the original). + """ + if keyboard_visible(): + press_key("KEYCODE_ESCAPE") + settle("keyboard") + return not keyboard_visible() + + +def and_enter_main(clear=False): + """Get to MainActivity. clear=True wipes the vault first (virgin DB). + + Runs the 4-tap onboarding skip by resource-id only, choosing rb_none so the + vault opens directly on every relaunch (no unlock screen). Returns the last + fresh node list, or None if Main was never reached. + """ + if clear: + clear_data() + restart_app() + wait_for_foreground() + n = ui() + if node_by_id(n, "btnNext"): + for rid in ("btnNext", "rb_none", "btnNext", "btnNext"): + t = node_by_id(n, rid) + if t is None or not tap_node(t): + return None + n = ui() + if node_by_id(n, "fab") is None: + return None + return n + + +def _count_text(nodes=None): + nodes = ui() if nodes is None else nodes + c = node_by_id(nodes, "entries_shown_count") + return (c or {}).get("text") + + +def _issuers(nodes=None): + """Top-to-bottom list of profile_issuer strings currently shown.""" + nodes = ui() if nodes is None else nodes + rows = [(x["_bounds"][1], x.get("text", "")) + for x in nodes + if x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_issuer" + and "_bounds" in x] + return [t for _y, t in sorted(rows)] + + +def and_enter_editor(): + """Main -> FAB menu -> Enter manually -> EditEntryActivity. Backs depth via + the and_enter_* NAME + an and_enter() call once the surface changes.""" + n = ui() + fab = node_by_id(n, "fab") + if fab is None or not tap_node(fab): + return False + n = ui() + enter = node_by_id(n, "fab_menu_item_enter") + if enter is None or not tap_node(enter): + return False + settle("tap") + if not get_current_activity().endswith("EditEntryActivity"): + return False + and_enter("editor") + return True + + +def and_create_entry(name, issuer, secret): + """FAB -> Enter manually -> fill name/issuer/secret -> SAVE. Returns True only + when we land back on Main with the new issuer visible. Robust: re-dumps after + every field, lowers the keyboard between fields (secret sits below it), and + handles the discard/error dialogs.""" + if not and_enter_editor(): + return False + n = ui() + nm = node_by_id(n, "text_name") + if nm is None or not type_text(nm, name): + return False + _kb_off() + n = ui() + iss = node_by_id(n, "text_issuer") + if iss is None or not type_text(iss, issuer): + return False + _kb_off() + n = ui() + sec = node_by_id(n, "text_secret") + if sec is None or not type_text(sec, secret): + return False + _kb_off() + n = ui() + save = node_by_id(n, "action_save") + if save is None or not tap_node(save): + return False + n = ui() + if find_node_ci(n, "Error saving profile"): + return False + if find_node_ci(n, "Your changes have not been saved"): + sv = find_node(n, text="Save") + if sv: + tap_node(sv) + n = ui() + if not get_current_activity().endswith("MainActivity"): + return False + return find_node_ci(ui(), issuer) is not None + + +def and_open_action_mode(issuer=None): + """Long-press a row (the one with `issuer`, else the first) to enter the + contextual action mode. Returns True once action_mode_close_button appears.""" + n = ui() + row = None + if issuer: + for x in n: + if (x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_issuer" + and x.get("text") == issuer): + row = x + break + if row is None: + row = node_by_id(n, "profile_issuer") + if row is None or not long_press(row): + return False + settle("tap") + if node_by_id(ui(), "action_mode_close_button") is None: + return False + and_enter("action_mode") + return True + + +def _exit_action_mode(): + n = ui() + done = node_by_id(n, "action_mode_close_button") + if done: + tap_node(done) + + +def _clear_and_type(node, rid, val): + """Clear an EditText (select-to-end + delete) then type `val`. No BACK.""" + if not tap_node(node): + return False + settle("keyboard") + press_key("KEYCODE_MOVE_END") + for _ in range(24): + press_key("KEYCODE_DEL") + settle("text") + fresh = node_by_id(ui(), rid) + if fresh is None: + return False + return type_text(fresh, val) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1. Create entry -> count increments AND issuer appears +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_create_entry",)) +def test_create_entry(): + if and_enter_main(clear=True) is None: + record("interaction_create_entry", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="value", expect="Showing 1 entry + issuer 'iCreate'") + return + absent = find_node_ci(ui(), "iCreate") is None and _count_text() is None + if not and_create_entry("nCreate", "iCreate", SEC_A): + record("interaction_create_entry", False, + "feature_missing: could not create an entry via FAB/Enter-manually", + depth=1, jump_kind="value", expect="Showing 1 entry + issuer 'iCreate'") + return + n = ui() + present = find_node_ci(n, "iCreate") is not None + cnt = _count_text(n) + ok = absent and present and cnt == "Showing 1 entry" + record("interaction_create_entry", ok, + "" if ok else f"behavior_wrong: after create count={cnt!r} " + f"issuer_present={present} (expected 'Showing 1 entry')", + depth=1, jump_kind="value", expect="Showing 1 entry + issuer 'iCreate'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2. Create then read back -> count flips absent -> present (transition) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_create_absent_then_present",)) +def test_create_absent_then_present(): + if and_enter_main(clear=True) is None: + record("interaction_create_absent_then_present", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="transition", expect="issuer 'iFlip' absent->present") + return + before = find_node_ci(ui(), "iFlip") is not None + if not and_create_entry("nFlip", "iFlip", SEC_A): + record("interaction_create_absent_then_present", False, + "feature_missing: could not create an entry", + depth=1, jump_kind="transition", expect="issuer 'iFlip' absent->present") + return + after = find_node_ci(ui(), "iFlip") is not None + ok = (not before) and after + record("interaction_create_absent_then_present", ok, + "" if ok else f"behavior_wrong: iFlip before={before} after={after}", + depth=1, jump_kind="transition", expect="issuer 'iFlip' absent->present") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3. Multi-record integrity: create 2 -> both present AND "Showing 2 entries" +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_multi_two_entries",)) +def test_multi_two_entries(): + if and_enter_main(clear=True) is None: + record("interaction_multi_two_entries", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="value", expect="Showing 2 entries + iMultiA + iMultiB") + return + if not and_create_entry("nMultiA", "iMultiA", SEC_A): + record("interaction_multi_two_entries", False, + "feature_missing: could not create the first entry", + depth=1, jump_kind="value", expect="Showing 2 entries + iMultiA + iMultiB") + return + if not and_create_entry("nMultiB", "iMultiB", SEC_A): + record("interaction_multi_two_entries", False, + "behavior_wrong: could not create the second entry", + depth=1, jump_kind="value", expect="Showing 2 entries + iMultiA + iMultiB") + return + n = ui() + both = find_node_ci(n, "iMultiA") is not None and find_node_ci(n, "iMultiB") is not None + cnt = _count_text(n) + ok = both and cnt == "Showing 2 entries" + record("interaction_multi_two_entries", ok, + "" if ok else f"behavior_wrong: both_present={both} count={cnt!r} " + f"(expected 'Showing 2 entries')", + depth=1, jump_kind="value", expect="Showing 2 entries + iMultiA + iMultiB") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4. Multi-record integrity across an EDIT of the middle row (recreation killer: +# an app that rebuilds the whole list keeping one row fails here) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_edit_middle_keeps_others",)) +def test_edit_middle_keeps_others(): + if and_enter_main(clear=True) is None: + record("interaction_edit_middle_keeps_others", False, + "setup_failed: could not reach MainActivity", + depth=2, jump_kind="value", expect="rows [iOne, iTwoEDIT, iThree]") + return + for nm, iss in (("n1", "iOne"), ("n2", "iTwo"), ("n3", "iThree")): + if not and_create_entry(nm, iss, SEC_A): + record("interaction_edit_middle_keeps_others", False, + f"feature_missing: could not create {iss}", + depth=2, jump_kind="value", expect="rows [iOne, iTwoEDIT, iThree]") + return + # Edit the middle row (iTwo) -> issuer iTwoEDIT. + if not and_open_action_mode("iTwo"): + record("interaction_edit_middle_keeps_others", False, + "feature_missing: long-press did not open action mode on iTwo", + depth=2, jump_kind="value", expect="rows [iOne, iTwoEDIT, iThree]") + return + n = ui() + ed = node_by_id(n, "action_edit") + if ed is None or not tap_node(ed): + record("interaction_edit_middle_keeps_others", False, + "feature_missing: no Edit control in action mode", + depth=2, jump_kind="value", expect="rows [iOne, iTwoEDIT, iThree]") + return + and_enter("editor") + n = ui() + iss = node_by_id(n, "text_issuer") + if iss is None or not _clear_and_type(iss, "text_issuer", "iTwoEDIT"): + record("interaction_edit_middle_keeps_others", False, + "behavior_wrong: could not change the issuer field", + depth=2, jump_kind="value", expect="rows [iOne, iTwoEDIT, iThree]") + return + n = ui() + save = node_by_id(n, "action_save") + tap_node(save) + n = ui() + if find_node_ci(n, "Your changes have not been saved"): + tap_node(find_node(n, text="Save")) + n = ui() + isr = _issuers(n) + ok = ("iOne" in isr and "iThree" in isr and "iTwoEDIT" in isr + and "iTwo" not in isr and len(isr) == 3) + record("interaction_edit_middle_keeps_others", ok, + "" if ok else f"behavior_wrong: rows after middle edit = {isr!r} " + f"(expected iOne, iTwoEDIT, iThree)", + depth=2, jump_kind="value", expect="rows [iOne, iTwoEDIT, iThree]") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5. Long-press -> contextual ACTION MODE controls appear (transition) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_longpress_action_mode",)) +def test_longpress_action_mode(): + if and_enter_main(clear=True) is None or not and_create_entry("nLP", "iLP", SEC_A): + record("interaction_longpress_action_mode", False, + "setup_failed: could not create an entry to long-press", + depth=1, jump_kind="transition", + expect="Done/Copy/Edit/Favorite appear (absent before)") + return + n = ui() + # Before: none of the action-mode controls present. + before = all(node_by_id(n, r) is None for r in + ("action_mode_close_button", "action_copy", "action_edit", + "action_toggle_favorite")) + if not and_open_action_mode("iLP"): + record("interaction_longpress_action_mode", False, + "feature_missing: long-press did not open action mode", + depth=1, jump_kind="transition", + expect="Done/Copy/Edit/Favorite appear (absent before)") + return + n = ui() + got = [r for r in ("action_mode_close_button", "action_copy", "action_edit", + "action_toggle_favorite", "action_share_qr") + if node_by_id(n, r) is not None] + ok = before and len(got) >= 4 + _exit_action_mode() + record("interaction_longpress_action_mode", ok, + "" if ok else f"behavior_wrong: action-mode controls before_absent={before} " + f"present_now={got}", + depth=1, jump_kind="transition", + expect="Done/Copy/Edit/Favorite appear (absent before)") + + +# VLM #1: long-press selection highlight (color) +@and_test(expects=("interaction_longpress_highlight_vlm",)) +def test_longpress_highlight_vlm(): + if and_enter_main(clear=True) is None or not and_create_entry("nHL", "iHL", SEC_A): + record("interaction_longpress_highlight_vlm", False, + "setup_failed: could not create an entry to long-press", + depth=1, jump_kind="transition", tag="color") + return + if not and_open_action_mode("iHL"): + record("interaction_longpress_highlight_vlm", False, + "feature_missing: long-press did not open action mode", + depth=1, jump_kind="transition", tag="color") + return + vlm_assert("interaction_longpress_highlight", + "A single entry row in this authenticator list is long-press " + "selected. Is exactly one list row visually highlighted with a " + "different (tinted/darker) background colour than the rest of the " + "screen?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", tag="color") + _exit_action_mode() + + +# ══════════════════════════════════════════════════════════════════════════════ +# 6. Action-mode overflow -> Select all / Assign to group / Delete appear (reach) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_context_more_menu",)) +def test_context_more_menu(): + if and_enter_main(clear=True) is None or not and_create_entry("nCM", "iCM", SEC_A): + record("interaction_context_more_menu", False, + "setup_failed: could not create an entry", + depth=2, jump_kind="reach", + expect="menu 'Select all'/'Assign to group'/'Delete'") + return + if not and_open_action_mode("iCM"): + record("interaction_context_more_menu", False, + "feature_missing: long-press did not open action mode", + depth=2, jump_kind="reach", + expect="menu 'Select all'/'Assign to group'/'Delete'") + return + n = ui() + mo = find_node(n, content_desc="More options") + before = and_showing(n) + if mo is None or not tap_node(mo): + record("interaction_context_more_menu", False, + "feature_missing: no More-options overflow in action mode", + depth=2, jump_kind="reach", + expect="menu 'Select all'/'Assign to group'/'Delete'") + return + and_enter("context_menu") + n = ui() + after = and_showing(n) + items = [t for t in ("Select all", "Assign to group", "Delete") + if find_node_ci(n, t) is not None] + reached = and_reach(before, after, "Select all") + ok = reached and len(items) >= 2 and "Delete" in items + # Close the menu without tapping any destructive item. + back() + _exit_action_mode() + record("interaction_context_more_menu", ok, + "" if ok else f"behavior_wrong: overflow items={items} reached={reached}", + depth=2, jump_kind="reach", + expect="menu 'Select all'/'Assign to group'/'Delete'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 7. Edit entry: prefilled -> change name -> SAVE -> row shows NEW name, old gone +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_edit_prefilled",)) +def test_edit_prefilled(): + if and_enter_main(clear=True) is None or not and_create_entry("nEd", "iEdOLD", SEC_A): + record("interaction_edit_prefilled", False, + "setup_failed: could not create an entry to edit", + depth=2, jump_kind="value", expect="editor prefilled issuer 'iEdOLD'") + return + if not and_open_action_mode("iEdOLD"): + record("interaction_edit_prefilled", False, + "feature_missing: long-press did not open action mode", + depth=2, jump_kind="value", expect="editor prefilled issuer 'iEdOLD'") + return + n = ui() + ed = node_by_id(n, "action_edit") + if ed is None or not tap_node(ed): + record("interaction_edit_prefilled", False, + "feature_missing: no Edit control in action mode", + depth=2, jump_kind="value", expect="editor prefilled issuer 'iEdOLD'") + return + and_enter("editor") + n = ui() + # Prefilled check: the editor's issuer field equals what we created. + prefilled_iss = (node_by_id(n, "text_issuer") or {}).get("text") + prefilled_nm = (node_by_id(n, "text_name") or {}).get("text") + ok = prefilled_iss == "iEdOLD" and prefilled_nm == "nEd" + record("interaction_edit_prefilled", ok, + "" if ok else f"behavior_wrong: editor prefilled issuer={prefilled_iss!r} " + f"name={prefilled_nm!r} (expected 'iEdOLD'/'nEd')", + depth=2, jump_kind="value", expect="editor prefilled issuer 'iEdOLD'") + + +@and_test(expects=("interaction_edit_saves_new_name",)) +def test_edit_saves_new_name(): + if and_enter_main(clear=True) is None or not and_create_entry("nEd2", "iEdA", SEC_A): + record("interaction_edit_saves_new_name", False, + "setup_failed: could not create an entry to edit", + depth=2, jump_kind="value", expect="row issuer 'iEdB' present, 'iEdA' gone") + return + if not and_open_action_mode("iEdA"): + record("interaction_edit_saves_new_name", False, + "feature_missing: long-press did not open action mode", + depth=2, jump_kind="value", expect="row issuer 'iEdB' present, 'iEdA' gone") + return + n = ui() + ed = node_by_id(n, "action_edit") + if ed is None or not tap_node(ed): + record("interaction_edit_saves_new_name", False, + "feature_missing: no Edit control in action mode", + depth=2, jump_kind="value", expect="row issuer 'iEdB' present, 'iEdA' gone") + return + and_enter("editor") + n = ui() + iss = node_by_id(n, "text_issuer") + if iss is None or not _clear_and_type(iss, "text_issuer", "iEdB"): + record("interaction_edit_saves_new_name", False, + "behavior_wrong: could not change the issuer field", + depth=2, jump_kind="value", expect="row issuer 'iEdB' present, 'iEdA' gone") + return + n = ui() + tap_node(node_by_id(n, "action_save")) + n = ui() + if find_node_ci(n, "Your changes have not been saved"): + tap_node(find_node(n, text="Save")) + n = ui() + new_present = find_node_ci(n, "iEdB") is not None + old_gone = find_node_ci(n, "iEdA") is None + ok = new_present and old_gone and get_current_activity().endswith("MainActivity") + record("interaction_edit_saves_new_name", ok, + "" if ok else f"behavior_wrong: iEdB_present={new_present} iEdA_gone={old_gone}", + depth=2, jump_kind="value", expect="row issuer 'iEdB' present, 'iEdA' gone") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 8. Favorite toggle: favoriting the BOTTOM entry pins it to the TOP (value) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_favorite_pins_top",)) +def test_favorite_pins_top(): + if and_enter_main(clear=True) is None: + record("interaction_favorite_pins_top", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="value", expect="favorited iFavC becomes first row") + return + for nm, iss in (("na", "iFavA"), ("nb", "iFavB"), ("nc", "iFavC")): + if not and_create_entry(nm, iss, SEC_A): + record("interaction_favorite_pins_top", False, + f"feature_missing: could not create {iss}", + depth=1, jump_kind="value", expect="favorited iFavC becomes first row") + return + order0 = _issuers() + if not order0 or order0[0] == "iFavC": + # Need iFavC NOT already first for the pin to be observable. + record("interaction_favorite_pins_top", False, + f"setup_failed: unexpected initial order {order0!r}", + depth=1, jump_kind="value", expect="favorited iFavC becomes first row") + return + if not and_open_action_mode("iFavC"): + record("interaction_favorite_pins_top", False, + "feature_missing: long-press did not open action mode", + depth=1, jump_kind="value", expect="favorited iFavC becomes first row") + return + n = ui() + fav = node_by_id(n, "action_toggle_favorite") + if fav is None or not tap_node(fav): + record("interaction_favorite_pins_top", False, + "feature_missing: no Favorite toggle in action mode", + depth=1, jump_kind="value", expect="favorited iFavC becomes first row") + return + _exit_action_mode() + order1 = _issuers() + ok = bool(order1) and order1[0] == "iFavC" and set(order1) == set(order0) + record("interaction_favorite_pins_top", ok, + "" if ok else f"behavior_wrong: order before={order0!r} after favorite={order1!r} " + f"(expected iFavC first)", + depth=1, jump_kind="value", expect="favorited iFavC becomes first row") + + +# VLM #2: favorite star/indicator rendering (shape) +@and_test(expects=("interaction_favorite_marker_vlm",)) +def test_favorite_marker_vlm(): + if and_enter_main(clear=True) is None or not and_create_entry("nfm", "iFavM", SEC_A): + record("interaction_favorite_marker_vlm", False, + "setup_failed: could not create an entry to favorite", + depth=1, jump_kind="transition", tag="shape") + return + if not and_open_action_mode("iFavM"): + record("interaction_favorite_marker_vlm", False, + "feature_missing: long-press did not open action mode", + depth=1, jump_kind="transition", tag="shape") + return + n = ui() + fav = node_by_id(n, "action_toggle_favorite") + if fav is None or not tap_node(fav): + record("interaction_favorite_marker_vlm", False, + "feature_missing: no Favorite toggle in action mode", + depth=1, jump_kind="transition", tag="shape") + return + _exit_action_mode() + vlm_assert("interaction_favorite_marker", + "One entry in this authenticator list was just marked as a " + "favorite. Is there a small star-shaped indicator (a star icon or " + "a coloured vertical bar) marking one of the entry rows as " + "favorited?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", tag="shape") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 9. PERSISTENCE across process death — the key in-memory-shell killer (value) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_persist_single",)) +def test_persist_single(): + if and_enter_main(clear=True) is None or not and_create_entry("nPersist", "iPersist", SEC_A): + record("interaction_persist_single", False, + "setup_failed: could not create an entry to persist", + depth=0, jump_kind="value", expect="issuer 'iPersist' + Showing 1 entry after relaunch") + return + cnt_before = _count_text() + force_stop_and_relaunch() + wait_for_foreground() + n = ui() + # rb_none means no unlock; data persisted means no onboarding either. + present = find_node_ci(n, "iPersist") is not None + cnt_after = _count_text(n) + ok = present and cnt_after == "Showing 1 entry" and cnt_before == cnt_after + record("interaction_persist_single", ok, + "" if ok else f"behavior_wrong: after process death issuer_present={present} " + f"count={cnt_after!r} (expected 'Showing 1 entry')", + depth=0, jump_kind="value", + expect="issuer 'iPersist' + Showing 1 entry after relaunch") + + +@and_test(expects=("interaction_persist_multi_integrity",)) +def test_persist_multi_integrity(): + if and_enter_main(clear=True) is None: + record("interaction_persist_multi_integrity", False, + "setup_failed: could not reach MainActivity", + depth=0, jump_kind="value", + expect="rows [iPa, iPb, iPc] + Showing 3 entries after relaunch") + return + for nm, iss in (("npa", "iPa"), ("npb", "iPb"), ("npc", "iPc")): + if not and_create_entry(nm, iss, SEC_A): + record("interaction_persist_multi_integrity", False, + f"feature_missing: could not create {iss}", + depth=0, jump_kind="value", + expect="rows [iPa, iPb, iPc] + Showing 3 entries after relaunch") + return + force_stop_and_relaunch() + wait_for_foreground() + n = ui() + isr = set(_issuers(n)) + cnt = _count_text(n) + ok = {"iPa", "iPb", "iPc"} <= isr and cnt == "Showing 3 entries" + record("interaction_persist_multi_integrity", ok, + "" if ok else f"behavior_wrong: after death issuers={sorted(isr)} count={cnt!r} " + f"(expected iPa/iPb/iPc + 'Showing 3 entries')", + depth=0, jump_kind="value", + expect="rows [iPa, iPb, iPc] + Showing 3 entries after relaunch") + + +@and_test(expects=("interaction_edit_persists",)) +def test_edit_persists(): + """An edit must survive process death, not just live in memory.""" + if and_enter_main(clear=True) is None or not and_create_entry("nep", "iEpOLD", SEC_A): + record("interaction_edit_persists", False, + "setup_failed: could not create an entry to edit", + depth=0, jump_kind="value", expect="issuer 'iEpNEW' after relaunch, 'iEpOLD' gone") + return + if not and_open_action_mode("iEpOLD"): + record("interaction_edit_persists", False, + "feature_missing: long-press did not open action mode", + depth=0, jump_kind="value", expect="issuer 'iEpNEW' after relaunch, 'iEpOLD' gone") + return + n = ui() + ed = node_by_id(n, "action_edit") + if ed is None or not tap_node(ed): + record("interaction_edit_persists", False, + "feature_missing: no Edit control in action mode", + depth=0, jump_kind="value", expect="issuer 'iEpNEW' after relaunch, 'iEpOLD' gone") + return + n = ui() + iss = node_by_id(n, "text_issuer") + if iss is None or not _clear_and_type(iss, "text_issuer", "iEpNEW"): + record("interaction_edit_persists", False, + "behavior_wrong: could not change the issuer field", + depth=0, jump_kind="value", expect="issuer 'iEpNEW' after relaunch, 'iEpOLD' gone") + return + n = ui() + tap_node(node_by_id(n, "action_save")) + n = ui() + if find_node_ci(n, "Your changes have not been saved"): + tap_node(find_node(n, text="Save")) + force_stop_and_relaunch() + wait_for_foreground() + n = ui() + new_present = find_node_ci(n, "iEpNEW") is not None + old_gone = find_node_ci(n, "iEpOLD") is None + ok = new_present and old_gone + record("interaction_edit_persists", ok, + "" if ok else f"behavior_wrong: after death iEpNEW_present={new_present} " + f"iEpOLD_gone={old_gone}", + depth=0, jump_kind="value", expect="issuer 'iEpNEW' after relaunch, 'iEpOLD' gone") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 10. Cancel / discard create -> no phantom row, count unchanged (transition) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_cancel_create_no_phantom",)) +def test_cancel_create_no_phantom(): + if and_enter_main(clear=True) is None or not and_create_entry("nseed", "iSeed", SEC_A): + record("interaction_cancel_create_no_phantom", False, + "setup_failed: could not seed one entry", + depth=1, jump_kind="transition", expect="count stays 'Showing 1 entry', no iPhantom") + return + cnt0 = _count_text() + if not and_enter_editor(): + record("interaction_cancel_create_no_phantom", False, + "feature_missing: could not open the create form", + depth=1, jump_kind="transition", expect="count stays 'Showing 1 entry', no iPhantom") + return + n = ui() + type_text(node_by_id(n, "text_issuer"), "iPhantom") + _kb_off() + # BACK without saving -> discard dialog -> Discard. + back() + n = ui() + if find_node_ci(n, "Your changes have not been saved"): + d = find_node(n, text="Discard") + if d: + tap_node(d) + n = ui() + cnt1 = _count_text(n) + phantom = find_node_ci(ui(), "iPhantom") is not None + ok = (cnt0 == cnt1 == "Showing 1 entry") and not phantom \ + and get_current_activity().endswith("MainActivity") + record("interaction_cancel_create_no_phantom", ok, + "" if ok else f"behavior_wrong: count {cnt0!r}->{cnt1!r} phantom_present={phantom}", + depth=1, jump_kind="transition", expect="count stays 'Showing 1 entry', no iPhantom") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 11. Long-press action mode dismisses cleanly via Done (transition) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_action_mode_done_exits",)) +def test_action_mode_done_exits(): + if and_enter_main(clear=True) is None or not and_create_entry("ndn", "iDone", SEC_A): + record("interaction_action_mode_done_exits", False, + "setup_failed: could not create an entry", + depth=1, jump_kind="transition", expect="action mode -> Done -> back to list") + return + if not and_open_action_mode("iDone"): + record("interaction_action_mode_done_exits", False, + "feature_missing: long-press did not open action mode", + depth=1, jump_kind="transition", expect="action mode -> Done -> back to list") + return + before = and_showing() + n = ui() + done = node_by_id(n, "action_mode_close_button") + if done is None or not tap_node(done): + record("interaction_action_mode_done_exits", False, + "feature_missing: no Done control to leave action mode", + depth=1, jump_kind="transition", expect="action mode -> Done -> back to list") + return + after = and_showing() + # Done DISAPPEARED and the FAB (plain-list affordance) is back. + gone = node_by_id(ui(), "action_mode_close_button") is None + fab_back = node_by_id(ui(), "fab") is not None + ok = gone and fab_back and surface_changed(before, after) + record("interaction_action_mode_done_exits", ok, + "" if ok else f"behavior_wrong: done_gone={gone} fab_back={fab_back}", + depth=1, jump_kind="transition", expect="action mode -> Done -> back to list") + + +# ══════════════════════════════════════════════════════════════════════════════ +# ── VLM cluster: rendered per-row / per-surface properties (distinct fine tags) ─ +# All questions were authored from screenshots captured on the running original. +# ══════════════════════════════════════════════════════════════════════════════ + +# VLM #3 — avatar tile is a circle (shape) +@and_test(expects=("interaction_row_avatar_vlm",)) +def test_row_avatar_vlm(): + if and_enter_main(clear=True) is None or not and_create_entry("nAv", "Zebra", SEC_A): + record("interaction_row_avatar_vlm", False, + "setup_failed: could not create an entry", + depth=0, jump_kind="none", tag="shape") + return + vlm_assert("interaction_row_avatar", + "In this authenticator list, does the entry whose issuer is " + "'Zebra' have a round circular avatar tile on its left side " + "(a coloured circle, typically showing a letter)?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="none", tag="shape") + + +# VLM #4 — avatar shows the issuer's first letter (content) +@and_test(expects=("interaction_row_avatar_letter_vlm",)) +def test_row_avatar_letter_vlm(): + if and_enter_main(clear=True) is None or not and_create_entry("nQ", "Quartz", SEC_A): + record("interaction_row_avatar_letter_vlm", False, + "setup_failed: could not create an entry", + depth=0, jump_kind="none", tag="content") + return + vlm_assert("interaction_row_avatar_letter", + "The single entry in this authenticator list has issuer 'Quartz'. " + "Does its round avatar tile on the left contain the capital letter " + "'Q' (the first letter of the issuer)?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="none", tag="content") + + +# VLM #5 — each entry sits inside its own rounded card (shape) +@and_test(expects=("interaction_row_card_shape_vlm",)) +def test_row_card_shape_vlm(): + if and_enter_main(clear=True) is None or not and_create_entry("nCard", "iCard", SEC_A): + record("interaction_row_card_shape_vlm", False, + "setup_failed: could not create an entry", + depth=0, jump_kind="none", tag="shape") + return + vlm_assert("interaction_row_card_shape", + "In this authenticator list, is the single entry drawn inside its " + "own rounded-corner rectangular card/tile whose fill colour differs " + "from the plain page background around it?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="none", tag="shape") + + +# VLM #6 — TOTP code digits are a solid accent colour (color) +@and_test(expects=("interaction_row_code_color_vlm",)) +def test_row_code_color_vlm(): + if and_enter_main(clear=True) is None or not and_create_entry("nCol", "iCol", SEC_A): + record("interaction_row_code_color_vlm", False, + "setup_failed: could not create an entry", + depth=0, jump_kind="none", tag="color") + return + vlm_assert("interaction_row_code_color", + "Look at the large TOTP code digits on the entry row. Are the code " + "digits rendered in a single solid colour (a coloured accent such " + "as red/green/blue) rather than plain black or grey body text?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="none", tag="color") + + +# VLM #7 — FAB menu options stack above the FAB (position) +@and_test(expects=("interaction_fab_menu_layout_vlm",)) +def test_fab_menu_layout_vlm(): + if and_enter_main(clear=True) is None: + record("interaction_fab_menu_layout_vlm", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="transition", tag="position") + return + n = ui() + fab = node_by_id(n, "fab") + if fab is None or not tap_node(fab): + record("interaction_fab_menu_layout_vlm", False, + "feature_missing: FAB not tappable", + depth=1, jump_kind="transition", tag="position") + return + and_enter("fab_menu") + # confirm the menu opened before asking the VLM + if node_by_id(ui(), "fab_menu_item_enter") is None: + record("interaction_fab_menu_layout_vlm", False, + "feature_missing: FAB menu did not expand", + depth=1, jump_kind="transition", tag="position") + return + vlm_assert("interaction_fab_menu_layout", + "The add-entry menu is open. Are its options stacked vertically as " + "a column of labelled items positioned above the floating action " + "button in the bottom-right area of the screen?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", tag="position") + back() + + +# VLM #8 — action bar shows a horizontal row of icons (layout) +@and_test(expects=("interaction_action_toolbar_layout_vlm",)) +def test_action_toolbar_layout_vlm(): + if and_enter_main(clear=True) is None or not and_create_entry("nTb", "iTb", SEC_A): + record("interaction_action_toolbar_layout_vlm", False, + "setup_failed: could not create an entry", + depth=1, jump_kind="transition", tag="layout") + return + if not and_open_action_mode("iTb"): + record("interaction_action_toolbar_layout_vlm", False, + "feature_missing: long-press did not open action mode", + depth=1, jump_kind="transition", tag="layout") + return + # NOTE: the vlm_assert name MUST equal the declared expects (minus the _vlm + # suffix the kit appends) or the record drifts the denominator. + vlm_assert("interaction_action_toolbar_layout", + "The contextual action bar is showing at the top after a " + "long-press. Does the top bar display a horizontal row of several " + "action icons (such as copy, edit, favourite, share/QR)?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", tag="layout") + _exit_action_mode() + + +# VLM #9 — after process death, list is NOT in selection mode (color) +@and_test(expects=("interaction_persist_highlight_gone_vlm",)) +def test_persist_highlight_gone_vlm(): + """After process death the list is NOT in selection mode: no row highlighted. + A rendered-state check that complements the rule persistence tests.""" + if and_enter_main(clear=True) is None or not and_create_entry("nph", "iPH", SEC_A): + record("interaction_persist_highlight_gone_vlm", False, + "setup_failed: could not create an entry", + depth=0, jump_kind="value", tag="color") + return + force_stop_and_relaunch() + wait_for_foreground() + if node_by_id(ui(), "fab") is None: + record("interaction_persist_highlight_gone_vlm", False, + "behavior_wrong: not on the entry list after relaunch", + depth=0, jump_kind="value", tag="color") + return + vlm_assert("interaction_persist_highlight_gone", + "This authenticator list was just relaunched from a killed " + "process. Is the list in its normal state with NO row highlighted " + "or selected (i.e. every row shares the same background colour)?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="color") + + +TESTS = [ + test_create_entry, + test_create_absent_then_present, + test_multi_two_entries, + test_edit_middle_keeps_others, + test_longpress_action_mode, + test_longpress_highlight_vlm, + test_context_more_menu, + test_edit_prefilled, + test_edit_saves_new_name, + test_favorite_pins_top, + test_favorite_marker_vlm, + test_persist_single, + test_persist_multi_integrity, + test_edit_persists, + test_cancel_create_no_phantom, + test_action_mode_done_exits, + test_row_avatar_vlm, + test_row_avatar_letter_vlm, + test_row_card_shape_vlm, + test_row_code_color_vlm, + test_fab_menu_layout_vlm, + test_action_toolbar_layout_vlm, + test_persist_highlight_gone_vlm, +] + +if __name__ == "__main__": + run_suite(TESTS, "interaction") diff --git a/android/beemdevelopment-aegis/tests/test_android_navigation.py b/android/beemdevelopment-aegis/tests/test_android_navigation.py new file mode 100644 index 0000000000000000000000000000000000000000..b6ad16c134941899298cfbb2bfb5059166a970a0 --- /dev/null +++ b/android/beemdevelopment-aegis/tests/test_android_navigation.py @@ -0,0 +1,526 @@ +#!/usr/bin/env python3 +"""NAVIGATION lane — surface REACHABILITY + back-stack integrity for Aegis +Authenticator (TOTP/2FA). Sole owner of jump_kind="reach" and of depth>=2 chains. + +Every jump is proven by and_reach(before, after, target, source): the TARGET +surface's discriminating element APPEARED and the SOURCE surface's element +DISAPPEARED. No element that was already in the tree is ever asserted as a +"reach". Reaching a screen by relaunching is NOT navigation — every chain +navigates from within the app via and_enter*/and_reach* calls that back the +declared depth. + +Discriminators were read off the running app (uiautomator dump), because a +surface here is the SET of visible element keys, not the Activity: + * Main toolbar title .......... 'AegisDev' + * Overflow popup items ........ 'Settings', 'About' (Main toolbar not in tree) + * PreferencesActivity root .... title 'Settings' + 'Navigate up' + category rows + * A settings SUB-screen ....... the 'Settings' title is REPLACED by the section + title, so 'Settings' leaving + a section-only + child appearing proves the deeper jump + * Search active ............... 'Clear query' appears, 'AegisDev' leaves + * FAB menu (overlay) .......... 'Enter manually' appears, 'AegisDev' stays + * Add / Edit entry ............ title 'Add new entry' / 'Edit entry', 'AegisDev' gone + +Run: + python3 test_android_navigation.py +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 + + +# ══════════════════════════════════════════════════════════════════════════════ +# Entry-point + shared navigation helpers. +# The and_enter_() / and_reach_() NAMES are what the depth audit +# looks for to back a depth>=1 / jump_kind="reach"; the implementations are ours. +# ══════════════════════════════════════════════════════════════════════════════ + +def and_enter_main(): + """Clean launch to MainActivity. Clears data so onboarding is deterministic, + then skips it entirely by resource-id (portable to the recreation). Chooses + rb_none so the vault never locks and every restart lands on Main.""" + clear_data() + launch_app() + wait_for_foreground() + settle("launch") + nodes = ui() + if node_by_id(nodes, "btnNext"): + tap_node(node_by_id(ui(), "btnNext")) # Welcome -> Security + tap_node(node_by_id(ui(), "rb_none")) # None = no password + tap_node(node_by_id(ui(), "btnNext")) # Security -> Setup completed + tap_node(node_by_id(ui(), "btnNext")) # Setup completed -> Main + return ui() + + +def on_main(nodes=None): + """True iff the Main entry list is showing (toolbar title 'AegisDev').""" + nodes = ui() if nodes is None else nodes + return find_node(nodes, text="AegisDev") is not None + + +def on_settings_root(nodes=None): + """True iff the Settings ROOT is showing: the 'Settings' title is present and + at least two category rows are visible (a sub-screen shows neither).""" + nodes = ui() if nodes is None else nodes + return (find_node(nodes, text="Settings") is not None + and find_node_ci(nodes, "Behavior") is not None + and find_node_ci(nodes, "Security") is not None) + + +def _esc_hide_keyboard(): + """Dismiss the soft keyboard WITHOUT navigating. KEYCODE_ESCAPE closes the + IME on this build but never pops the surface (BACK sometimes does), which the + add-entry form is sensitive to.""" + if keyboard_visible(): + press_key("KEYCODE_ESCAPE") + settle("keyboard") + + +def _fill_field(rid, text): + """Focus an EditText by resource-id suffix and type ASCII into it, then drop + the keyboard. Re-dumps to verify focus (an unfocused field swallows input).""" + node = node_by_id(ui(), rid) + if not node: + return False + tap_node(node) + settle("keyboard") + fresh = node_by_id(ui(), rid) + if fresh and fresh.get("focused") != "true": + tap_node(fresh) + settle("keyboard") + adb_shell("input", "text", text) + settle("text") + _esc_hide_keyboard() + return True + + +def create_entry(name="TestAcc", secret="JBSWY3DPEHPK3PXP"): + """Main -> FAB -> Enter manually -> fill name + secret -> SAVE. Returns True + when a row (rlCardEntry) is present on Main afterwards. This is SETUP for the + navigate-to-a-record tests; the creation itself is the interaction lane's.""" + tap_node(node_by_id(ui(), "fab")) + settle("tap") + enter = node_by_id(ui(), "fab_menu_item_enter") + if not enter or not tap_node(enter): + return False + settle("launch") + _fill_field("text_name", name) + _fill_field("text_secret", secret) + save = node_by_id(ui(), "action_save") + if not save or not tap_node(save): + return False + settle("launch") + return node_by_id(ui(), "rlCardEntry") is not None + + +def open_overflow(): + """Tap the toolbar 'More options' and return the fresh tree (the overflow + popup shows only 'Settings' and 'About'; the Main toolbar leaves the tree).""" + mo = find_node(ui(), content_desc="More options") + if mo: + tap_node(mo) + settle("tap") + return ui() + + +def and_reach_settings(): + """Main -> overflow -> Settings root. The overflow popup already contains a + 'Settings' menu item, so the ARRIVAL is proven by the PreferencesActivity's + 'Navigate up' affordance appearing and the sibling 'About' menu item leaving. + Counts one surface.""" + open_overflow() + item = find_node_ci(ui(), "Settings") + return bool(item) and and_reach_surface(item, "Navigate up", "About") + + +# Each settings section echoes its name in BOTH the root row and the sub-screen +# title, so the title is NOT a valid "appeared" key. The reliable arrival proof +# is: the root 'Settings' title LEAVES (replaced by the section title) and a +# section-ONLY child element APPEARS. These children were read off each screen. +_SECTION_CHILD = { + "Appearance": "Dynamic colors", + "Behavior": "Haptic feedback", + "Security": "Encryption", + "Audit log": "No reported events", + "Import": "Import from file", + "Backups": "Automatic backups", + "Icon packs": "No icon packs", +} + + +def and_reach_settings_section(label, child): + """From the Settings ROOT, tap a category row and prove its sub-screen + arrived: `child` (a section-only element) APPEARED and the root 'Settings' + title LEFT. `label` is matched by prefix so the entity-escaped + 'Import & Export' row resolves from 'Import'. Counts one surface.""" + trigger = None + for n in ui(): + if n.get("resource-id", "").endswith("title") and \ + n.get("text", "").lower().startswith(label.lower()): + trigger = n + break + if trigger is None: + trigger = find_node_ci(ui(), label) + if trigger is None: + return False + return and_reach_surface(trigger, child, "Settings") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Top-level destinations (depth 1) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_open_overflow_menu",)) +def test_open_overflow_menu(): + and_enter_main() + before = and_showing() # Main (no Settings/About yet) + mo = find_node(ui(), content_desc="More options") + ok = False + if mo: + tap_node(mo) + and_enter("overflow") + after = and_showing() + # The popup overlays Main; assert both items appeared and Main title left. + ok = (and_reach(before, after, "Settings", "AegisDev") + and find_node_ci(ui(), "About") is not None) + record("navigation_open_overflow_menu", ok, + "" if ok else "feature_missing: overflow menu with Settings/About not reachable", + depth=1, jump_kind="reach", + expect="Overflow popup 'Settings'/'About' appeared; Main 'AegisDev' title gone") + + +@and_test(expects=("navigation_reach_settings", "navigation_reach_settings_vlm")) +def test_reach_settings(): + and_enter_main() + ok = and_reach_settings() + record("navigation_reach_settings", ok, + "" if ok else "behavior_wrong: Settings root not reached (no 'Navigate up' / 'About' stayed)", + depth=1, jump_kind="reach", + expect="PreferencesActivity 'Navigate up' appeared; overflow 'About' item gone") + vlm_assert("navigation_reach_settings", + "Is there a back/up arrow icon at the far top-left of the top app bar " + "(to the left of the 'Settings' title)?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("navigation_reach_about", "navigation_reach_about_vlm")) +def test_reach_about(): + and_enter_main() + open_overflow() + item = find_node_ci(ui(), "About") + # From the open overflow: About screen title appears, the 'Settings' menu + # item (sibling in the popup) leaves. + ok = bool(item) and and_reach_surface(item, "Aegis Authenticator", "Settings") + record("navigation_reach_about", ok, + "" if ok else "behavior_wrong: About not reached / overflow 'Settings' item stayed", + depth=1, jump_kind="reach", + expect="AboutActivity 'Aegis Authenticator' appeared; overflow 'Settings' item gone") + vlm_assert("navigation_reach_about", + "Is there a small app logo icon immediately to the LEFT of the " + "'Aegis Authenticator' text, near the top of the screen?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("navigation_fab_menu_open", "navigation_fab_menu_open_vlm")) +def test_fab_menu_open(): + and_enter_main() + before = and_showing() + fab = node_by_id(ui(), "fab") + ok = False + if fab: + tap_node(fab) + and_enter("fab_menu") + after = and_showing() + # FAB menu is an overlay: 'AegisDev' stays, so assert the target only. + ok = (and_reach(before, after, "Enter manually") + and find_node_ci(ui(), "Scan QR code") is not None) + record("navigation_fab_menu_open", ok, + "" if ok else "feature_missing: FAB add-entry menu did not open", + depth=1, jump_kind="reach", + expect="FAB menu options 'Enter manually' and 'Scan QR code' appeared over Main") + vlm_assert("navigation_fab_menu_open", + "Are there three labelled rounded option cards ('Scan QR code', " + "'Scan image', 'Enter manually') stacked vertically in the " + "lower-right area of the screen?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("navigation_reach_add_entry", "navigation_reach_add_entry_vlm")) +def test_reach_add_entry(): + and_enter_main() + tap_node(node_by_id(ui(), "fab")) + settle("tap") + and_enter("fab_menu") + enter = node_by_id(ui(), "fab_menu_item_enter") + # FAB menu -> Enter manually IS a real surface jump: the form title appears + # and Main's 'AegisDev' (still behind the FAB overlay) leaves. + ok = bool(enter) and and_reach_surface(enter, "Add new entry", "AegisDev") + record("navigation_reach_add_entry", ok, + "" if ok else "behavior_wrong: EditEntryActivity 'Add new entry' not reached", + depth=2, jump_kind="reach", + expect="EditEntryActivity 'Add new entry' shown; Main 'AegisDev' gone") + vlm_assert("navigation_reach_add_entry", + "Is there a 'SAVE' action button in the top-right area of the top app bar?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("navigation_search_open", "navigation_search_open_vlm")) +def test_search_open(): + and_enter_main() + sb = node_by_id(ui(), "search_button") + ok = False + if sb: + before = and_showing() + tap_node(sb) + and_enter("search") + after = and_showing() + # In-toolbar SearchView: the 'Clear query' button appears, 'AegisDev' goes. + ok = and_reach(before, after, "Clear query", "AegisDev") + record("navigation_search_open", ok, + "" if ok else "behavior_wrong: in-toolbar search field did not appear", + depth=1, jump_kind="reach", + expect="SearchView 'Clear query' affordance appeared; toolbar 'AegisDev' gone") + vlm_assert("navigation_search_open", + "Does the top app bar now contain a wide text input field that spans " + "most of the bar's width (a search box)?", + RESULTS_DIR, tag="layout") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Depth-2 chains: Main -> Settings -> sub-screen (navigation lane owns depth>=2) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_reach_appearance", "navigation_reach_appearance_vlm")) +def test_reach_appearance(): + and_enter_main() + deep = and_reach_settings() # hop 1 (depth 1) + ok = deep and and_reach_settings_section("Appearance", _SECTION_CHILD["Appearance"]) + record("navigation_reach_appearance", ok, # hop 2 (depth 2) + "" if ok else "behavior_wrong: Settings->Appearance sub-screen not reached", + depth=2, jump_kind="reach", + expect="Appearance sub-screen 'Dynamic colors' appeared; Settings root title gone") + vlm_assert("navigation_reach_appearance", + "Is there a vertical list of settings rows, where each row has a " + "label with a smaller grey description line beneath it?", + RESULTS_DIR, tag="layout") + + +@and_test(expects=("navigation_reach_behavior",)) +def test_reach_behavior(): + and_enter_main() + deep = and_reach_settings() + ok = deep and and_reach_settings_section("Behavior", _SECTION_CHILD["Behavior"]) + record("navigation_reach_behavior", ok, + "" if ok else "behavior_wrong: Settings->Behavior sub-screen not reached", + depth=2, jump_kind="reach", + expect="Behavior sub-screen 'Haptic feedback' appeared; Settings root title gone") + + +@and_test(expects=("navigation_reach_security",)) +def test_reach_security(): + and_enter_main() + deep = and_reach_settings() + ok = deep and and_reach_settings_section("Security", _SECTION_CHILD["Security"]) + record("navigation_reach_security", ok, + "" if ok else "behavior_wrong: Settings->Security sub-screen not reached", + depth=2, jump_kind="reach", + expect="Security sub-screen 'Encryption' appeared; Settings root title gone") + + +@and_test(expects=("navigation_reach_audit_log",)) +def test_reach_audit_log(): + and_enter_main() + deep = and_reach_settings() + ok = deep and and_reach_settings_section("Audit log", _SECTION_CHILD["Audit log"]) + record("navigation_reach_audit_log", ok, + "" if ok else "behavior_wrong: Settings->Audit log sub-screen not reached", + depth=2, jump_kind="reach", + expect="Audit log sub-screen 'No reported events' appeared; Settings root title gone") + + +@and_test(expects=("navigation_reach_import_export",)) +def test_reach_import_export(): + and_enter_main() + deep = and_reach_settings() + # Dump text is the entity-escaped 'Import & Export'; match the row by the + # 'Import' prefix and assert the section-only 'Import from file' arrived. + ok = deep and and_reach_settings_section("Import", _SECTION_CHILD["Import"]) + record("navigation_reach_import_export", ok, + "" if ok else "behavior_wrong: Settings->Import & Export sub-screen not reached", + depth=2, jump_kind="reach", + expect="Import & Export sub-screen 'Import from file' appeared; Settings root title gone") + + +@and_test(expects=("navigation_reach_backups",)) +def test_reach_backups(): + and_enter_main() + deep = and_reach_settings() + ok = deep and and_reach_settings_section("Backups", _SECTION_CHILD["Backups"]) + record("navigation_reach_backups", ok, + "" if ok else "behavior_wrong: Settings->Backups sub-screen not reached", + depth=2, jump_kind="reach", + expect="Backups sub-screen 'Automatic backups' appeared; Settings root title gone") + + +@and_test(expects=("navigation_reach_icon_packs",)) +def test_reach_icon_packs(): + and_enter_main() + deep = and_reach_settings() + ok = deep and and_reach_settings_section("Icon packs", _SECTION_CHILD["Icon packs"]) + record("navigation_reach_icon_packs", ok, + "" if ok else "behavior_wrong: Settings->Icon packs sub-screen not reached", + depth=2, jump_kind="reach", + expect="Icon packs sub-screen 'No icon packs' appeared; Settings root title gone") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Back-stack integrity — BACK unwinds hop by hop, deepest surface back to home +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_settings_back_to_main",)) +def test_settings_back_to_main(): + and_enter_main() + deep = and_reach_settings() # depth 1 + home = False + if deep: + before = and_showing() # Settings root + and_back() # pop Settings + after = and_showing() + home = and_reach(before, after, "AegisDev", "Settings") and on_main() + record("navigation_settings_back_to_main", deep and home, + "" if deep and home else "behavior_wrong: BACK from Settings did not restore Main", + depth=1, jump_kind="reach", + expect="Main 'AegisDev' restored and 'Settings' title gone after one BACK") + + +@and_test(expects=("navigation_appearance_back_to_settings",)) +def test_appearance_back_to_settings(): + """Depth-2 chain, then ONE BACK must land on the Settings ROOT (depth 1), NOT + jump straight to Main — proves the intermediate surface is on the back stack.""" + and_enter_main() + deep = (and_reach_settings() + and and_reach_settings_section("Appearance", _SECTION_CHILD["Appearance"])) + to_settings = False + if deep: + before = and_showing() # Appearance sub-screen + and_back() # pop Appearance -> Settings root + after = and_showing() + # The 'Behavior' root row reappears; the section-only 'Dynamic colors' + # leaves; and we are provably NOT on Main. + to_settings = (and_reach(before, after, "Behavior", "Dynamic colors") + and on_settings_root() and not on_main()) + record("navigation_appearance_back_to_settings", deep and to_settings, + "" if deep and to_settings else + "behavior_wrong: BACK from Appearance did not return to the Settings root", + depth=2, jump_kind="reach", + expect="Settings root ('Behavior' row) restored after one BACK; 'Dynamic colors' gone; not Main") + + +@and_test(expects=("navigation_backstack_2hop_unwind",)) +def test_backstack_2hop_unwind(): + """Main -> Settings -> Behavior, then two BACKs unwind it hop by hop: + Behavior -> Settings root, then Settings root -> Main.""" + and_enter_main() + deep = (and_reach_settings() + and and_reach_settings_section("Behavior", _SECTION_CHILD["Behavior"])) + step1 = step2 = False + if deep: + b1 = and_showing() # Behavior sub-screen + and_back() # Behavior -> Settings root + a1 = and_showing() + # Settings root re-shows the 'Appearance' row; 'Haptic feedback' leaves. + step1 = (and_reach(b1, a1, "Appearance", "Haptic feedback") + and on_settings_root() and not on_main()) + b2 = and_showing() # Settings root + and_back() # Settings root -> Main + a2 = and_showing() + step2 = and_reach(b2, a2, "AegisDev", "Settings") and on_main() + ok = deep and step1 and step2 + record("navigation_backstack_2hop_unwind", ok, + "" if ok else "behavior_wrong: two BACKs did not unwind Behavior->Settings->Main", + depth=2, jump_kind="reach", + expect="BACK #1 restores Settings root ('Appearance' row); BACK #2 restores Main 'AegisDev'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Navigate to a record created in setup: entry -> (long-press) edit -> BACK +# ══════════════════════════════════════════════════════════════════════════════ + +def and_reach_edit_entry(): + """From Main with a row present: long-press the row -> action mode -> + action_edit -> EditEntryActivity 'Edit entry'. The Main title 'AegisDev' + persists behind the contextual bar, so it is the disappearing source once + the editor opens. Counts one surface.""" + row = node_by_id(ui(), "rlCardEntry") + if not row: + return False + long_press(row) + settle("tap") # let the action mode animate in + edit = node_by_id(ui(), "action_edit") + if not edit: + return False + return and_reach_surface(edit, "Edit entry", "AegisDev") + + +@and_test(expects=("navigation_reach_edit_entry",)) +def test_reach_edit_entry(): + and_enter_main() + made = create_entry() # SETUP (interaction lane owns it) + ok = made and and_reach_edit_entry() + record("navigation_reach_edit_entry", ok, + "" if ok else ("setup_failed: could not create an entry to edit" + if not made else + "behavior_wrong: long-press -> Edit did not reach 'Edit entry'"), + depth=1, jump_kind="reach", + expect="EditEntryActivity 'Edit entry' shown; Main 'AegisDev' gone") + + +@and_test(expects=("navigation_edit_entry_back_to_main",)) +def test_edit_entry_back_to_main(): + and_enter_main() + made = create_entry() + reached = made and and_reach_edit_entry() # depth 1 (Edit entry) + home = False + if reached: + before = and_showing() + and_back() # pop Edit entry -> Main + after = and_showing() + home = and_reach(before, after, "AegisDev", "Edit entry") and on_main() + ok = reached and home + record("navigation_edit_entry_back_to_main", ok, + "" if ok else ("setup_failed: could not reach the entry editor" + if not reached else + "behavior_wrong: BACK from 'Edit entry' did not restore Main"), + depth=1, jump_kind="reach", + expect="Main 'AegisDev' restored and 'Edit entry' gone after one BACK") + + +TESTS = [ + test_open_overflow_menu, + test_reach_settings, + test_reach_about, + test_fab_menu_open, + test_reach_add_entry, + test_search_open, + test_reach_appearance, + test_reach_behavior, + test_reach_security, + test_reach_audit_log, + test_reach_import_export, + test_reach_backups, + test_reach_icon_packs, + test_settings_back_to_main, + test_appearance_back_to_settings, + test_backstack_2hop_unwind, + test_reach_edit_entry, + test_edit_entry_back_to_main, +] + + +if __name__ == "__main__": + if not device_online(): + print("device offline — aborting") + sys.exit(2) + run_suite(TESTS, "navigation") diff --git a/android/beemdevelopment-aegis/tests/test_android_states.py b/android/beemdevelopment-aegis/tests/test_android_states.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f7d08a8c515698dcc6e3d927e0db783ccae2f8 --- /dev/null +++ b/android/beemdevelopment-aegis/tests/test_android_states.py @@ -0,0 +1,1072 @@ +#!/usr/bin/env python3 +"""STATES lane — checked/enabled/selected/focused TRANSITIONS paired with their +app-authored CONSEQUENCE, page-level state machines, and SETTINGS / mode +PERSISTENCE across process death, for the Aegis Authenticator app (TOTP/2FA). + +This lane is the SOLE owner of `checked` and of `focused`. Every test reads the +BEFORE state out of a fresh ui(), drives the user path, reads the AFTER state out +of a FRESH ui() (re-locating stale nodes with find_closest_match), asserts the +transition, AND asserts the observable consequence — a bare `checked` flip that a +framework Switch does for free is worthless, so it is always paired. + +Nothing is keyed on the package / paths / coordinates — the same file scores a +from-scratch recreation at a different package name. Every expected value was +OBSERVED on the running original. + +Run: + python3 test_android_states.py +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +SEC_A = "JBSWY3DPEHPK3PXP" + + +# ══════════════════════════════════════════════════════════════════════════════ +# Entry point + shared plumbing (own copies of the proven patterns). +# ══════════════════════════════════════════════════════════════════════════════ + +def _kb_off(): + """Lower the soft keyboard WITHOUT navigating. On EditEntryActivity BACK + raises a discard dialog, so KEYCODE_ESCAPE is used (verified on original).""" + if keyboard_visible(): + press_key("KEYCODE_ESCAPE") + settle("keyboard") + return not keyboard_visible() + + +def and_enter_main(clear=False): + """Get to MainActivity. clear=True wipes the vault first (virgin DB). + + Runs the 4-tap onboarding skip by resource-id only, choosing rb_none so the + vault opens directly on every relaunch (no unlock screen — essential for the + persistence tests). Returns the last fresh node list, or None if Main was + never reached.""" + if clear: + clear_data() + restart_app() + wait_for_foreground() + n = ui() + if node_by_id(n, "btnNext"): + for rid in ("btnNext", "rb_none", "btnNext", "btnNext"): + t = node_by_id(n, rid) + if t is None or not tap_node(t): + return None + n = ui() + if node_by_id(n, "fab") is None: + return None + return n + + +def _open_overflow(): + mo = find_node(ui(), content_desc="More options") + if mo: + tap_node(mo) + settle("tap") + return ui() + + +def and_reach_settings(): + """Main -> overflow -> Settings root. Proven jump: the PreferencesActivity's + 'Navigate up' affordance appears and the sibling 'About' menu item leaves. + Backs one surface (jump_kind='reach').""" + _open_overflow() + item = find_node_ci(ui(), "Settings") + return bool(item) and and_reach_surface(item, "Navigate up", "About") + + +# The section title echoes in BOTH the root row and the sub-screen header, so the +# title is not a valid "appeared" key. A section-only child is. (Read off each.) +_SECTION_CHILD = { + "Appearance": "Dynamic colors", + "Behavior": "Haptic feedback", +} + + +def and_reach_settings_section(label): + """From the Settings ROOT, tap a category row and prove its sub-screen + arrived: a section-only `child` APPEARED and the root 'Settings' title LEFT. + Backs one more surface (jump_kind='reach').""" + child = _SECTION_CHILD[label] + trigger = None + for n in ui(): + if n.get("resource-id", "").endswith("title") and \ + n.get("text", "").lower().startswith(label.lower()): + trigger = n + break + if trigger is None: + trigger = find_node_ci(ui(), label) + if trigger is None: + return False + return and_reach_surface(trigger, child, "Settings") + + +def and_reach_behavior(): + """Main -> Settings -> Behavior sub-screen. Two proven surface hops.""" + return and_reach_settings() and and_reach_settings_section("Behavior") + + +def and_reach_appearance(): + """Main -> Settings -> Appearance sub-screen. Two proven surface hops.""" + return and_reach_settings() and and_reach_settings_section("Appearance") + + +def and_enter_editor(): + """Main -> FAB menu -> Enter manually -> EditEntryActivity. Backs one surface + once the editor is confirmed foreground.""" + fab = node_by_id(ui(), "fab") + if fab is None or not tap_node(fab): + return False + en = node_by_id(ui(), "fab_menu_item_enter") + if en is None or not tap_node(en): + return False + settle("tap") + if not get_current_activity().endswith("EditEntryActivity"): + return False + and_enter("editor") + return True + + +def and_create_entry(name, issuer, secret=SEC_A): + """FAB -> Enter manually -> fill name/issuer/secret -> SAVE. Returns True only + when we land back on Main with the new issuer visible. Robust: re-dumps after + every field, lowers the keyboard between fields, handles the save dialog.""" + if not and_enter_editor(): + return False + nm = node_by_id(ui(), "text_name") + if nm is None or not type_text(nm, name): + return False + _kb_off() + iss = node_by_id(ui(), "text_issuer") + if iss is None or not type_text(iss, issuer): + return False + _kb_off() + sec = node_by_id(ui(), "text_secret") + if sec is None or not type_text(sec, secret): + return False + _kb_off() + save = node_by_id(ui(), "action_save") + if save is None or not tap_node(save): + return False + n = ui() + if find_node_ci(n, "Error saving profile"): + return False + if find_node_ci(n, "Your changes have not been saved"): + sv = find_node(n, text="Save") + if sv: + tap_node(sv) + n = ui() + if not get_current_activity().endswith("MainActivity"): + return False + return find_node_ci(ui(), issuer) is not None + + +def _issuers(nodes=None): + """Top-to-bottom list of profile_issuer strings currently shown.""" + nodes = ui() if nodes is None else nodes + rows = [(x["_bounds"][1], x.get("text", "")) + for x in nodes + if x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_issuer" + and "_bounds" in x] + return [t for _y, t in sorted(rows)] + + +def _switch_for_label(nodes, label): + """Return the `switchWidget` Switch belonging to the preference row whose + title == `label`. All Behavior/Appearance switches share id `switchWidget`; + the correct one is the switch whose vertical centre is closest to the title's + vertical centre. Verified on the running app (each row's switch sits within a + ~30px y-band of its title).""" + title = None + for x in nodes: + if (x.get("resource-id", "").rsplit("/", 1)[-1] == "title" + and x.get("text", "").strip().lower() == label.strip().lower() + and "_center" in x): + title = x + break + if title is None: + return None + ty = title["_center"][1] + best, best_dy = None, 10 ** 9 + for x in nodes: + if x.get("resource-id", "").rsplit("/", 1)[-1] == "switchWidget" and "_center" in x: + dy = abs(x["_center"][1] - ty) + if dy < best_dy: + best, best_dy = x, dy + # Guard: the matched switch must actually be on the same row (within a + # generous band), never a distant one, else return None -> feature_missing. + return best if best_dy <= 140 else None + + +def _summary_under(nodes, title_label): + """Return the `summary` TextView that sits directly beneath the preference + row titled `title_label` (the next summary at greater y within the row). + Used to read 'Selected: X' consequence text.""" + ty = None + for x in nodes: + if (x.get("resource-id", "").rsplit("/", 1)[-1] == "title" + and x.get("text", "").strip().lower() == title_label.strip().lower() + and "_bounds" in x): + ty = x["_bounds"][1] + break + if ty is None: + return None + cands = [(x["_bounds"][1], 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 cands: + return None + return min(cands, key=lambda p: p[0])[1] + + +def _open_dialog_from_row(title_label): + """Tap a preference row (by its title label) that opens a selection dialog, + counting the dialog as one crossed surface. Returns the fresh tree, or None.""" + row = find_node_ci(ui(), title_label) + if row is None or not tap_node(row): + return None + settle("tap") + and_enter("dialog") + return ui() + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1. Behavior switch flips checked — three DIFFERENT switches (a recreation that +# hardcodes one still fails the others). Each pairs the flip with the row's own +# checked read-back (the app-authored per-row state), re-located in a fresh dump. +# ══════════════════════════════════════════════════════════════════════════════ + +def _toggle_behavior_switch(label, rec_name): + """Shared body: reach Behavior, flip the named switch, assert `checked` + transitioned to the opposite of what was observed before. depth=2.""" + if and_enter_main(clear=True) is None: + record(rec_name, False, "setup_failed: could not reach MainActivity", + depth=2, jump_kind="transition", expect=f"'{label}' checked flips") + return + if not and_reach_behavior(): + record(rec_name, False, "setup_failed: could not reach Behavior settings", + depth=2, jump_kind="transition", expect=f"'{label}' checked flips") + return + n = ui() + sw = _switch_for_label(n, label) + if sw is None: + record(rec_name, False, f"feature_missing: no '{label}' switch row", + depth=2, jump_kind="transition", expect=f"'{label}' checked flips") + return + before = sw.get("checked") + if not tap_node(sw): + record(rec_name, False, f"setup_failed: '{label}' switch not tappable", + depth=2, jump_kind="transition", expect=f"'{label}' checked flips") + return + settle("tap") + fresh = ui() + sw2 = _switch_for_label(fresh, label) or find_closest_match(fresh, sw) + after = (sw2 or {}).get("checked") + want = "false" if before == "true" else "true" + ok = after == want and after != before + record(rec_name, ok, + "" if ok else f"behavior_wrong: '{label}' checked {before!r}->{after!r} " + f"(expected ->{want!r})", + depth=2, jump_kind="transition", + expect=f"'{label}' checked {before}->{want}") + + +@and_test(expects=("states_behavior_focus_search_toggle",)) +def test_behavior_focus_search_toggle(): + _toggle_behavior_switch("Focus search on app start", + "states_behavior_focus_search_toggle") + + +@and_test(expects=("states_behavior_minimize_toggle",)) +def test_behavior_minimize_toggle(): + _toggle_behavior_switch("Minimize on copy", "states_behavior_minimize_toggle") + + +@and_test(expects=("states_behavior_haptic_toggle", "states_behavior_haptic_toggle_vlm")) +def test_behavior_haptic_toggle(): + # Haptic feedback is the one switch that ships ON — flipping it exercises the + # true->false direction, which a shell that defaults every switch off fails. + _toggle_behavior_switch("Haptic feedback", "states_behavior_haptic_toggle") + # VLM: an ON Material switch has a coloured (accent) track+thumb; toggling it + # OFF makes the track grey. We just flipped Haptic OFF, so the switch that was + # coloured is now grey — a rendered-colour confirm the dump's bool cannot give. + vlm_assert("states_behavior_haptic_toggle", + "In this settings list, look at the on/off toggle switch on the " + "'Haptic feedback' row. Is that switch in the OFF position, i.e. its " + "thumb is on the LEFT and its track is grey/uncoloured (not a filled " + "green/accent colour)?", + RESULTS_DIR, expect="YES", depth=2, jump_kind="transition", tag="color") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2. Switch state PERSISTS across process death — the core in-memory-shell killer. +# Flip via the GUI, force_stop_and_relaunch(), navigate BACK to the same row, +# assert the NEW value survived. Done for two independent switches. +# ══════════════════════════════════════════════════════════════════════════════ + +def _persist_behavior_switch(label, rec_name): + if and_enter_main(clear=True) is None or not and_reach_behavior(): + record(rec_name, False, "setup_failed: could not reach Behavior settings", + depth=2, jump_kind="value", expect=f"'{label}' checked persists after relaunch") + return + n = ui() + sw = _switch_for_label(n, label) + if sw is None: + record(rec_name, False, f"feature_missing: no '{label}' switch row", + depth=2, jump_kind="value", expect=f"'{label}' checked persists after relaunch") + return + before = sw.get("checked") + if not tap_node(sw): + record(rec_name, False, f"setup_failed: '{label}' switch not tappable", + depth=2, jump_kind="value", expect=f"'{label}' checked persists after relaunch") + return + settle("tap") + want = "false" if before == "true" else "true" + # Kill the process and come back, then RE-NAVIGATE to the same row so the read + # is against a freshly-inflated screen, not a cached view. + force_stop_and_relaunch() + wait_for_foreground() + if node_by_id(ui(), "btnNext"): + # A vault that forgot rb_none would show onboarding; with persistence the + # app should reopen straight to Main. Treat onboarding as a fail signal. + record(rec_name, False, + "behavior_wrong: relaunch hit onboarding (setting not persisted / vault reset)", + depth=2, jump_kind="value", expect=f"'{label}' checked persists after relaunch") + return + if not and_reach_behavior(): + record(rec_name, False, "setup_failed: could not re-reach Behavior after relaunch", + depth=2, jump_kind="value", expect=f"'{label}' checked persists after relaunch") + return + sw2 = _switch_for_label(ui(), label) + after = (sw2 or {}).get("checked") + ok = after == want + record(rec_name, ok, + "" if ok else f"behavior_wrong: after relaunch '{label}' checked={after!r} " + f"(expected persisted {want!r})", + depth=2, jump_kind="value", + expect=f"'{label}' checked persists as {want} after relaunch") + + +@and_test(expects=("states_behavior_minimize_persists",)) +def test_behavior_minimize_persists(): + _persist_behavior_switch("Minimize on copy", "states_behavior_minimize_persists") + + +@and_test(expects=("states_behavior_multiselect_persists",)) +def test_behavior_multiselect_persists(): + _persist_behavior_switch("Multiselect groups", "states_behavior_multiselect_persists") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3. Dynamic colors switch (Appearance, default off) — checked flips. depth=2. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_dynamic_colors_toggle",)) +def test_dynamic_colors_toggle(): + if and_enter_main(clear=True) is None or not and_reach_appearance(): + record("states_dynamic_colors_toggle", False, + "setup_failed: could not reach Appearance settings", + depth=2, jump_kind="transition", expect="'Dynamic colors' checked flips") + return + n = ui() + sw = _switch_for_label(n, "Dynamic colors") + if sw is None: + record("states_dynamic_colors_toggle", False, + "feature_missing: no 'Dynamic colors' switch row", + depth=2, jump_kind="transition", expect="'Dynamic colors' checked flips") + return + before = sw.get("checked") + tap_node(sw) + settle("tap") + fresh = ui() + sw2 = _switch_for_label(fresh, "Dynamic colors") or find_closest_match(fresh, sw) + after = (sw2 or {}).get("checked") + want = "false" if before == "true" else "true" + ok = after == want and after != before + record("states_dynamic_colors_toggle", ok, + "" if ok else f"behavior_wrong: Dynamic colors checked {before!r}->{after!r}", + depth=2, jump_kind="transition", + expect=f"'Dynamic colors' checked {before}->{want}") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4. THEME is a selected-state machine: Appearance -> Theme dialog -> pick a +# non-default option -> the 'Selected: X' summary changes AND the app repaints. +# Selecting recreates the activity — re-dump after. depth=2 (Appearance) then +# the dialog. Restores System default at the end. +# ══════════════════════════════════════════════════════════════════════════════ + +def _theme_summary_text(nodes=None): + s = _summary_under(ui() if nodes is None else nodes, "Theme") + return (s or {}).get("text") + + +def _select_theme(option_label): + """From the Appearance sub-screen: open the Theme dialog and tap `option_label`. + Returns True once we are back on PreferencesActivity (the selection recreates + it). depth: opens the dialog as a surface.""" + row = find_node_ci(ui(), "Theme") + if row is None or not tap_node(row): + return False + settle("tap") + if find_node_ci(ui(), "Select your desired theme") is None: + return False + and_enter("theme_dialog") + opt = find_node_ci(ui(), option_label) + if opt is None or not tap_node(opt): + return False + # Selecting a theme recreates PreferencesActivity; give it time and re-dump. + settle("launch") + settle("tap") + return get_current_activity().endswith("PreferencesActivity") + + +def _reset_theme_to_system(): + """Best-effort cleanup so later lanes/screenshots see a neutral theme.""" + try: + if and_enter_main() is None or not and_reach_appearance(): + return + cur = _theme_summary_text() + if cur and "System default" in cur and "AMOLED" not in cur: + return + _select_theme("System default") + except Exception: + pass + + +@and_test(expects=("states_theme_select_light", "states_theme_select_light_vlm")) +def test_theme_select_light(): + if and_enter_main(clear=True) is None or not and_reach_appearance(): + record("states_theme_select_light", False, + "setup_failed: could not reach Appearance settings", + depth=2, jump_kind="value", expect="Theme summary 'Selected: Light theme'") + return + before = _theme_summary_text() + if not _select_theme("Light theme"): + record("states_theme_select_light", False, + "feature_missing: Theme dialog / 'Light theme' option not available", + depth=2, jump_kind="value", expect="Theme summary 'Selected: Light theme'") + _reset_theme_to_system() + return + after = _theme_summary_text() + ok = after == "Selected: Light theme" and after != before + record("states_theme_select_light", ok, + "" if ok else f"behavior_wrong: Theme summary {before!r}->{after!r} " + f"(expected 'Selected: Light theme')", + depth=2, jump_kind="value", expect="Theme summary 'Selected: Light theme'") + # VLM: the whole app must have repainted to a LIGHT background with dark text. + vlm_assert("states_theme_select_light", + "Light theme was just selected. Is the overall screen background " + "light/white (a bright page) with dark text, rather than a dark or " + "black background?", + RESULTS_DIR, expect="YES", depth=2, jump_kind="value", tag="color") + _reset_theme_to_system() + + +@and_test(expects=("states_theme_persists_vlm", "states_theme_persists_summary")) +def test_theme_persists(): + """Select Dark -> force stop + relaunch -> app is STILL dark (VLM) AND + Appearance->Theme still reads 'Selected: Dark theme' (rule). Proves settings + persistence both visually and textually against a NON-default theme (the + emulator's system default renders light, so Dark is the distinguishing + choice). Resets to System default at the end.""" + if and_enter_main(clear=True) is None or not and_reach_appearance(): + record("states_theme_persists_summary", False, + "setup_failed: could not reach Appearance settings", + depth=2, jump_kind="value", expect="Theme stays 'Selected: Dark theme' after relaunch") + return + if not _select_theme("Dark theme"): + record("states_theme_persists_summary", False, + "feature_missing: could not select Dark theme", + depth=2, jump_kind="value", expect="Theme stays 'Selected: Dark theme' after relaunch") + _reset_theme_to_system() + return + force_stop_and_relaunch() + wait_for_foreground() + if node_by_id(ui(), "btnNext"): + record("states_theme_persists_summary", False, + "behavior_wrong: relaunch hit onboarding (theme/vault not persisted)", + depth=2, jump_kind="value", expect="Theme stays 'Selected: Dark theme' after relaunch") + return + # VLM #1 — the MAIN screen after relaunch is still dark. + vlm_assert("states_theme_persists", + "This authenticator app was just relaunched after Dark theme was " + "chosen. Is its main screen still shown with a dark background " + "(near-black / dark grey, light-coloured text) rather than a " + "bright white page?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="color") + # Rule — the setting text survived too. + if not and_reach_appearance(): + record("states_theme_persists_summary", False, + "setup_failed: could not re-reach Appearance after relaunch", + depth=2, jump_kind="value", expect="Theme stays 'Selected: Dark theme' after relaunch") + _reset_theme_to_system() + return + after = _theme_summary_text() + ok = after == "Selected: Dark theme" + record("states_theme_persists_summary", ok, + "" if ok else f"behavior_wrong: after relaunch Theme summary={after!r} " + f"(expected persisted 'Selected: Dark theme')", + depth=2, jump_kind="value", + expect="Theme stays 'Selected: Dark theme' after relaunch") + _reset_theme_to_system() + + +@and_test(expects=("states_theme_dialog_checkmark_vlm",)) +def test_theme_dialog_checkmark_vlm(): + """The Theme dialog is a single-choice list: exactly one option carries the + selected radio/check mark. Rendered indicator — a shape the dump's `checked` + bool cannot show. Cancels out without changing the theme.""" + if and_enter_main(clear=True) is None or not and_reach_appearance(): + record("states_theme_dialog_checkmark_vlm", False, + "setup_failed: could not reach Appearance settings", + depth=2, jump_kind="transition", tag="shape") + return + row = find_node_ci(ui(), "Theme") + if row is None or not tap_node(row): + record("states_theme_dialog_checkmark_vlm", False, + "feature_missing: Theme row not tappable", + depth=2, jump_kind="transition", tag="shape") + return + settle("tap") + and_enter("theme_dialog") + if find_node_ci(ui(), "Select your desired theme") is None: + record("states_theme_dialog_checkmark_vlm", False, + "feature_missing: theme selection dialog did not open", + depth=2, jump_kind="transition", tag="shape") + return + vlm_assert("states_theme_dialog_checkmark", + "This is a single-choice theme picker dialog listing Light theme, " + "Dark theme, AMOLED theme and System default options. Is exactly ONE " + "option marked with a filled/selected radio button (a round selected " + "indicator) while the others are unselected?", + RESULTS_DIR, expect="YES", depth=2, jump_kind="transition", tag="shape") + # Dismiss without changing the theme. + c = find_node_ci(ui(), "Cancel") + if c: + tap_node(c) + else: + back() + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5. VIEW MODE selection state: Appearance -> View mode dialog -> pick Compact -> +# summary 'Selected: Normal' becomes 'Selected: Compact'. The summary flip is +# the strong app-authored consequence of the state machine (rule assertion). +# No VLM: Normal vs Compact row density is too subtle for a reliable +# single-screenshot YES/NO. depth=2. Restores to Normal at the end. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_view_mode_compact",)) +def test_view_mode_compact(): + if and_enter_main(clear=True) is None or not and_create_entry("nVM", "iViewMode"): + record("states_view_mode_compact", False, + "setup_failed: could not create an entry to view", + depth=2, jump_kind="value", expect="View mode summary 'Selected: Compact'") + return + if not and_reach_appearance(): + record("states_view_mode_compact", False, + "setup_failed: could not reach Appearance settings", + depth=2, jump_kind="value", expect="View mode summary 'Selected: Compact'") + return + before = (_summary_under(ui(), "View mode") or {}).get("text") + fresh = _open_dialog_from_row("View mode") + if fresh is None or find_node_ci(fresh, "Compact") is None: + record("states_view_mode_compact", False, + "feature_missing: View mode dialog / 'Compact' option not available", + depth=2, jump_kind="value", expect="View mode summary 'Selected: Compact'") + return + tap_node(find_node_ci(fresh, "Compact")) + settle("tap") + after = (_summary_under(ui(), "View mode") or {}).get("text") + ok = after == "Selected: Compact" and after != before + record("states_view_mode_compact", ok, + "" if ok else f"behavior_wrong: View mode summary {before!r}->{after!r} " + f"(expected 'Selected: Compact')", + depth=2, jump_kind="value", expect="View mode summary 'Selected: Compact'") + # Restore Normal so later lanes/screenshots see the default density. + try: + if and_enter_main() is not None and and_reach_appearance(): + f = _open_dialog_from_row("View mode") + if f and find_node_ci(f, "Normal"): + tap_node(find_node_ci(f, "Normal")) + settle("tap") + except Exception: + pass + + +# ══════════════════════════════════════════════════════════════════════════════ +# 6. SHOW ACCOUNT NAME selection: 'Selected: Next to the issuer' -> pick a +# different option -> the summary changes. depth=2. Restores at the end. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_show_account_name_select",)) +def test_show_account_name_select(): + if and_enter_main(clear=True) is None or not and_reach_appearance(): + record("states_show_account_name_select", False, + "setup_failed: could not reach Appearance settings", + depth=2, jump_kind="transition", expect="Show-account-name summary changes") + return + before = (_summary_under(ui(), "Show the account name") or {}).get("text") + fresh = _open_dialog_from_row("Show the account name") + if fresh is None: + record("states_show_account_name_select", False, + "feature_missing: 'Show the account name' dialog not available", + depth=2, jump_kind="transition", expect="Show-account-name summary changes") + return + # Pick any option whose label differs from the current selection. The dialog + # lists placement choices; 'Below the issuer' is a stable alternative — fall + # back to the first radio option that is not the current one. + target = find_node_ci(fresh, "Below the issuer") + if target is None: + opts = [x for x in fresh + if x.get("resource-id", "").rsplit("/", 1)[-1] == "text1" + and x.get("checked") == "false" and x.get("text")] + target = opts[0] if opts else None + if target is None: + record("states_show_account_name_select", False, + "feature_missing: no alternative account-name option to select", + depth=2, jump_kind="transition", expect="Show-account-name summary changes") + c = find_node_ci(ui(), "Cancel") + if c: + tap_node(c) + return + chosen = target.get("text") + tap_node(target) + settle("tap") + after = (_summary_under(ui(), "Show the account name") or {}).get("text") + ok = bool(after) and after != before and after == f"Selected: {chosen}" + record("states_show_account_name_select", ok, + "" if ok else f"behavior_wrong: account-name summary {before!r}->{after!r} " + f"(expected 'Selected: {chosen}')", + depth=2, jump_kind="transition", + expect=f"Show-account-name summary '{before}' -> 'Selected: {chosen}'") + # Restore the original ('Next to the issuer'). + try: + f = _open_dialog_from_row("Show the account name") + if f and find_node_ci(f, "Next to the issuer"): + tap_node(find_node_ci(f, "Next to the issuer")) + settle("tap") + except Exception: + pass + + +# ══════════════════════════════════════════════════════════════════════════════ +# 7. SORT selection state machine + reorder CONSEQUENCE (a page-level state +# change): create Bravo then Alpha (insertion order [Bravo, Alpha]) -> sort +# 'Issuer (A to Z)' -> first row becomes the alphabetically-first issuer. +# depth=1 (the sort popup). Plus persistence of the order across relaunch. +# ══════════════════════════════════════════════════════════════════════════════ + +def and_open_sort_popup(): + srt = find_node(ui(), content_desc="Sort") + if srt is None or not tap_node(srt): + return False + settle("tap") + if find_node_ci(ui(), "Issuer (A to Z)") is None: + return False + and_enter("sort_popup") + return True + + +@and_test(expects=("states_sort_issuer_reorders", "states_sort_issuer_reorders_vlm")) +def test_sort_issuer_reorders(): + if and_enter_main(clear=True) is None: + record("states_sort_issuer_reorders", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="value", expect="first issuer 'Bravo'->'Alpha' after sort") + return + if not and_create_entry("accB", "Bravo") or not and_create_entry("accA", "Alpha"): + record("states_sort_issuer_reorders", False, + "feature_missing: could not create the two sortable entries", + depth=1, jump_kind="value", expect="first issuer 'Bravo'->'Alpha' after sort") + return + order0 = _issuers() + if not order0 or order0[0] != "Bravo": + record("states_sort_issuer_reorders", False, + f"setup_failed: unexpected initial order {order0!r} (wanted Bravo first)", + depth=1, jump_kind="value", expect="first issuer 'Bravo'->'Alpha' after sort") + return + if not and_open_sort_popup(): + record("states_sort_issuer_reorders", False, + "feature_missing: Sort popup did not open", + depth=1, jump_kind="value", expect="first issuer 'Bravo'->'Alpha' after sort") + return + opt = find_node_ci(ui(), "Issuer (A to Z)") + tap_node(opt) + settle("tap") + order1 = _issuers() + ok = bool(order1) and order1[0] == "Alpha" and set(order1) == {"Alpha", "Bravo"} + record("states_sort_issuer_reorders", ok, + "" if ok else f"behavior_wrong: order before={order0!r} after Issuer-A-Z={order1!r} " + f"(expected Alpha first)", + depth=1, jump_kind="value", expect="first issuer 'Bravo'->'Alpha' after sort") + # VLM — the list visibly reordered: 'Alpha' now sits above 'Bravo'. + vlm_assert("states_sort_issuer_reorders", + "This authenticator list has two entries, one for issuer 'Alpha' and " + "one for issuer 'Bravo', after sorting by issuer A to Z. Is the " + "'Alpha' entry positioned ABOVE the 'Bravo' entry in the list?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="value", tag="position") + + +@and_test(expects=("states_sort_order_persists",)) +def test_sort_order_persists(): + """The chosen sort order survives process death: pick Issuer (A to Z), + force stop + relaunch, the list is STILL Alpha-first (sort choice persisted).""" + if and_enter_main(clear=True) is None: + record("states_sort_order_persists", False, + "setup_failed: could not reach MainActivity", + depth=0, jump_kind="value", expect="first issuer stays 'Alpha' after relaunch") + return + if not and_create_entry("accB", "Bravo") or not and_create_entry("accA", "Alpha"): + record("states_sort_order_persists", False, + "feature_missing: could not create the two sortable entries", + depth=0, jump_kind="value", expect="first issuer stays 'Alpha' after relaunch") + return + if not and_open_sort_popup(): + record("states_sort_order_persists", False, + "feature_missing: Sort popup did not open", + depth=0, jump_kind="value", expect="first issuer stays 'Alpha' after relaunch") + return + tap_node(find_node_ci(ui(), "Issuer (A to Z)")) + settle("tap") + if _issuers()[:1] != ["Alpha"]: + record("states_sort_order_persists", False, + "setup_failed: sort did not take effect before relaunch", + depth=0, jump_kind="value", expect="first issuer stays 'Alpha' after relaunch") + return + force_stop_and_relaunch() + wait_for_foreground() + if node_by_id(ui(), "btnNext"): + record("states_sort_order_persists", False, + "behavior_wrong: relaunch hit onboarding (state reset)", + depth=0, jump_kind="value", expect="first issuer stays 'Alpha' after relaunch") + return + order = _issuers() + ok = bool(order) and order[0] == "Alpha" and set(order) == {"Alpha", "Bravo"} + record("states_sort_order_persists", ok, + "" if ok else f"behavior_wrong: after relaunch order={order!r} " + f"(expected persisted Alpha first)", + depth=0, jump_kind="value", expect="first issuer stays 'Alpha' after relaunch") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 8. SECRET MASKING toggle (EditEntryActivity, 'Show password' end icon): the +# secret field is `password=true` (dots) -> tap -> `password=false` (revealed). +# A checked-like visibility state with a real consequence. depth=1 (editor). +# Emits TWO decidable content VLMs: masked (dots) before, plaintext after. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_secret_mask_toggle", "states_secret_masked_vlm", + "states_secret_mask_toggle_vlm")) +def test_secret_mask_toggle(): + if and_enter_main(clear=True) is None or not and_enter_editor(): + record("states_secret_mask_toggle", False, + "setup_failed: could not open the entry editor", + depth=1, jump_kind="transition", expect="secret password=true->false (revealed)") + return + sec = node_by_id(ui(), "text_secret") + if sec is None or not type_text(sec, SEC_A): + record("states_secret_mask_toggle", False, + "setup_failed: could not type into the secret field", + depth=1, jump_kind="transition", expect="secret password=true->false (revealed)") + return + _kb_off() + n = ui() + sec = node_by_id(n, "text_secret") + before = (sec or {}).get("password") + # VLM (masked): before revealing, the secret must render as masked dots. + vlm_assert("states_secret_masked", + "On this add-entry form, look at the 'Secret' input field. Is its " + "value shown as masked characters (a row of dots or bullets / " + "asterisks) rather than readable plain-text letters and digits?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", tag="content") + icon = find_node(n, content_desc="Show password") + if icon is None: + # end-icon by id, whichever carries a content-desc + for x in n: + if x.get("resource-id", "").rsplit("/", 1)[-1] == "text_input_end_icon" \ + and x.get("content-desc"): + icon = x + break + if icon is None: + record("states_secret_mask_toggle", False, + "feature_missing: no 'Show password' reveal control on the secret field", + depth=1, jump_kind="transition", expect="secret password=true->false (revealed)") + return + tap_node(icon) + settle("tap") + fresh = ui() + sec2 = node_by_id(fresh, "text_secret") + after = (sec2 or {}).get("password") + # Masked field reports password=true; revealing flips it to false, and the + # plaintext secret is now readable in the field's text. + ok = before == "true" and after == "false" and (sec2 or {}).get("text") == SEC_A + record("states_secret_mask_toggle", ok, + "" if ok else f"behavior_wrong: secret password {before!r}->{after!r} " + f"text={ (sec2 or {}).get('text')!r} (expected true->false, plaintext shown)", + depth=1, jump_kind="transition", expect="secret password=true->false (revealed)") + # VLM (revealed) — the secret is now legible as plain characters, not dots. + vlm_assert("states_secret_mask_toggle", + "On this add-entry form, the 'Secret' field's reveal (eye) button was " + "just tapped. Is the secret now shown as readable plain-text " + f"characters (the value '{SEC_A}') rather than as masked dots?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", tag="content") + # leave the editor without saving + back() + n = ui() + if find_node_ci(n, "Your changes have not been saved"): + d = find_node(n, text="Discard") + if d: + tap_node(d) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 9. ADVANCED accordion expand (EditEntryActivity): before expand the Advanced +# fields are NOT in the tree; tapping the header makes them APPEAR — a +# page-level shape/state change and the app-authored consequence. depth=1. +# (The header scrolls out of the tree once expanded, so collapse is not a +# reliable read on this build; the absent->present expand is the assertion.) +# ══════════════════════════════════════════════════════════════════════════════ + +def _advanced_header(nodes): + for rid in ("accordian_header", "accordian_title"): + h = node_by_id(nodes, rid) + if h: + return h + return find_node_ci(nodes, "Advanced") + + +@and_test(expects=("states_advanced_accordion_expand", "states_advanced_accordion_expand_vlm")) +def test_advanced_accordion_expand(): + if and_enter_main(clear=True) is None or not and_enter_editor(): + record("states_advanced_accordion_expand", False, + "setup_failed: could not open the entry editor", + depth=1, jump_kind="transition", + expect="Advanced fields absent->present on expand") + return + _kb_off() + n = ui() + fields = ("dropdown_type", "text_digits", "text_period_counter") + before = {f: node_by_id(n, f) is not None for f in fields} + header = _advanced_header(n) + if header is None: + record("states_advanced_accordion_expand", False, + "feature_missing: no 'Advanced' accordion header", + depth=1, jump_kind="transition", + expect="Advanced fields absent->present on expand") + return + tap_node(header) + settle("tap") + n = ui() + after = {f: node_by_id(n, f) is not None for f in fields} + # The consequence: fields that were ABSENT are now PRESENT (all of them). + ok = all(not before[f] and after[f] for f in fields) + record("states_advanced_accordion_expand", ok, + "" if ok else f"behavior_wrong: Advanced fields before={before} after_expand={after} " + f"(expected all absent->present)", + depth=1, jump_kind="transition", + expect="Advanced fields (type/digits/period) absent->present on expand") + # VLM — confirm the extra fields render as a new block. + if node_by_id(ui(), "dropdown_type") is not None: + vlm_assert("states_advanced_accordion_expand", + "The 'Advanced' section of this add-entry form was just expanded. " + "Are extra input rows now visible below the Advanced header (such " + "as a token 'Type', an 'Algorithm', a 'Period' and a 'Digits' " + "field) that were hidden before?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", tag="layout") + else: + vlm_assert("states_advanced_accordion_expand", + "The 'Advanced' section of this add-entry form was just expanded. " + "Are extra input rows now visible below the Advanced header?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", tag="layout") + back() + n = ui() + if find_node_ci(n, "Your changes have not been saved"): + d = find_node(n, text="Discard") + if d: + tap_node(d) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 10. FOCUS (this lane is the SOLE owner): opening Search moves focus onto the +# search EditText — a `focused` false/absent -> true transition. depth=1. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_search_field_focused",)) +def test_search_field_focused(): + if and_enter_main(clear=True) is None: + record("states_search_field_focused", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="transition", expect="search field focused=true after opening search") + return + n = ui() + # Before: no search EditText focused on Main. + before = node_by_id(n, "search_src_text") + before_focused = (before or {}).get("focused") == "true" + sb = node_by_id(n, "search_button") + if sb is None or not tap_node(sb): + record("states_search_field_focused", False, + "feature_missing: no Search control to open", + depth=1, jump_kind="transition", expect="search field focused=true after opening search") + return + and_enter("search") + fresh = ui() + sst = node_by_id(fresh, "search_src_text") + after_focused = (sst or {}).get("focused") == "true" + ok = (sst is not None) and (not before_focused) and after_focused + record("states_search_field_focused", ok, + "" if ok else f"behavior_wrong: search field focused before={before_focused} " + f"after={after_focused} (expected ->true)", + depth=1, jump_kind="transition", + expect="search field focused=true after opening search") + back() + + +# ══════════════════════════════════════════════════════════════════════════════ +# 11. FOCUS via a persisted SETTING: 'Focus search on app start' ON -> after a +# relaunch the search field is auto-opened AND focused. This couples a +# persisted checked state to a focus consequence — a dead shell fails both. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_focus_search_on_start",)) +def test_focus_search_on_start(): + if and_enter_main(clear=True) is None or not and_reach_behavior(): + record("states_focus_search_on_start", False, + "setup_failed: could not reach Behavior settings", + depth=2, jump_kind="value", + expect="search field focused=true on next app start") + return + sw = _switch_for_label(ui(), "Focus search on app start") + if sw is None: + record("states_focus_search_on_start", False, + "feature_missing: no 'Focus search on app start' switch", + depth=2, jump_kind="value", + expect="search field focused=true on next app start") + return + if sw.get("checked") != "true": + tap_node(sw) + settle("tap") + # Relaunch: the setting should auto-focus search on Main. + force_stop_and_relaunch() + wait_for_foreground() + if node_by_id(ui(), "btnNext"): + record("states_focus_search_on_start", False, + "behavior_wrong: relaunch hit onboarding (setting not persisted)", + depth=2, jump_kind="value", + expect="search field focused=true on next app start") + return + n = ui() + sst = node_by_id(n, "search_src_text") + focused = (sst or {}).get("focused") == "true" + ok = sst is not None and focused + record("states_focus_search_on_start", ok, + "" if ok else f"behavior_wrong: after relaunch search field present={sst is not None} " + f"focused={focused} (expected auto-focused search)", + depth=2, jump_kind="value", + expect="search field focused=true on next app start") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 12. VLM: a switch in the OFF state has a grey/uncoloured track (color) — a +# rendered confirm of the dump's `checked=false`. Uses 'Minimize on copy' +# (ships OFF) so no state change is needed; distinct row from the haptic VLM. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_switch_off_track_vlm",)) +def test_switch_off_track_vlm(): + if and_enter_main(clear=True) is None or not and_reach_behavior(): + record("states_switch_off_track_vlm", False, + "setup_failed: could not reach Behavior settings", + depth=2, jump_kind="value", tag="color") + return + if _switch_for_label(ui(), "Minimize on copy") is None: + record("states_switch_off_track_vlm", False, + "feature_missing: 'Minimize on copy' switch row not found", + depth=2, jump_kind="value", tag="color") + return + vlm_assert("states_switch_off_track", + "In this settings list, look at the on/off toggle switch on the " + "'Minimize on copy' row. Is that switch OFF — its thumb on the LEFT " + "and its track a plain grey/uncoloured tone (not a filled green or " + "coloured accent)?", + RESULTS_DIR, expect="YES", depth=2, jump_kind="value", tag="color") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 13. VLM: the ON 'Haptic feedback' switch (default ON) renders a coloured/accent +# track — the positive-colour counterpart to #12. Read WITHOUT changing it. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_switch_on_track_vlm",)) +def test_switch_on_track_vlm(): + if and_enter_main(clear=True) is None or not and_reach_behavior(): + record("states_switch_on_track_vlm", False, + "setup_failed: could not reach Behavior settings", + depth=2, jump_kind="value", tag="color") + return + sw = _switch_for_label(ui(), "Haptic feedback") + if sw is None or sw.get("checked") != "true": + record("states_switch_on_track_vlm", False, + "feature_missing: 'Haptic feedback' switch not found in the ON state", + depth=2, jump_kind="value", tag="color") + return + vlm_assert("states_switch_on_track", + "In this settings list, look at the on/off toggle switch on the " + "'Haptic feedback' row. Is that switch ON — its thumb on the RIGHT " + "and its track filled with a coloured/accent tone (e.g. green/blue) " + "rather than plain grey?", + RESULTS_DIR, expect="YES", depth=2, jump_kind="value", tag="color") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 14. VLM: the DEFAULT (System default) Main screen renders LIGHT on this device — +# a bright page with dark text. The ground-truth baseline the Dark-theme +# persistence VLM contrasts against (color). Read on a virgin vault. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_default_theme_light_vlm",)) +def test_default_theme_light_vlm(): + if and_enter_main(clear=True) is None: + record("states_default_theme_light_vlm", False, + "setup_failed: could not reach MainActivity", + depth=0, jump_kind="none", tag="color") + return + vlm_assert("states_default_theme_light", + "This authenticator app is on its default (freshly installed) theme. " + "Is its main screen background light — a bright white / very light " + "page with dark text — rather than a dark or black background?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="none", tag="color") + + +TESTS = [ + test_behavior_focus_search_toggle, + test_behavior_minimize_toggle, + test_behavior_haptic_toggle, + test_behavior_minimize_persists, + test_behavior_multiselect_persists, + test_dynamic_colors_toggle, + test_theme_select_light, + test_theme_persists, + test_theme_dialog_checkmark_vlm, + test_view_mode_compact, + test_show_account_name_select, + test_sort_issuer_reorders, + test_sort_order_persists, + test_secret_mask_toggle, + test_advanced_accordion_expand, + test_search_field_focused, + test_focus_search_on_start, + test_switch_off_track_vlm, + test_switch_on_track_vlm, + test_default_theme_light_vlm, +] + +if __name__ == "__main__": + if not device_online(): + print("device offline — aborting") + sys.exit(2) + run_suite(TESTS, "states") diff --git a/android/beemdevelopment-aegis/tests/test_android_structure.py b/android/beemdevelopment-aegis/tests/test_android_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..53db4528034ec15e4f1631eda15ff11fbcc8cc59 --- /dev/null +++ b/android/beemdevelopment-aegis/tests/test_android_structure.py @@ -0,0 +1,589 @@ +#!/usr/bin/env python3 +"""STRUCTURE lane — Aegis Authenticator. + +Owns exactly two things: + 1. The GATE: MainActivity is in the foreground and its top-level surfaces + (toolbar host with search/sort/overflow, FAB, root container) exist. + These are jump_kind="none" existence checks — the only place existence + is allowed. + 2. Tree-SHAPE deltas: an interaction that changes the tree's shape (a menu + that adds a class of card, a dialog that adds a window layer, an + empty->populated list, a contextual action-mode toolbar). Recorded as + jump_kind="transition" with the observed delta, reversed where the app + reverses it. + +Every expected shape below was OBSERVED on the running original app. +Never asserts content strings/values — those belong to other lanes. +""" +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403 + +TESTS = [] + + +def test(fn): + TESTS.append(fn) + return fn + + +# ── Shared entry points ────────────────────────────────────────────────────── + +def _robust_id(rid_suffix, tries=4): + """node_by_id with a re-dump retry. A dump taken right after a keyboard + dismissal can come back partial (missing nodes); retrying absorbs that.""" + for _ in range(tries): + n = node_by_id(ui(), rid_suffix) + if n: + return n + settle("dump") + return None + + +def _dismiss_kb_on_form(): + """Dismiss the soft keyboard on EditEntryActivity WITHOUT leaving it, so the + lower form fields (text_issuer/text_secret) and the toolbar SAVE button + return to the uiautomator dump. A raw BACK here collapses the IME but keeps + the activity; we re-press once if the IME lags, and bail if we somehow left + the form. (The kit's generic hide_keyboard() taps an inert strip that on this + form re-shows the IME, leaving those fields below the fold.)""" + for _ in range(2): + if not keyboard_visible(): + return True + if "EditEntryActivity" not in get_current_activity(): + return False + press_key("KEYCODE_BACK") + settle("keyboard") + return "EditEntryActivity" in get_current_activity() + + +def and_enter_main(): + """Clean MainActivity: force-stop + clear data (-> onboarding), then skip the + IntroActivity by resource-id if it is showing (portable). Choosing rb_none + means the vault opens directly on every launch (no unlock screen).""" + force_stop() + clear_data() + launch_app() + wait_for_foreground() + nodes = ui() + if node_by_id(nodes, "btnNext"): + tap_node(node_by_id(nodes, "btnNext")) # Welcome -> Security + rb = node_by_id(ui(), "rb_none") + if rb: + tap_node(rb) # choose "None" + b = node_by_id(ui(), "btnNext") + if b: + tap_node(b) # Security -> Setup completed + b = node_by_id(ui(), "btnNext") + if b: + tap_node(b) # -> MainActivity + return ui() + + +def and_enter_edit_entry(): + """Navigate Main -> FAB menu -> "Enter manually" -> EditEntryActivity. + Counts one surface (backs a depth>=1 declaration).""" + tap_node(node_by_id(ui(), "fab")) + settle("tap") + item = node_by_id(ui(), "fab_menu_item_enter") + if not item: + return None + tap_node(item) + settle("launch") + and_enter("EditEntryActivity") + return ui() + + +def and_enter_settings(): + """Navigate Main -> overflow ("More options") -> Settings -> + PreferencesActivity. Counts one surface.""" + ov = find_node(ui(), content_desc="More options") + if not ov: + return None + tap_node(ov) + settle("tap") + st = find_node_ci(ui(), "Settings") + if not st: + return None + tap_node(st) + settle("launch") + and_enter("PreferencesActivity") + return ui() + + +def _create_entry(name="TestIssuer", secret="GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"): + """Fill and SAVE one manual entry from Main. Returns the Main tree after save, + or None if the flow did not land back on MainActivity. + + Per field: tap-type (type_text focuses the field first) then hide the + keyboard so the next field's tap is not intercepted. Every element lookup + goes through _robust_id because the post-keyboard dump is occasionally + partial on this form.""" + if and_enter_edit_entry() is None: + return None + nm = _robust_id("text_name") + if nm: + type_text(nm, name) + _dismiss_kb_on_form() + iss = _robust_id("text_issuer") + if iss: + type_text(iss, name) + _dismiss_kb_on_form() + sec = _robust_id("text_secret") + if sec: + type_text(sec, secret) + _dismiss_kb_on_form() + save = _robust_id("action_save") + if not save: + return None + tap_node(save) + settle("launch") + # SAVE itself pops EditEntryActivity back to Main (no extra BACK — a BACK on + # Main would exit the app). Reset the surface counter to reflect that. + and_reset_depth() + if "MainActivity" not in get_current_activity(): + return None + return ui() + + +def _count_by_id(nodes, rid_suffix): + """How many nodes carry this resource-id last segment (for row counting).""" + return len([n for n in (nodes or []) + if n.get("resource-id", "").rsplit("/", 1)[-1] == rid_suffix]) + + +# ══════════════════════════════════════════════════════════════════════════════ +# GATE — existence only (jump_kind="none"). Kept to <=30% of tests. +# ══════════════════════════════════════════════════════════════════════════════ + +@test +@and_test(expects=("structure_gate_launch",)) +def test_gate_launch(): + nodes = and_enter_main() + fg = wait_for_foreground() + root = bool(find_by_class(nodes, "FrameLayout")) and bool(find_by_class(nodes, "ViewGroup")) + ok = fg and root and "MainActivity" in get_current_activity() + record("structure_gate_launch", bool(ok), + "" if ok else "setup_failed: app did not reach MainActivity with a root container", + depth=0, jump_kind="none") + + +@test +@and_test(expects=("structure_gate_toolbar",)) +def test_gate_toolbar(): + nodes = and_enter_main() + # Toolbar host by id + its three action affordances by content-desc/id. + host = node_by_id(nodes, "toolbar") is not None or node_by_id(nodes, "app_bar_layout") is not None + search = node_by_id(nodes, "search_button") is not None + sort = node_by_id(nodes, "action_sort") is not None + overflow = find_node(nodes, content_desc="More options") is not None + ok = host and search and sort and overflow + record("structure_gate_toolbar", bool(ok), + "" if ok else "feature_missing: toolbar host with search/sort/overflow not all present", + depth=0, jump_kind="none") + + +@test +@and_test(expects=("structure_gate_fab",)) +def test_gate_fab(): + nodes = and_enter_main() + fab = node_by_id(nodes, "fab") is not None + add_desc = find_node(nodes, content_desc="Add new entry") is not None + ok = fab and add_desc + record("structure_gate_fab", bool(ok), + "" if ok else "feature_missing: FAB ('Add new entry') not present on MainActivity", + depth=0, jump_kind="none") + + +# ══════════════════════════════════════════════════════════════════════════════ +# SHAPE deltas — jump_kind="transition". Each observed the delta on the original. +# ══════════════════════════════════════════════════════════════════════════════ + +@test +@and_test(expects=("structure_fab_menu_shape", + "structure_fab_menu_shape_vlm")) +def test_fab_menu_shape(): + """FAB tap -> tree gains the 3 CardView menu items (Scan QR / Scan image / + Enter manually) that were absent before. Observed: 0 -> 3 cards.""" + nodes = and_enter_main() + cards_before = len(find_by_class(nodes, "CardView")) + before = and_showing(nodes) + ok_tap = tap_node(node_by_id(nodes, "fab")) + settle("tap") + after_nodes = ui() + cards_after = len(find_by_class(after_nodes, "CardView")) + after = and_showing(after_nodes) + menu_item = node_by_id(after_nodes, "fab_menu_item_enter") is not None + ok = (ok_tap and menu_item and cards_after == cards_before + 3 + and surface_changed(before, after)) + record("structure_fab_menu_shape", bool(ok), + "" if ok else f"behavior_wrong: fab menu did not add 3 cards " + f"({cards_before}->{cards_after})", + depth=0, jump_kind="transition", + expect="FAB menu subtree appears: CardView 0->3 + fab_menu_item_enter") + # VLM: the expanded menu is a vertical stack of cards ABOVE the FAB. + vlm_assert("structure_fab_menu_shape", + "Is there a vertical stack of menu item cards positioned above the " + "circular floating action button in the lower-right area?", + RESULTS_DIR, tag="layout", depth=0, jump_kind="transition") + + +@test +@and_test(expects=("structure_fab_menu_reverse",)) +def test_fab_menu_reverse(): + """FAB menu is reversible: BACK collapses it -> the 3 cards disappear and the + tree shape restores to the pre-open surface.""" + nodes = and_enter_main() + base = and_showing(nodes) + tap_node(node_by_id(nodes, "fab")) + settle("tap") + opened = ui() + open_has = node_by_id(opened, "fab_menu_item_enter") is not None + back() # scrim/back collapses the menu (observed: cards removed) + settle("tap") + closed = ui() + close_gone = node_by_id(closed, "fab_menu_item_enter") is None + cards_gone = len(find_by_class(closed, "CardView")) == 0 + restored = not surface_changed(base, and_showing(closed)) + ok = open_has and close_gone and cards_gone and restored + record("structure_fab_menu_reverse", bool(ok), + "" if ok else "behavior_wrong: fab menu did not collapse/restore on back", + depth=0, jump_kind="transition", + expect="FAB menu cards removed on back; surface restored to base") + + +@test +@and_test(expects=("structure_search_shape", + "structure_search_shape_vlm")) +def test_search_shape(): + """Search tap -> toolbar swaps to a SearchView subtree: search_src_text + + search_close_btn appear where the search_button was.""" + nodes = and_enter_main() + before = and_showing(nodes) + ok_tap = tap_node(node_by_id(nodes, "search_button")) + settle("tap") + after_nodes = ui() + after = and_showing(after_nodes) + src = node_by_id(after_nodes, "search_src_text") is not None + close_btn = node_by_id(after_nodes, "search_close_btn") is not None + btn_gone = node_by_id(after_nodes, "search_button") is None + ok = ok_tap and src and close_btn and btn_gone and surface_changed(before, after) + record("structure_search_shape", bool(ok), + "" if ok else "behavior_wrong: search did not swap toolbar to a SearchView subtree", + depth=0, jump_kind="transition", + expect="Toolbar -> SearchView: search_src_text/search_close_btn appear, search_button gone") + # VLM: an in-toolbar search field appears — magnifier + "Search" hint on the + # left, an X clear button on the right (observed layout). + vlm_assert("structure_search_shape", + "Is there a search input field across the top with a magnifier icon " + "on the left and an X (clear) icon on the right?", + RESULTS_DIR, tag="position", depth=0, jump_kind="transition") + + +@test +@and_test(expects=("structure_search_reverse",)) +def test_search_reverse(): + """Search is reversible: tapping the SearchView close button collapses it -> + search_src_text disappears and the normal search_button returns.""" + nodes = and_enter_main() + tap_node(node_by_id(nodes, "search_button")) + settle("tap") + opened = ui() + open_src = node_by_id(opened, "search_src_text") is not None + cb = node_by_id(opened, "search_close_btn") + tap_node(cb) + settle("tap") + closed = ui() + src_gone = node_by_id(closed, "search_src_text") is None + btn_back = node_by_id(closed, "search_button") is not None + fab_back = node_by_id(closed, "fab") is not None + ok = open_src and src_gone and btn_back and fab_back + record("structure_search_reverse", bool(ok), + "" if ok else "behavior_wrong: search did not collapse back to the normal toolbar", + depth=0, jump_kind="transition", + expect="SearchView collapses: search_src_text gone, search_button+fab restored") + + +@test +@and_test(expects=("structure_sort_popup_shape",)) +def test_sort_popup_shape(): + """Sort tap -> a popup subtree layers over Main: RadioButtons + the sort + option rows appear (none of which were in the tree before).""" + nodes = and_enter_main() + radios_before = len(find_by_class(nodes, "RadioButton")) + before = and_showing(nodes) + trigger = node_by_id(nodes, "action_sort") or find_node(nodes, content_desc="Sort") + ok_tap = tap_node(trigger) + settle("tap") + after_nodes = ui() + after = and_showing(after_nodes) + radios_after = len(find_by_class(after_nodes, "RadioButton")) + ok = ok_tap and radios_after > radios_before and surface_changed(before, after) + record("structure_sort_popup_shape", bool(ok), + "" if ok else f"behavior_wrong: sort popup added no radio subtree " + f"({radios_before}->{radios_after})", + depth=0, jump_kind="transition", + expect="Sort popup subtree appears: RadioButton count increases (0->>0)") + + +@test +@and_test(expects=("structure_overflow_menu_shape", + "structure_overflow_menu_shape_vlm")) +def test_overflow_menu_shape(): + """More-options tap -> an options popup subtree layers over Main (Settings / + About rows appear that were not in the tree before).""" + nodes = and_enter_main() + before = and_showing(nodes) + ov = find_node(nodes, content_desc="More options") + ok_tap = tap_node(ov) + settle("tap") + after_nodes = ui() + after = and_showing(after_nodes) + settings = find_node_ci(after_nodes, "Settings") is not None + about = find_node_ci(after_nodes, "About") is not None + ok = ok_tap and settings and about and surface_changed(before, after) + record("structure_overflow_menu_shape", bool(ok), + "" if ok else "behavior_wrong: overflow did not add a popup menu subtree", + depth=0, jump_kind="transition", + expect="Overflow popup subtree appears with Settings + About rows") + # VLM: overflow menu is a small popup anchored to the top-right corner. + vlm_assert("structure_overflow_menu_shape", + "Is there a small popup menu of text options anchored near the " + "top-right corner of the screen?", + RESULTS_DIR, tag="position", depth=0, jump_kind="transition") + + +@test +@and_test(expects=("structure_editentry_form_shape",)) +def test_editentry_form_shape(): + """EditEntryActivity presents the add-entry form cluster: the text fields + (name/issuer/secret) and the collapsed Advanced accordion header + SAVE — + a distinct shape from Main's list. depth>=1 (backed by and_enter_edit_entry).""" + and_enter_main() + nodes = and_enter_edit_entry() + if nodes is None: + record("structure_editentry_form_shape", False, + "setup_failed: could not reach EditEntryActivity", + depth=1, jump_kind="transition", + expect="EditEntryActivity form fields present") + return + edits = len(find_by_class(nodes, "EditText")) + have = all(node_by_id(nodes, i) is not None + for i in ("text_name", "text_issuer", "text_secret", + "accordian_header", "action_save")) + on_edit = "EditEntryActivity" in get_current_activity() + ok = on_edit and have and edits >= 4 + record("structure_editentry_form_shape", bool(ok), + "" if ok else f"behavior_wrong: edit-entry form cluster incomplete " + f"(EditText={edits})", + depth=1, jump_kind="transition", + expect="EditEntryActivity: >=4 EditText + accordian_header + action_save") + + +@test +@and_test(expects=("structure_accordion_expand", + "structure_accordion_expand_vlm")) +def test_accordion_expand(): + """Advanced accordion in EditEntryActivity: tapping the header expands the + subtree, adding the advanced controls (dropdown_type, dropdown_algo, + text_digits) and increasing the node count. Observed: 50 -> 75 nodes. + depth>=1 (backed by and_enter_edit_entry).""" + and_enter_main() + nodes = and_enter_edit_entry() + if nodes is None: + record("structure_accordion_expand", False, + "setup_failed: could not reach EditEntryActivity", + depth=1, jump_kind="transition", + expect="Advanced accordion expands to add dropdown_type/text_digits") + record("structure_accordion_expand_vlm", False, + "setup_failed: could not reach EditEntryActivity", + depth=1, jump_kind="transition", tag="position", + expect="two dropdowns side by side after Advanced expands") + return + n_before = len(nodes) + adv_before = node_by_id(nodes, "dropdown_type") is not None + before = and_showing(nodes) + ok_tap = tap_node(node_by_id(nodes, "accordian_header")) + settle("tap") + after_nodes = ui() + n_after = len(after_nodes) + after = and_showing(after_nodes) + adv_after = all(node_by_id(after_nodes, i) is not None + for i in ("dropdown_type", "dropdown_algo", "text_digits")) + ok = (ok_tap and not adv_before and adv_after and n_after > n_before + and surface_changed(before, after)) + record("structure_accordion_expand", bool(ok), + "" if ok else f"behavior_wrong: accordion did not expand advanced subtree " + f"(nodes {n_before}->{n_after})", + depth=1, jump_kind="transition", + expect="Accordion expands: dropdown_type/dropdown_algo/text_digits appear, node count grows") + # VLM: expanded Advanced shows the type + algorithm dropdowns SIDE BY SIDE. + vlm_assert("structure_accordion_expand", + "In the expanded Advanced section, are there two dropdown/spinner " + "controls placed side by side on the same row?", + RESULTS_DIR, tag="position", depth=1, jump_kind="transition") + + +@test +@and_test(expects=("structure_settings_list_shape", + "structure_settings_list_shape_vlm")) +def test_settings_list_shape(): + """Settings root (PreferencesActivity) is a scrollable RecyclerView list of + category rows — a distinct shape from Main. depth>=1 (and_enter_settings).""" + and_enter_main() + nodes = and_enter_settings() + if nodes is None: + record("structure_settings_list_shape", False, + "setup_failed: could not reach Settings", + depth=1, jump_kind="transition", + expect="PreferencesActivity RecyclerView list of category rows") + record("structure_settings_list_shape_vlm", False, + "setup_failed: could not reach Settings", + depth=1, jump_kind="transition", tag="layout", + expect="single vertical column of settings category rows") + return + on_prefs = "PreferencesActivity" in get_current_activity() + has_list = len(find_by_class(nodes, "RecyclerView")) >= 1 + # Several category rows are visible (each a TextView label in the list). + rows = sum(1 for lbl in ("Appearance", "Behavior", "Security", "Backups") + if find_node_ci(nodes, lbl) is not None) + ok = on_prefs and has_list and rows >= 3 + record("structure_settings_list_shape", bool(ok), + "" if ok else f"behavior_wrong: settings not a category list " + f"(recycler={has_list}, rows={rows})", + depth=1, jump_kind="transition", + expect="PreferencesActivity: RecyclerView with >=3 category rows") + # VLM: settings is a single-column vertical list of category rows. + vlm_assert("structure_settings_list_shape", + "Is the settings screen a single vertical column of stacked category " + "rows, each with a title and a short description line?", + RESULTS_DIR, tag="layout", depth=1, jump_kind="transition") + + +@test +@and_test(expects=("structure_create_populates_list", + "structure_create_populates_list_vlm")) +def test_create_populates_list(): + """Creating an entry flips the list shape: the empty-state placeholder + (textView5) is replaced by a populated list containing a profile_code row, + and the header gains entries_shown_count. depth 0 but a real shape delta.""" + nodes = and_enter_main() + empty_before = node_by_id(nodes, "textView5") is not None + code_before = node_by_id(nodes, "profile_code") is not None + after = _create_entry() + if after is None: + record("structure_create_populates_list", False, + "setup_failed: entry creation flow did not complete", + depth=0, jump_kind="transition", + expect="empty-state -> populated list with a profile_code row") + record("structure_create_populates_list_vlm", False, + "setup_failed: entry creation flow did not complete", + depth=0, jump_kind="transition", tag="layout", + expect="entry row: circular avatar left, two text lines right") + return + code_after = node_by_id(after, "profile_code") is not None + empty_gone = node_by_id(after, "textView5") is None + count_row = node_by_id(after, "entries_shown_count") is not None + ok = (empty_before and not code_before and code_after and empty_gone and count_row) + record("structure_create_populates_list", bool(ok), + "" if ok else "behavior_wrong: list shape did not change from empty to populated", + depth=0, jump_kind="transition", + expect="empty textView5 removed; profile_code row + entries_shown_count appear") + # VLM: an entry row = circular avatar tile on the left, text stacked to its right. + vlm_assert("structure_create_populates_list", + "Does the list now show an entry row with a circular avatar tile on " + "the left and two lines of text stacked to its right?", + RESULTS_DIR, tag="layout", depth=0, jump_kind="transition") + + +@test +@and_test(expects=("structure_longpress_action_mode", + "structure_longpress_action_mode_vlm")) +def test_longpress_action_mode(): + """Long-press an entry -> the normal toolbar is replaced by a contextual + action-mode bar: action_mode_close_button + Copy/Edit action buttons appear. + depth>=1 (backed by and_enter_edit_entry inside the create helper).""" + and_enter_main() + nodes = _create_entry() + if nodes is None or node_by_id(nodes, "profile_code") is None: + record("structure_longpress_action_mode", False, + "setup_failed: no entry to long-press", + depth=1, jump_kind="transition", + expect="contextual action-mode toolbar appears on long-press") + record("structure_longpress_action_mode_vlm", False, + "setup_failed: no entry to long-press", + depth=1, jump_kind="transition", tag="layout", + expect="row of action icons across the top bar") + return + row = node_by_id(nodes, "profile_code") + before = and_showing(nodes) + long_press(row) + settle("tap") + after_nodes = ui() + after = and_showing(after_nodes) + close_btn = node_by_id(after_nodes, "action_mode_close_button") is not None + copy = node_by_id(after_nodes, "action_copy") is not None + edit = node_by_id(after_nodes, "action_edit") is not None + ok = close_btn and copy and edit and surface_changed(before, after) + record("structure_longpress_action_mode", bool(ok), + "" if ok else "behavior_wrong: long-press did not open the contextual action mode", + depth=1, jump_kind="transition", + expect="action-mode bar: action_mode_close_button + action_copy + action_edit appear") + # VLM: the action-mode bar is a row of action icons across the top, with a + # back/close affordance at the far left (observed: back arrow + star/copy/ + # edit/QR icons). + vlm_assert("structure_longpress_action_mode", + "Is the top bar a row of several action icons (such as star, copy, " + "edit) with a back or close arrow icon at the far left?", + RESULTS_DIR, tag="layout", depth=1, jump_kind="transition") + + +@test +@and_test(expects=("structure_multi_entry_shape",)) +def test_multi_entry_shape(): + """Creating a second entry grows the list shape: the number of profile_code + rows increases from 1 to 2 (each row is one entry). depth 0 shape delta.""" + and_enter_main() + one = _create_entry(name="AlphaOne") + if one is None: + record("structure_multi_entry_shape", False, + "setup_failed: first entry not created", + depth=0, jump_kind="transition", + expect="profile_code row count 1 -> 2 after a second create") + return + rows_one = _count_by_id(one, "profile_code") + two = _create_entry(name="BravoTwo") + rows_two = _count_by_id(two, "profile_code") + ok = rows_one == 1 and rows_two == 2 + record("structure_multi_entry_shape", bool(ok), + "" if ok else f"behavior_wrong: profile_code row count not 1->2 " + f"({rows_one}->{rows_two})", + depth=0, jump_kind="transition", + expect="profile_code rows: 1 -> 2 after second create") + + +@test +@and_test(expects=("structure_main_overview_vlm",)) +def test_main_overview_vlm(): + """Whole-screen layout of Main with one entry: a single-column list with a + floating action button in the bottom-right. VLM-only (spatial).""" + and_enter_main() + nodes = _create_entry() + ok_setup = nodes is not None and node_by_id(nodes, "profile_code") is not None + if not ok_setup: + record("structure_main_overview_vlm", False, + "setup_failed: could not populate Main for the overview shot", + depth=0, jump_kind="transition", tag="position", + expect="single-column list with a FAB bottom-right") + return + vlm_assert("structure_main_overview", + "Is the main screen a single-column list of entries with a round " + "floating action button in the bottom-right corner?", + RESULTS_DIR, tag="position", depth=0, jump_kind="transition") + + +if __name__ == "__main__": + if not device_online(): + print("setup_failed: device offline — the adb tunnel may have dropped") + sys.exit(1) + run_suite(TESTS, "structure") diff --git a/android/beemdevelopment-aegis/tests/test_android_text.py b/android/beemdevelopment-aegis/tests/test_android_text.py new file mode 100644 index 0000000000000000000000000000000000000000..6fc9198d156f58a9429fad00d724cd33ef1d67c9 --- /dev/null +++ b/android/beemdevelopment-aegis/tests/test_android_text.py @@ -0,0 +1,935 @@ +#!/usr/bin/env python3 +"""TEXT lane — CONTENT/OUTPUT strings an interaction PRODUCES for the Aegis +Authenticator app (TOTP/HOTP 2FA). Sole owner of exact-string equality. + +Every test drives the app to a working state via the portable resource-id path, +performs the interaction that PRODUCES the string, and reads it back out of a +FRESH ui(). The discriminating half is the CHANGE: the count string flips +singular->plural, a summary flips 'System default'->'Light theme', a title flips +'Add new entry'->'Edit entry'. Nothing is keyed on the package / paths / +coordinates — the same file scores a from-scratch recreation at a different +package name. Every asserted string was OBSERVED on the running original; no +version/build/copyright string is ever asserted (source-derived, unfair). + +VLM budget = 4 records, all pointed at TEXT that does NOT reach the view tree: +the canvas-drawn avatar letter (two distinct issuers), the pink error-bar +styling, and the bold count digit. + +Run: + python3 test_android_text.py +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +# Valid base32 secrets (produce a live TOTP row); distinctive markers so a +# read-back cannot accidentally match pre-existing data. +SEC_A = "JBSWY3DPEHPK3PXP" + + +# ══════════════════════════════════════════════════════════════════════════════ +# Shared plumbing (own copies of the proven interaction/navigation helpers — the +# kit is imported, never re-implemented; these are app-specific orchestration). +# ══════════════════════════════════════════════════════════════════════════════ + +def _kb_off(): + """Lower the soft keyboard on the edit form WITHOUT navigating. The kit's + hide_keyboard() falls back to BACK, which on EditEntryActivity raises the + discard dialog; KEYCODE_ESCAPE lowers the IME with no navigation.""" + if keyboard_visible(): + press_key("KEYCODE_ESCAPE") + settle("keyboard") + + +def and_enter_main(clear=False): + """Get to MainActivity. clear=True wipes the vault first (virgin DB). + + Runs the 4-tap onboarding skip by resource-id only, choosing rb_none so the + vault opens directly on every relaunch (no unlock screen). Returns the last + fresh node list, or None if Main was never reached.""" + if clear: + clear_data() + restart_app() + wait_for_foreground() + n = ui() + if node_by_id(n, "btnNext"): + for rid in ("btnNext", "rb_none", "btnNext", "btnNext"): + t = node_by_id(n, rid) + if t is None or not tap_node(t): + return None + n = ui() + if node_by_id(n, "fab") is None: + return None + return n + + +def _count_text(nodes=None): + nodes = ui() if nodes is None else nodes + c = node_by_id(nodes, "entries_shown_count") + return (c or {}).get("text") + + +def and_enter_editor(): + """Main -> FAB menu -> Enter manually -> EditEntryActivity. Backs depth via + the and_enter_* NAME + an and_enter() call once the surface changes.""" + n = ui() + fab = node_by_id(n, "fab") + if fab is None or not tap_node(fab): + return False + n = ui() + enter = node_by_id(n, "fab_menu_item_enter") + if enter is None or not tap_node(enter): + return False + settle("tap") + if not get_current_activity().endswith("EditEntryActivity"): + return False + and_enter("editor") + return True + + +def and_create_entry(name, issuer, secret=SEC_A): + """FAB -> Enter manually -> fill name/issuer/secret -> SAVE. Returns True only + when we land back on Main with the new issuer visible.""" + if not and_enter_editor(): + return False + n = ui() + nm = node_by_id(n, "text_name") + if nm is None or not type_text(nm, name): + return False + _kb_off() + n = ui() + iss = node_by_id(n, "text_issuer") + if iss is None or not type_text(iss, issuer): + return False + _kb_off() + n = ui() + sec = node_by_id(n, "text_secret") + if sec is None or not type_text(sec, secret): + return False + _kb_off() + n = ui() + save = node_by_id(n, "action_save") + if save is None or not tap_node(save): + return False + n = ui() + if find_node_ci(n, "Error saving profile"): + return False + if find_node_ci(n, "Your changes have not been saved"): + sv = find_node(n, text="Save") + if sv: + tap_node(sv) + n = ui() + if not get_current_activity().endswith("MainActivity"): + return False + return find_node_ci(ui(), issuer) is not None + + +def and_open_action_mode(issuer=None): + """Long-press a row (the one with `issuer`, else the first) to enter the + contextual action mode. Returns True once action_mode_close_button appears.""" + n = ui() + row = None + if issuer: + for x in n: + if (x.get("resource-id", "").rsplit("/", 1)[-1] == "profile_issuer" + and x.get("text") == issuer): + row = x + break + if row is None: + row = node_by_id(n, "profile_issuer") + if row is None or not long_press(row): + return False + settle("tap") + if node_by_id(ui(), "action_mode_close_button") is None: + return False + and_enter("action_mode") + return True + + +def and_reach_settings_root(): + """Main -> overflow -> Settings root. Confirms arrival by the 'Settings' title + plus category rows. Counts one surface via and_enter().""" + mo = find_node(ui(), content_desc="More options") + if mo is None or not tap_node(mo): + return False + settle("tap") + item = find_node_ci(ui(), "Settings") + if item is None or not tap_node(item): + return False + settle("tap") + n = ui() + if find_node(n, text="Settings") is None or find_node_ci(n, "Appearance") is None: + return False + and_enter("settings") + return True + + +def and_reach_section(label, child): + """From the Settings ROOT, tap a category row and confirm the sub-screen: + `child` (a section-only element) is present and the root is left. `label` is + matched by the row `title` prefix so 'Import & Export' resolves from + 'Import'. Counts one surface via and_enter().""" + trigger = None + for n in ui(): + if n.get("resource-id", "").rsplit("/", 1)[-1] == "title" and \ + n.get("text", "").lower().startswith(label.lower()): + trigger = n + break + if trigger is None: + trigger = find_node_ci(ui(), label) + if trigger is None or not tap_node(trigger): + return False + settle("tap") + if find_node_ci(ui(), child) is None: + return False + and_enter(label) + return True + + +def and_reach_about(): + """Main -> overflow -> About. Confirms arrival by the 'Aegis Authenticator' + heading. Counts one surface via and_enter().""" + mo = find_node(ui(), content_desc="More options") + if mo is None or not tap_node(mo): + return False + settle("tap") + item = find_node_ci(ui(), "About") + if item is None or not tap_node(item): + return False + settle("tap") + if find_node_ci(ui(), "Aegis Authenticator") is None: + return False + and_enter("about") + return True + + +def _summary_under(nodes, title_text): + """The `summary` string of the preference row whose `title` == title_text. + Rows are (title, summary) sibling pairs stacked vertically; pick the summary + whose y sits just below the matching title and above the next title.""" + titles = sorted( + [(x["_bounds"][1], x.get("text", "")) for x in nodes + if x.get("resource-id", "").rsplit("/", 1)[-1] == "title" + and "_bounds" in x], + key=lambda p: p[0]) + summaries = sorted( + [(x["_bounds"][1], x.get("text", "")) for x in nodes + if x.get("resource-id", "").rsplit("/", 1)[-1] == "summary" + and "_bounds" in x], + key=lambda p: p[0]) + ty = None + next_ty = None + for i, (y, t) in enumerate(titles): + if t == title_text: + ty = y + next_ty = titles[i + 1][0] if i + 1 < len(titles) else 10 ** 9 + break + if ty is None: + return None + for y, s in summaries: + if ty <= y < next_ty: + return s + return None + + +def _norm(s): + return (s or "").strip().casefold() + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1. entries_shown_count reflects entry count: empty-state -> 1 (singular) -> +# 2 (plural). The singular/plural switch is a real content behavior. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_count_empty_state",)) +def test_count_empty_state(): + """A virgin vault shows NO 'Showing N entries' bar; it shows the empty-state + message instead. Assert the exact empty-state wording observed.""" + if and_enter_main(clear=True) is None: + record("text_count_empty_state", False, + "setup_failed: could not reach MainActivity", + depth=0, jump_kind="value", expect="'No entries found' empty state") + return + n = ui() + # No count bar on an empty vault; the empty-state heading is present instead. + no_count = _count_text(n) is None + heading = find_node_ci(n, "No entries found") is not None + ok = no_count and heading + record("text_count_empty_state", ok, + "" if ok else f"behavior_wrong: empty vault count={_count_text(n)!r} " + f"heading_present={heading} (expected no count + 'No entries found')", + depth=0, jump_kind="value", expect="'No entries found' + no count bar") + + +@and_test(expects=("text_count_singular_one",)) +def test_count_singular_one(): + if and_enter_main(clear=True) is None: + record("text_count_singular_one", False, + "setup_failed: could not reach MainActivity", + depth=0, jump_kind="value", expect="count 'Showing 1 entry'") + return + absent = _count_text() is None + if not and_create_entry("nOne", "iOne"): + record("text_count_singular_one", False, + "feature_missing: could not create an entry", + depth=0, jump_kind="value", expect="count 'Showing 1 entry'") + return + got = _count_text() + ok = absent and _norm(got) == _norm("Showing 1 entry") + record("text_count_singular_one", ok, + "" if ok else f"behavior_wrong: count={got!r} (expected 'Showing 1 entry')", + depth=0, jump_kind="value", expect="count 'Showing 1 entry' (singular)") + + +@and_test(expects=("text_count_plural_two",)) +def test_count_plural_two(): + """Discriminator: singular 'entry' -> plural 'entries' as the count crosses 1.""" + if and_enter_main(clear=True) is None: + record("text_count_plural_two", False, + "setup_failed: could not reach MainActivity", + depth=0, jump_kind="value", expect="count 'Showing 2 entries'") + return + if not and_create_entry("nA", "iA"): + record("text_count_plural_two", False, + "feature_missing: could not create the first entry", + depth=0, jump_kind="value", expect="count 'Showing 2 entries'") + return + singular = _count_text() + if not and_create_entry("nB", "iB"): + record("text_count_plural_two", False, + "behavior_wrong: could not create the second entry", + depth=0, jump_kind="value", expect="count 'Showing 2 entries'") + return + plural = _count_text() + ok = (_norm(singular) == _norm("Showing 1 entry") + and _norm(plural) == _norm("Showing 2 entries")) + record("text_count_plural_two", ok, + "" if ok else f"behavior_wrong: count {singular!r}->{plural!r} " + f"(expected 'Showing 1 entry' then 'Showing 2 entries')", + depth=0, jump_kind="value", expect="count 'Showing 2 entries' (plural)") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2. A new entry's issuer/name strings appear verbatim on its row. +# Observed format: profile_issuer=='TextCheckIssuer', profile_account_name=='(TextCheckName)' +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_new_entry_issuer_name",)) +def test_new_entry_issuer_name(): + if and_enter_main(clear=True) is None: + record("text_new_entry_issuer_name", False, + "setup_failed: could not reach MainActivity", + depth=0, jump_kind="value", + expect="row 'TextCheckIssuer' + '(TextCheckName)'") + return + absent = find_node_ci(ui(), "TextCheckIssuer") is None + if not and_create_entry("TextCheckName", "TextCheckIssuer"): + record("text_new_entry_issuer_name", False, + "feature_missing: could not create the entry", + depth=0, jump_kind="value", + expect="row 'TextCheckIssuer' + '(TextCheckName)'") + return + n = ui() + issuer = (node_by_id(n, "profile_issuer") or {}).get("text") + acct = (node_by_id(n, "profile_account_name") or {}).get("text") + ok = (absent and issuer == "TextCheckIssuer" and acct == "(TextCheckName)") + record("text_new_entry_issuer_name", ok, + "" if ok else f"behavior_wrong: issuer={issuer!r} account={acct!r} " + f"(expected 'TextCheckIssuer' and '(TextCheckName)')", + depth=0, jump_kind="value", + expect="profile_issuer 'TextCheckIssuer', profile_account_name '(TextCheckName)'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3. Search PRODUCES count strings: a matching query -> 'Showing 1 entry', +# a non-matching query 'ZZZQQ' -> 'Showing 0 entries'. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_search_count_strings",)) +def test_search_count_strings(): + if and_enter_main(clear=True) is None: + record("text_search_count_strings", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="value", + expect="'Showing 1 entry' (match) / 'Showing 0 entries' (no match)") + return + if not and_create_entry("SrchName", "SrchIssuer"): + record("text_search_count_strings", False, + "feature_missing: could not create an entry to search", + depth=1, jump_kind="value", + expect="'Showing 1 entry' (match) / 'Showing 0 entries' (no match)") + return + sb = node_by_id(ui(), "search_button") + if sb is None or not tap_node(sb): + record("text_search_count_strings", False, + "feature_missing: no Search control on the toolbar", + depth=1, jump_kind="value", + expect="'Showing 1 entry' (match) / 'Showing 0 entries' (no match)") + return + and_enter("search") + sst = node_by_id(ui(), "search_src_text") + if sst is None or not type_text(sst, "Srch"): + record("text_search_count_strings", False, + "setup_failed: search field not typable", + depth=1, jump_kind="value", + expect="'Showing 1 entry' (match) / 'Showing 0 entries' (no match)") + return + settle("text") + match_cnt = _count_text() + # Clear the field, then a non-matching query. + sst = node_by_id(ui(), "search_src_text") + tap_node(sst) + press_key("KEYCODE_MOVE_END") + for _ in range(20): + press_key("KEYCODE_DEL") + settle("text") + sst = node_by_id(ui(), "search_src_text") + type_text(sst, "ZZZQQ") + settle("text") + nomatch_cnt = _count_text() + ok = (_norm(match_cnt) == _norm("Showing 1 entry") + and _norm(nomatch_cnt) == _norm("Showing 0 entries")) + record("text_search_count_strings", ok, + "" if ok else f"behavior_wrong: match={match_cnt!r} nomatch={nomatch_cnt!r} " + f"(expected 'Showing 1 entry' / 'Showing 0 entries')", + depth=1, jump_kind="value", + expect="match 'Showing 1 entry', no-match 'Showing 0 entries'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4. Editor title strings: create form title 'Add new entry'; long-press -> +# Edit -> title 'Edit entry'. Assert both exact titles (depth>=1, backed). +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_title_add_new_entry",)) +def test_title_add_new_entry(): + if and_enter_main(clear=True) is None: + record("text_title_add_new_entry", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="value", expect="editor title 'Add new entry'") + return + absent = find_node_ci(ui(), "Add new entry") is None + if not and_enter_editor(): + record("text_title_add_new_entry", False, + "feature_missing: could not open the create form", + depth=1, jump_kind="value", expect="editor title 'Add new entry'") + return + present = find_node_ci(ui(), "Add new entry") is not None + ok = absent and present + record("text_title_add_new_entry", ok, + "" if ok else "behavior_wrong: create form title is not 'Add new entry'", + depth=1, jump_kind="value", expect="editor title 'Add new entry'") + + +@and_test(expects=("text_title_edit_entry",)) +def test_title_edit_entry(): + if and_enter_main(clear=True) is None or not and_create_entry("nEd", "iEd"): + record("text_title_edit_entry", False, + "setup_failed: could not create an entry to edit", + depth=2, jump_kind="value", expect="editor title 'Edit entry'") + return + absent = find_node_ci(ui(), "Edit entry") is None + if not and_open_action_mode("iEd"): + record("text_title_edit_entry", False, + "feature_missing: long-press did not open action mode", + depth=2, jump_kind="value", expect="editor title 'Edit entry'") + return + ed = node_by_id(ui(), "action_edit") + if ed is None or not tap_node(ed): + record("text_title_edit_entry", False, + "feature_missing: no Edit control in action mode", + depth=2, jump_kind="value", expect="editor title 'Edit entry'") + return + and_enter("editor") + present = find_node_ci(ui(), "Edit entry") is not None + ok = absent and present + record("text_title_edit_entry", ok, + "" if ok else "behavior_wrong: edit form title is not 'Edit entry'", + depth=2, jump_kind="value", expect="editor title 'Edit entry'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5. Theme selected-summary string (Appearance -> Theme dialog -> Light) -> +# the summary under 'Theme' becomes 'Selected: Light theme'. +# NOTE theme selection recreates the activity — re-dump. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_theme_summary",)) +def test_theme_summary(): + if and_enter_main(clear=True) is None: + record("text_theme_summary", False, + "setup_failed: could not reach MainActivity", + depth=2, jump_kind="value", expect="Theme summary 'Selected: Light theme'") + return + if not (and_reach_settings_root() + and and_reach_section("Appearance", "Dynamic colors")): + record("text_theme_summary", False, + "setup_failed: could not reach Appearance settings", + depth=2, jump_kind="value", expect="Theme summary 'Selected: Light theme'") + return + before = _summary_under(ui(), "Theme") + th = find_node_ci(ui(), "Theme") + if th is None or not tap_node(th): + record("text_theme_summary", False, + "feature_missing: no Theme preference row", + depth=2, jump_kind="value", expect="Theme summary 'Selected: Light theme'") + return + settle("tap") + if find_node_ci(ui(), "Select your desired theme") is None: + record("text_theme_summary", False, + "feature_missing: Theme dialog did not open", + depth=2, jump_kind="value", expect="Theme summary 'Selected: Light theme'") + return + lt = find_node_ci(ui(), "Light theme") + if lt is None or not tap_node(lt): + record("text_theme_summary", False, + "behavior_wrong: no 'Light theme' option in the dialog", + depth=2, jump_kind="value", expect="Theme summary 'Selected: Light theme'") + return + settle("launch") # activity recreated after selecting a theme + after = _summary_under(ui(), "Theme") + ok = (_norm(before) == _norm("Selected: System default") + and _norm(after) == _norm("Selected: Light theme")) + # Reset to System default so later launches repaint normally. + th = find_node_ci(ui(), "Theme") + if th and tap_node(th): + settle("tap") + sd = find_node_ci(ui(), "System default") + if sd: + tap_node(sd) + settle("launch") + record("text_theme_summary", ok, + "" if ok else f"behavior_wrong: Theme summary {before!r}->{after!r} " + f"(expected 'Selected: System default'->'Selected: Light theme')", + depth=2, jump_kind="value", expect="Theme summary 'Selected: Light theme'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 6. View mode summary string (Appearance): default 'Selected: Normal'. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_view_mode_summary",)) +def test_view_mode_summary(): + if and_enter_main(clear=True) is None: + record("text_view_mode_summary", False, + "setup_failed: could not reach MainActivity", + depth=2, jump_kind="value", expect="View mode summary 'Selected: Normal'") + return + if not (and_reach_settings_root() + and and_reach_section("Appearance", "View mode")): + record("text_view_mode_summary", False, + "setup_failed: could not reach Appearance settings", + depth=2, jump_kind="value", expect="View mode summary 'Selected: Normal'") + return + got = _summary_under(ui(), "View mode") + ok = _norm(got) == _norm("Selected: Normal") + record("text_view_mode_summary", ok, + "" if ok else f"behavior_wrong: View mode summary={got!r} " + f"(expected 'Selected: Normal')", + depth=2, jump_kind="value", expect="View mode summary 'Selected: Normal'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 7. Copy-tokens summary (Behavior): default 'Selected: Never'. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_copy_tokens_summary",)) +def test_copy_tokens_summary(): + if and_enter_main(clear=True) is None: + record("text_copy_tokens_summary", False, + "setup_failed: could not reach MainActivity", + depth=2, jump_kind="value", + expect="'Copy tokens to the clipboard' summary 'Selected: Never'") + return + if not (and_reach_settings_root() + and and_reach_section("Behavior", "Haptic feedback")): + record("text_copy_tokens_summary", False, + "setup_failed: could not reach Behavior settings", + depth=2, jump_kind="value", + expect="'Copy tokens to the clipboard' summary 'Selected: Never'") + return + got = _summary_under(ui(), "Copy tokens to the clipboard") + ok = _norm(got) == _norm("Selected: Never") + record("text_copy_tokens_summary", ok, + "" if ok else f"behavior_wrong: Copy-tokens summary={got!r} " + f"(expected 'Selected: Never')", + depth=2, jump_kind="value", + expect="Copy-tokens summary 'Selected: Never'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 8. Advanced-accordion default strings (EditEntry): the form PRODUCES +# dropdown_type='TOTP', dropdown_algo='SHA1', period='30', digits='6', usage='0'. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_advanced_defaults",)) +def test_advanced_defaults(): + if and_enter_main(clear=True) is None: + record("text_advanced_defaults", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="value", + expect="Advanced defaults TOTP/SHA1/30/6/0") + return + if not and_enter_editor(): + record("text_advanced_defaults", False, + "feature_missing: could not open the create form", + depth=1, jump_kind="value", + expect="Advanced defaults TOTP/SHA1/30/6/0") + return + # Expand the Advanced accordion to reveal the type/algo/period/digits/usage fields. + adv = None + for x in ui(): + if _norm(x.get("text", "")) == _norm("Advanced"): + adv = x + break + if adv is None or not tap_node(adv): + record("text_advanced_defaults", False, + "feature_missing: no Advanced accordion in the create form", + depth=1, jump_kind="value", + expect="Advanced defaults TOTP/SHA1/30/6/0") + return + settle("tap") + n = ui() + got = {rid: (node_by_id(n, rid) or {}).get("text") for rid in + ("dropdown_type", "dropdown_algo", "text_period_counter", + "text_digits", "text_usage_count")} + want = {"dropdown_type": "TOTP", "dropdown_algo": "SHA1", + "text_period_counter": "30", "text_digits": "6", + "text_usage_count": "0"} + ok = all(_norm(got[k]) == _norm(v) for k, v in want.items()) + record("text_advanced_defaults", ok, + "" if ok else f"behavior_wrong: advanced defaults {got!r} (expected {want!r})", + depth=1, jump_kind="value", + expect="TOTP / SHA1 / 30 / 6 / 0 in the Advanced section") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 9. Group field default + dialog strings (EditEntry): text_group='No group'; +# tapping it opens a dialog titled 'Groups' with a 'New group…' item. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_group_default_and_dialog",)) +def test_group_default_and_dialog(): + if and_enter_main(clear=True) is None: + record("text_group_default_and_dialog", False, + "setup_failed: could not reach MainActivity", + depth=2, jump_kind="value", + expect="group 'No group' + dialog 'Groups'/'New group…'") + return + if not and_enter_editor(): + record("text_group_default_and_dialog", False, + "feature_missing: could not open the create form", + depth=2, jump_kind="value", + expect="group 'No group' + dialog 'Groups'/'New group…'") + return + grp = node_by_id(ui(), "text_group") + default = (grp or {}).get("text") + if grp is None or not tap_node(grp): + record("text_group_default_and_dialog", False, + "feature_missing: no group field in the create form", + depth=2, jump_kind="value", + expect="group 'No group' + dialog 'Groups'/'New group…'") + return + settle("tap") + and_enter("group_dialog") + n = ui() + title = find_node_ci(n, "Groups") is not None + new_group = find_node_ci(n, "New group…") is not None + ok = (_norm(default) == _norm("No group") and title and new_group) + record("text_group_default_and_dialog", ok, + "" if ok else f"behavior_wrong: group default={default!r} " + f"dialog_title={title} new_group_item={new_group} " + f"(expected 'No group' + 'Groups'/'New group…')", + depth=2, jump_kind="value", + expect="text_group 'No group'; dialog title 'Groups'; item 'New group…'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 10. Field LABELS the form produces (EditEntry): the floating labels render as +# the row text 'Name'/'Issuer'/'Secret' (app-unique static strings a +# recreation must get right). +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_field_labels",)) +def test_field_labels(): + if and_enter_main(clear=True) is None: + record("text_field_labels", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="value", expect="labels 'Name'/'Issuer'/'Secret'") + return + absent = find_node_ci(ui(), "Secret") is None + if not and_enter_editor(): + record("text_field_labels", False, + "feature_missing: could not open the create form", + depth=1, jump_kind="value", expect="labels 'Name'/'Issuer'/'Secret'") + return + n = ui() + name = (node_by_id(n, "text_name") or {}).get("text") + issuer = (node_by_id(n, "text_issuer") or {}).get("text") + secret = (node_by_id(n, "text_secret") or {}).get("text") + ok = (absent and _norm(name) == _norm("Name") + and _norm(issuer) == _norm("Issuer") + and _norm(secret) == _norm("Secret")) + record("text_field_labels", ok, + "" if ok else f"behavior_wrong: labels name={name!r} issuer={issuer!r} " + f"secret={secret!r} (expected 'Name'/'Issuer'/'Secret')", + depth=1, jump_kind="value", + expect="field labels 'Name', 'Issuer', 'Secret'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 11. About-screen strings: 'Aegis Authenticator', 'GitHub', 'License', +# 'Beem Development', 'Write an email', 'Visit our website'. (Version string +# is source-derived — NOT asserted.) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_about_strings",)) +def test_about_strings(): + if and_enter_main(clear=True) is None: + record("text_about_strings", False, + "setup_failed: could not reach MainActivity", + depth=1, jump_kind="value", + expect="About shows GitHub/License/Beem Development/Write an email") + return + absent = find_node_ci(ui(), "Beem Development") is None + if not and_reach_about(): + record("text_about_strings", False, + "feature_missing: could not reach the About screen", + depth=1, jump_kind="value", + expect="About shows GitHub/License/Beem Development/Write an email") + return + n = ui() + want = ["Aegis Authenticator", "GitHub", "License", "Beem Development", + "Write an email", "Visit our website"] + missing = [w for w in want if find_node_ci(n, w) is None] + ok = absent and not missing + record("text_about_strings", ok, + "" if ok else f"behavior_wrong: About missing {missing!r}", + depth=1, jump_kind="value", + expect="'Aegis Authenticator','GitHub','License','Beem Development'," + "'Write an email','Visit our website'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 12. Sort-popup option strings: the popup shows 'Custom', 'Account (A to Z)', +# 'Issuer (A to Z)', 'Usage count', 'Last used', etc. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_sort_options",)) +def test_sort_options(): + if and_enter_main(clear=True) is None or not and_create_entry("nSort", "iSort"): + record("text_sort_options", False, + "setup_failed: could not create an entry to sort", + depth=1, jump_kind="value", + expect="sort options Custom/Account (A to Z)/Issuer (A to Z)/Usage count") + return + absent = find_node_ci(ui(), "Account (A to Z)") is None + srt = find_node(ui(), content_desc="Sort") + if srt is None or not tap_node(srt): + record("text_sort_options", False, + "feature_missing: no Sort control on the toolbar", + depth=1, jump_kind="value", + expect="sort options Custom/Account (A to Z)/Issuer (A to Z)/Usage count") + return + and_enter("sort_popup") + n = ui() + want = ["Custom", "Account (A to Z)", "Account (Z to A)", "Issuer (A to Z)", + "Issuer (Z to A)", "Usage count", "Last used"] + missing = [w for w in want if find_node_ci(n, w) is None] + ok = absent and not missing + back() # dismiss the popup without changing the sort + record("text_sort_options", ok, + "" if ok else f"behavior_wrong: sort popup missing {missing!r}", + depth=1, jump_kind="value", + expect="Custom / Account (A to Z) / Issuer (A to Z) / Usage count / Last used") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 13. Action-mode content-desc strings an interaction reveals: 'Done', 'Copy', +# 'Edit', 'Transfer' — plus the always-present FAB desc 'Add new entry'. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_action_mode_descs",)) +def test_action_mode_descs(): + if and_enter_main(clear=True) is None or not and_create_entry("nDesc", "iDesc"): + record("text_action_mode_descs", False, + "setup_failed: could not create an entry to long-press", + depth=1, jump_kind="value", + expect="content-desc 'Done'/'Copy'/'Edit'/'Transfer'") + return + absent = find_node(ui(), content_desc="Done") is None + if not and_open_action_mode("iDesc"): + record("text_action_mode_descs", False, + "feature_missing: long-press did not open action mode", + depth=1, jump_kind="value", + expect="content-desc 'Done'/'Copy'/'Edit'/'Transfer'") + return + n = ui() + want = ["Done", "Copy", "Edit", "Transfer", "Favorite"] + missing = [w for w in want if find_node(n, content_desc=w) is None] + ok = absent and not missing + # leave action mode cleanly + done = node_by_id(ui(), "action_mode_close_button") + if done: + tap_node(done) + record("text_action_mode_descs", ok, + "" if ok else f"behavior_wrong: action-mode content-desc missing {missing!r}", + depth=1, jump_kind="value", + expect="content-desc 'Done','Copy','Edit','Transfer','Favorite'") + + +@and_test(expects=("text_fab_content_desc",)) +def test_fab_content_desc(): + """The add-entry FAB carries content-desc 'Add new entry' (an icon-only + control a recreation must label correctly).""" + if and_enter_main(clear=True) is None: + record("text_fab_content_desc", False, + "setup_failed: could not reach MainActivity", + depth=0, jump_kind="value", expect="FAB content-desc 'Add new entry'") + return + fab = node_by_id(ui(), "fab") + desc = (fab or {}).get("content-desc") + ok = _norm(desc) == _norm("Add new entry") + record("text_fab_content_desc", ok, + "" if ok else f"behavior_wrong: FAB content-desc={desc!r} " + f"(expected 'Add new entry')", + depth=0, jump_kind="value", expect="FAB content-desc 'Add new entry'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 14. Persistent info-bar string: the app renders 'Changes are not backed up'. +# It is ABSENT on the empty-onboarding-only surface? — it renders on Main +# regardless, so assert its exact wording (content the app produces). +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_error_bar_string",)) +def test_error_bar_string(): + if and_enter_main(clear=True) is None: + record("text_error_bar_string", False, + "setup_failed: could not reach MainActivity", + depth=0, jump_kind="value", expect="info bar 'Changes are not backed up'") + return + n = ui() + bar = node_by_id(n, "text_error_bar") + got = (bar or {}).get("text") if bar else \ + (find_node_ci(n, "Changes are not backed up") or {}).get("text") + ok = _norm(got) == _norm("Changes are not backed up") + record("text_error_bar_string", ok, + "" if ok else f"behavior_wrong: info bar text={got!r} " + f"(expected 'Changes are not backed up')", + depth=0, jump_kind="value", expect="info bar 'Changes are not backed up'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# ── VLM cluster (budget = 4): TEXT that does NOT reach the view tree ────────── +# The avatar tile letter is canvas-drawn (no TextView carries it), so it is a +# legitimate opaque-text target; the error-bar colour and the bold count digit +# are rendered properties of strings that the dump cannot expose. +# ══════════════════════════════════════════════════════════════════════════════ + +# VLM #1 — canvas-drawn avatar letter 'T' for issuer 'Tango' (opaque content) +@and_test(expects=("text_avatar_letter_tango_vlm",)) +def test_avatar_letter_tango_vlm(): + if and_enter_main(clear=True) is None or not and_create_entry("Tango", "Tango"): + record("text_avatar_letter_tango_vlm", False, + "setup_failed: could not create the 'Tango' entry", + depth=0, jump_kind="value", tag="content") + return + vlm_assert("text_avatar_letter_tango", + "This authenticator list has a single entry whose issuer is " + "'Tango'. Inside the round coloured avatar circle on the left of " + "that row, is the capital letter 'T' shown?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="content") + + +# VLM #2 — canvas-drawn avatar letter 'Q' for issuer 'Quartz' (opaque content) +@and_test(expects=("text_avatar_letter_quartz_vlm",)) +def test_avatar_letter_quartz_vlm(): + if and_enter_main(clear=True) is None or not and_create_entry("Quartz", "Quartz"): + record("text_avatar_letter_quartz_vlm", False, + "setup_failed: could not create the 'Quartz' entry", + depth=0, jump_kind="value", tag="content") + return + vlm_assert("text_avatar_letter_quartz", + "This authenticator list has a single entry whose issuer is " + "'Quartz'. Inside the round coloured avatar circle on the left of " + "that row, is the capital letter 'Q' shown (NOT 'T' or any other " + "letter)?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="content") + + +# VLM #3 — the 'Changes are not backed up' text sits in a pink/red banner (color) +@and_test(expects=("text_error_bar_color_vlm",)) +def test_error_bar_color_vlm(): + if and_enter_main(clear=True) is None or not and_create_entry("nBar", "iBar"): + record("text_error_bar_color_vlm", False, + "setup_failed: could not create an entry", + depth=0, jump_kind="value", tag="color") + return + # Confirm the words are actually present before asking about their styling. + if find_node_ci(ui(), "Changes are not backed up") is None: + record("text_error_bar_color_vlm", False, + "behavior_wrong: the 'Changes are not backed up' bar is absent", + depth=0, jump_kind="value", tag="color") + return + vlm_assert("text_error_bar_color", + "Near the top of this authenticator screen, is the text 'Changes " + "are not backed up' displayed inside a pink / light-red rounded " + "banner (a coloured warning bar), rather than as plain text on the " + "white background?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="color") + + +# VLM #4 — the count digit in 'Showing 1 entry' is emphasised/bold (size/weight) +@and_test(expects=("text_count_bold_digit_vlm",)) +def test_count_bold_digit_vlm(): + if and_enter_main(clear=True) is None or not and_create_entry("nBold", "iBold"): + record("text_count_bold_digit_vlm", False, + "setup_failed: could not create an entry", + depth=0, jump_kind="value", tag="size") + return + if _norm(_count_text()) != _norm("Showing 1 entry"): + record("text_count_bold_digit_vlm", False, + "behavior_wrong: count is not 'Showing 1 entry' before the styling check", + depth=0, jump_kind="value", tag="size") + return + vlm_assert("text_count_bold_digit", + "At the bottom of the entry list is the line 'Showing 1 entry'. " + "Is the number '1' rendered noticeably bolder / heavier in weight " + "than the surrounding words 'Showing' and 'entry'?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="size") + + +TESTS = [ + test_count_empty_state, + test_count_singular_one, + test_count_plural_two, + test_new_entry_issuer_name, + test_search_count_strings, + test_title_add_new_entry, + test_title_edit_entry, + test_theme_summary, + test_view_mode_summary, + test_copy_tokens_summary, + test_advanced_defaults, + test_group_default_and_dialog, + test_field_labels, + test_about_strings, + test_sort_options, + test_action_mode_descs, + test_fab_content_desc, + test_error_bar_string, + test_avatar_letter_tango_vlm, + test_avatar_letter_quartz_vlm, + test_error_bar_color_vlm, + test_count_bold_digit_vlm, +] + + +if __name__ == "__main__": + if not device_online(): + print("device offline — aborting") + sys.exit(2) + run_suite(TESTS, "text") diff --git a/android/beemdevelopment-aegis/tests/test_manifest.json b/android/beemdevelopment-aegis/tests/test_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..6c63eed3f31daa267f104c2d8ed15ce78eedcc25 --- /dev/null +++ b/android/beemdevelopment-aegis/tests/test_manifest.json @@ -0,0 +1,761 @@ +{ + "manifest_version": 1, + "kit_api_version": 1, + "task_id": "Aegis", + "baseline_model": "claude-opus-4-8", + "baseline_package": "", + "total": 100, + "manifest_sha": "1005a3a63b40", + "tests": [ + { + "name": "computation::computation_code_accent_color_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_code_charset", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_code_grouped_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_code_large_font_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_code_stable_in_period", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_copy_matches_display", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_default_grouping_format", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_default_six_digits", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_diff_secret_diff_code", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_digits_contrast", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_digits_eight", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_digits_field_default_six", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_eight_grouping_format", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_eight_wider_than_six_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_period_field_default_thirty", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_same_secret_same_code", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_case_insensitive", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_matches_none", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_matches_one", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_search_present_then_absent", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_type_default_totp", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_action_mode_done_exits", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_cancel_create_no_phantom", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_context_more_menu", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_create_absent_then_present", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_create_entry", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_edit_middle_keeps_others", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_edit_persists", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_edit_prefilled", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_edit_saves_new_name", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_favorite_pins_top", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_longpress_action_mode", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_multi_two_entries", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_persist_multi_integrity", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_persist_single", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_appearance_back_to_settings", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_backstack_2hop_unwind", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_edit_entry_back_to_main", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_fab_menu_open", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_open_overflow_menu", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_reach_about", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_reach_add_entry", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_reach_appearance", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_reach_audit_log", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_reach_backups", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_reach_behavior", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_reach_edit_entry", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_reach_icon_packs", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_reach_import_export", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_reach_security", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_reach_settings", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_search_open", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_settings_back_to_main", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "states::states_advanced_accordion_expand", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_advanced_accordion_expand_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_behavior_focus_search_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_behavior_haptic_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_behavior_haptic_toggle_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_behavior_minimize_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_behavior_minimize_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_behavior_multiselect_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_default_theme_light_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dynamic_colors_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_focus_search_on_start", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_search_field_focused", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_secret_mask_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_secret_mask_toggle_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_secret_masked_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_show_account_name_select", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_sort_issuer_reorders", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_sort_issuer_reorders_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_sort_order_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_switch_off_track_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_switch_on_track_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_theme_dialog_checkmark_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_theme_persists_summary", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_theme_persists_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_theme_select_light", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_theme_select_light_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_view_mode_compact", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "structure::structure_accordion_expand", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_create_populates_list", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_editentry_form_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_fab_menu_reverse", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_fab_menu_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_fab", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_launch", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_toolbar", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_longpress_action_mode", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_multi_entry_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_overflow_menu_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_search_reverse", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_search_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_list_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_sort_popup_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "text::text_count_empty_state", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_count_plural_two", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_count_singular_one", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_new_entry_issuer_name", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_search_count_strings", + "module": "text", + "baseline_status": "passed" + } + ], + "ignored": [ + { + "name": "interaction::interaction_action_toolbar_layout_vlm", + "module": "interaction", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "interaction::interaction_fab_menu_layout_vlm", + "module": "interaction", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "interaction::interaction_favorite_marker_vlm", + "module": "interaction", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "interaction::interaction_longpress_highlight_vlm", + "module": "interaction", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "interaction::interaction_persist_highlight_gone_vlm", + "module": "interaction", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "interaction::interaction_row_avatar_letter_vlm", + "module": "interaction", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "interaction::interaction_row_avatar_vlm", + "module": "interaction", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "interaction::interaction_row_card_shape_vlm", + "module": "interaction", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "interaction::interaction_row_code_color_vlm", + "module": "interaction", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "navigation::navigation_fab_menu_open_vlm", + "module": "navigation", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "navigation::navigation_reach_about_vlm", + "module": "navigation", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "navigation::navigation_reach_add_entry_vlm", + "module": "navigation", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "navigation::navigation_reach_appearance_vlm", + "module": "navigation", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "navigation::navigation_reach_settings_vlm", + "module": "navigation", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "navigation::navigation_search_open_vlm", + "module": "navigation", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "structure::structure_accordion_expand_vlm", + "module": "structure", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "structure::structure_create_populates_list_vlm", + "module": "structure", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "structure::structure_fab_menu_shape_vlm", + "module": "structure", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "structure::structure_longpress_action_mode_vlm", + "module": "structure", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "structure::structure_main_overview_vlm", + "module": "structure", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "structure::structure_overflow_menu_shape_vlm", + "module": "structure", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "structure::structure_search_shape_vlm", + "module": "structure", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "structure::structure_settings_list_shape_vlm", + "module": "structure", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "text::text_title_add_new_entry", + "module": "text", + "reason": "baseline_fail", + "baseline_status": "failed", + "message": "behavior_wrong: create form title is not 'Add new entry'" + } + ], + "vlm_assertions": [ + { + "name": "computation::computation_code_accent_color_vlm", + "module": "computation", + "tag": "color" + }, + { + "name": "computation::computation_code_large_font_vlm", + "module": "computation", + "tag": "size" + }, + { + "name": "computation::computation_code_grouped_vlm", + "module": "computation", + "tag": "position" + }, + { + "name": "computation::computation_eight_wider_than_six_vlm", + "module": "computation", + "tag": "size" + }, + { + "name": "states::states_behavior_haptic_toggle_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_theme_select_light_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_theme_persists_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_theme_dialog_checkmark_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_sort_issuer_reorders_vlm", + "module": "states", + "tag": "position" + }, + { + "name": "states::states_secret_masked_vlm", + "module": "states", + "tag": "content" + }, + { + "name": "states::states_secret_mask_toggle_vlm", + "module": "states", + "tag": "content" + }, + { + "name": "states::states_advanced_accordion_expand_vlm", + "module": "states", + "tag": "layout" + }, + { + "name": "states::states_switch_off_track_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_switch_on_track_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_default_theme_light_vlm", + "module": "states", + "tag": "color" + } + ], + "vlm_total": 15, + "n_vlm_unverified": 23, + "vlm_log_found": true +} \ No newline at end of file diff --git a/android/beemdevelopment-aegis/vlm_assertions.json b/android/beemdevelopment-aegis/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..579e96054b80723ec0f8d8d74655a9c54d5610b9 --- /dev/null +++ b/android/beemdevelopment-aegis/vlm_assertions.json @@ -0,0 +1,819 @@ +{ + "schema_version": 2, + "instance_id": "android/beemdevelopment-aegis", + "grading": { + "mode": "inline", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 40, + "with_verdict": 38, + "calibrated": 0, + "usable": null, + "scored_records": 38, + "unbacked_records": 23, + "unbacked_sample": [ + "interaction_longpress_highlight_vlm", + "interaction_favorite_marker_vlm", + "interaction_row_avatar_vlm", + "interaction_row_avatar_letter_vlm", + "interaction_row_card_shape_vlm", + "interaction_row_code_color_vlm", + "interaction_fab_menu_layout_vlm", + "interaction_action_toolbar_layout_vlm" + ] + }, + "assertions": [ + { + "id": "computation_code_accent_color_vlm", + "screenshot": "computation_code_accent_color_vlm.png", + "assertion": "On the single authenticator entry row, are the large numeric TOTP code digits rendered in a distinct coloured accent (for example a blue/teal tint) that is clearly DIFFERENT from the plain black/dark issuer and account-name text on the same row?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "computation_code_accent_color", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_code_large_font_vlm", + "screenshot": "computation_code_large_font_vlm.png", + "assertion": "On the single authenticator entry row, are the numeric TOTP code digits rendered in a noticeably LARGER font than the smaller issuer/account-name text on the same row (i.e. the code is the most prominent text)?", + "form": "question", + "expected": true, + "aspect": "size", + "modality": null, + "links_to": "computation_code_large_font", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_code_grouped_vlm", + "screenshot": "computation_code_grouped_vlm.png", + "assertion": "Look at the six-digit TOTP code on the entry row. Is it displayed as TWO groups of three digits separated by a visible gap/space (for example '123 456'), rather than six digits with no gap?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "computation_code_grouped", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_eight_wider_than_six_vlm", + "screenshot": "computation_eight_wider_than_six_vlm.png", + "assertion": "This authenticator list has two entries. One shows a six-digit code and the other shows an eight-digit code. Is the eight-digit code visibly WIDER (occupies more horizontal space) than the six-digit code?", + "form": "question", + "expected": true, + "aspect": "size", + "modality": null, + "links_to": "computation_eight_wider_than_six", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_behavior_haptic_toggle_vlm", + "screenshot": "states_behavior_haptic_toggle_vlm.png", + "assertion": "In this settings list, look at the on/off toggle switch on the 'Haptic feedback' row. Is that switch in the OFF position, i.e. its thumb is on the LEFT and its track is grey/uncoloured (not a filled green/accent colour)?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_behavior_haptic_toggle", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_theme_select_light_vlm", + "screenshot": "states_theme_select_light_vlm.png", + "assertion": "Light theme was just selected. Is the overall screen background light/white (a bright page) with dark text, rather than a dark or black background?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_theme_select_light", + "rigor": { + "jump_kind": "value", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_theme_persists_vlm", + "screenshot": "states_theme_persists_vlm.png", + "assertion": "This authenticator app was just relaunched after Light theme was chosen. Is its main screen still shown with a light/white background (bright page, dark text) rather than a dark/black background?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_theme_persists", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_theme_dialog_checkmark_vlm", + "screenshot": "states_theme_dialog_checkmark_vlm.png", + "assertion": "This is a single-choice theme picker dialog listing Light theme, Dark theme, AMOLED theme and System default options. Is exactly ONE option marked with a filled/selected radio button (a round selected indicator) while the others are unselected?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_theme_dialog_checkmark", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_view_mode_compact_vlm", + "screenshot": "states_view_mode_compact_vlm.png", + "assertion": "This authenticator list is now in COMPACT view mode. Is the single entry row drawn in a dense/compact style — a short row with small text and little vertical padding, rather than a tall roomy card?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "states_view_mode_compact", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_sort_issuer_reorders_vlm", + "screenshot": "states_sort_issuer_reorders_vlm.png", + "assertion": "This authenticator list has two entries, one for issuer 'Alpha' and one for issuer 'Bravo', after sorting by issuer A to Z. Is the 'Alpha' entry positioned ABOVE the 'Bravo' entry in the list?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "states_sort_issuer_reorders", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_secret_mask_toggle_vlm", + "screenshot": "states_secret_mask_toggle_vlm.png", + "assertion": "On this add-entry form, the 'Secret' field's reveal (eye) button was just tapped. Is the secret shown as readable plain-text characters (the value 'JBSWY3DPEHPK3PXP') rather than as masked dots/asterisks?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "states_secret_mask_toggle", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_advanced_accordion_expand_vlm", + "screenshot": "states_advanced_accordion_expand_vlm.png", + "assertion": "The 'Advanced' section of this add-entry form was just expanded. Are extra input rows now visible below the Advanced header (such as a token 'Type', an 'Algorithm', a 'Period' and a 'Digits' field) that were hidden before?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "states_advanced_accordion_expand", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_switch_off_track_vlm", + "screenshot": "states_switch_off_track_vlm.png", + "assertion": "In this settings list, look at the on/off toggle switch on the 'Minimize on copy' row. Is that switch OFF — its thumb on the LEFT and its track a plain grey/uncoloured tone (not a filled green or coloured accent)?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_switch_off_track", + "rigor": { + "jump_kind": "value", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_switch_on_track_vlm", + "screenshot": "states_switch_on_track_vlm.png", + "assertion": "In this settings list, look at the on/off toggle switch on the 'Haptic feedback' row. Is that switch ON — its thumb on the RIGHT and its track filled with a coloured/accent tone (e.g. green/blue) rather than plain grey?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_switch_on_track", + "rigor": { + "jump_kind": "value", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_default_theme_dark_vlm", + "screenshot": "states_default_theme_dark_vlm.png", + "assertion": "This authenticator app is on its default theme. Is its main screen background dark (near-black / very dark grey) with light-coloured text, rather than a bright white page?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_default_theme_dark", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_secret_masked_vlm", + "screenshot": "states_secret_masked_vlm.png", + "assertion": "On this add-entry form, look at the 'Secret' input field. Is its value shown as masked characters (a row of dots or bullets / asterisks) rather than readable plain-text letters and digits?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "states_secret_masked", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_default_theme_light_vlm", + "screenshot": "states_default_theme_light_vlm.png", + "assertion": "This authenticator app is on its default (freshly installed) theme. Is its main screen background light — a bright white / very light page with dark text — rather than a dark or black background?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_default_theme_light", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_longpress_highlight_vlm", + "screenshot": "interaction_longpress_highlight_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "interaction_longpress_highlight", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_favorite_marker_vlm", + "screenshot": "interaction_favorite_marker_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "interaction_favorite_marker", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_row_avatar_vlm", + "screenshot": "interaction_row_avatar_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "interaction_row_avatar", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_row_avatar_letter_vlm", + "screenshot": "interaction_row_avatar_letter_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "interaction_row_avatar_letter", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_row_card_shape_vlm", + "screenshot": "interaction_row_card_shape_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "interaction_row_card_shape", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_row_code_color_vlm", + "screenshot": "interaction_row_code_color_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "interaction_row_code_color", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_fab_menu_layout_vlm", + "screenshot": "interaction_fab_menu_layout_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "interaction_fab_menu_layout", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_action_toolbar_layout_vlm", + "screenshot": "interaction_action_toolbar_layout_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "interaction_action_toolbar_layout", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_persist_highlight_gone_vlm", + "screenshot": "interaction_persist_highlight_gone_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "interaction_persist_highlight_gone", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "navigation_reach_settings_vlm", + "screenshot": "navigation_reach_settings_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "navigation_reach_settings", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "navigation_reach_about_vlm", + "screenshot": "navigation_reach_about_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "navigation_reach_about", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "navigation_fab_menu_open_vlm", + "screenshot": "navigation_fab_menu_open_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "navigation_fab_menu_open", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "navigation_reach_add_entry_vlm", + "screenshot": "navigation_reach_add_entry_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "navigation_reach_add_entry", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "navigation_search_open_vlm", + "screenshot": "navigation_search_open_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "navigation_search_open", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "navigation_reach_appearance_vlm", + "screenshot": "navigation_reach_appearance_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "navigation_reach_appearance", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_fab_menu_shape_vlm", + "screenshot": "structure_fab_menu_shape_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_fab_menu_shape", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_search_shape_vlm", + "screenshot": "structure_search_shape_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_search_shape", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_overflow_menu_shape_vlm", + "screenshot": "structure_overflow_menu_shape_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_overflow_menu_shape", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_accordion_expand_vlm", + "screenshot": "structure_accordion_expand_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_accordion_expand", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_settings_list_shape_vlm", + "screenshot": "structure_settings_list_shape_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_settings_list_shape", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_create_populates_list_vlm", + "screenshot": "structure_create_populates_list_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_create_populates_list", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_longpress_action_mode_vlm", + "screenshot": "structure_longpress_action_mode_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_longpress_action_mode", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_main_overview_vlm", + "screenshot": "structure_main_overview_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_main_overview", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + } + ], + "merged_from_files": 1, + "source_shapes": { + "list": 1 + } +} \ No newline at end of file diff --git a/android/blastrock-kakugo/LICENSE b/android/blastrock-kakugo/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f288702d2fa16d3cdf0035b15a9fcbc552cd88e7 --- /dev/null +++ b/android/blastrock-kakugo/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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 for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know 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 License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of 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 of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification 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 of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. 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 work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a 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 visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation 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 to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients 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 to +produce it from the Program, in the form of source code under the +terms 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 independent +works, 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 not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-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 excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the 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 install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional 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 you +add to a covered work, you may (if authorized by the copyright holders of +that 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 "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form 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 expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered 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 automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent 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 anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain 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 limiting +any implied license or other defenses to infringement that may +otherwise 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 or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License 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 have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License 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 the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES 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 OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy 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 greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + 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 appropriate +parts of the General Public License. Of course, your program's commands +might 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 +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/android/blastrock-kakugo/instance.json b/android/blastrock-kakugo/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..9ccb806d00e7a1aa35046973f8f0398da9cd65e0 --- /dev/null +++ b/android/blastrock-kakugo/instance.json @@ -0,0 +1,17 @@ +{ + "schema_version": 1, + "instance_id": "android/blastrock-kakugo", + "platform": "android", + "repo": "https://github.com/blastrock/kakugo", + "commit": "c00becb046949fc53aac98eae8f3c461bc30038d", + "patches": [ + { + "path": "reference/patches/local-source.patch", + "reason": "build_fix", + "note": "Use portable debug signing and suppress the automatic version-changelog dialog used by the frozen reference app.", + "sha256": "2c047e47c62683ac522ab503c41ef64752b2f925c4c4aed0cf0707143b74274a" + } + ], + "package": "org.kaqui", + "license": null +} diff --git a/android/blastrock-kakugo/reference/launch.sh b/android/blastrock-kakugo/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8 --- /dev/null +++ b/android/blastrock-kakugo/reference/launch.sh @@ -0,0 +1,9 @@ +#!/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 1 diff --git a/android/blastrock-kakugo/reference/patches/local-source.patch b/android/blastrock-kakugo/reference/patches/local-source.patch new file mode 100644 index 0000000000000000000000000000000000000000..ad5ca122964d55197663b53b85ef6bcfb0360015 --- /dev/null +++ b/android/blastrock-kakugo/reference/patches/local-source.patch @@ -0,0 +1,80 @@ +diff --git a/app/build.gradle.kts b/app/build.gradle.kts +index 12cd7a39b75a9651ee7c2f75aa67d92aba846b27..a796f93d30722d748a67d641205e523545845e8b 100644 +--- a/app/build.gradle.kts ++++ b/app/build.gradle.kts +@@ -22,7 +22,11 @@ android { + + signingConfigs { + create("debugconfig") { +- storeFile = file("/home/blastrock/.android/debug.keystore") ++ // Bloatware/dev-leftover removed: original hard-coded ++ // storeFile = file("/home/blastrock/.android/debug.keystore") ++ // which is the upstream maintainer's local path and breaks any other build. ++ // Use the per-user Android debug keystore that AGP auto-generates. ++ storeFile = file("${System.getProperty("user.home")}/.android/debug.keystore") + storePassword = "android" + keyAlias = "androiddebugkey" + keyPassword = "android" +@@ -35,10 +39,12 @@ android { + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) +- signingConfig = signingConfigs.getByName("debugconfig") ++ // Release stays unsigned for this clean build (we only assembleDebug). ++ // signingConfig = signingConfigs.getByName("debugconfig") + } + debug { +- signingConfig = signingConfigs.getByName("debugconfig") ++ // Use AGP-managed default debug signing in ANDROID_USER_HOME (auto-generated). ++ // signingConfig = signingConfigs.getByName("debugconfig") + } + } + testOptions { +diff --git a/app/src/main/java/org/kaqui/mainmenu/MainActivity.kt b/app/src/main/java/org/kaqui/mainmenu/MainActivity.kt +index 1ee8c28190c635913cbaf3e361139ac62c055aff..9e7fce4fadad14dcaa3350a3464b8d51905008f1 100644 +--- a/app/src/main/java/org/kaqui/mainmenu/MainActivity.kt ++++ b/app/src/main/java/org/kaqui/mainmenu/MainActivity.kt +@@ -74,22 +74,27 @@ class MainActivity : ComponentActivity() { + ) + + val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this) +- val lastVersionChangelog = sharedPrefs.getInt("last_version_changelog", 0) +- if (lastVersionChangelog < BuildConfig.VERSION_CODE) { +- AlertDialog.Builder(this) +- .setMessage( +- HtmlCompat.fromHtml( +- getString(R.string.changelog_contents), +- HtmlCompat.FROM_HTML_MODE_COMPACT +- ) +- ) +- .setPositiveButton(android.R.string.ok) { _, _ -> +- sharedPrefs.edit { +- putInt("last_version_changelog", BuildConfig.VERSION_CODE) +- } +- } +- .show() +- } ++ // Bloatware removed: "What's new in X.YZ" changelog popup that fires on every ++ // version bump (lastVersionChangelog < BuildConfig.VERSION_CODE). The user can ++ // still review the changelog manually via Settings -> Changelog. ++ // val lastVersionChangelog = sharedPrefs.getInt("last_version_changelog", 0) ++ // if (lastVersionChangelog < BuildConfig.VERSION_CODE) { ++ // AlertDialog.Builder(this) ++ // .setMessage( ++ // HtmlCompat.fromHtml( ++ // getString(R.string.changelog_contents), ++ // HtmlCompat.FROM_HTML_MODE_COMPACT ++ // ) ++ // ) ++ // .setPositiveButton(android.R.string.ok) { _, _ -> ++ // sharedPrefs.edit { ++ // putInt("last_version_changelog", BuildConfig.VERSION_CODE) ++ // } ++ // } ++ // .show() ++ // } ++ // Mark current version as already seen so the popup never appears for this build. ++ sharedPrefs.edit { putInt("last_version_changelog", BuildConfig.VERSION_CODE) } + + setContent { + MainScreen( diff --git a/android/blastrock-kakugo/tests/android__smoke_eval.json b/android/blastrock-kakugo/tests/android__smoke_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..815c3e9f493e3cd64b9f102a514dc4f92596cdb7 --- /dev/null +++ b/android/blastrock-kakugo/tests/android__smoke_eval.json @@ -0,0 +1,62 @@ +{ + "module": "_smoke", + "total": 3, + "passed": 1, + "failed": 2, + "pass_rate": 0.3333, + "rule": { + "total": 0, + "passed": 0, + "failed": 0, + "pass_rate": 0 + }, + "vlm": { + "total": 3, + "passed": 1, + "failed": 2, + "pass_rate": 0.3333 + }, + "vlm_ratio": 0, + "audit": { + "kit_api_version": 1, + "existence": 3, + "liveness": 0, + "interactive": 0, + "depth_ge1": 0, + "depth_ge2": 0, + "value": 0, + "vlm_fine": 1 + }, + "results": [ + { + "test": "smoke_a_vlm", + "passed": true, + "message": "VLM: Q='Does this screen show a vertical list of at least 5 large menu buttons?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does this screen show a vertical list of at least 5 large menu buttons?", + "tag": "layout" + }, + { + "test": "smoke_b_vlm", + "passed": false, + "message": "setup_failed: VLM API call failed", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "", + "tag": "content" + }, + { + "test": "smoke_c_vlm", + "passed": false, + "message": "setup_failed: VLM API call failed", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "", + "tag": "color" + } + ] +} \ No newline at end of file diff --git a/android/blastrock-kakugo/tests/android_computation_eval.json b/android/blastrock-kakugo/tests/android_computation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..143ae92b8f8dfb763f8effe3c040027f7f796424 --- /dev/null +++ b/android/blastrock-kakugo/tests/android_computation_eval.json @@ -0,0 +1,185 @@ +{ + "module": "computation", + "total": 17, + "passed": 17, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 17, + "passed": 17, + "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": 17, + "depth_ge1": 17, + "depth_ge2": 17, + "value": 17, + "vlm_fine": 0 + }, + "results": [ + { + "test": "computation_hira_grid_start_score_00", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 0/0 on a fresh hiragana grid quiz" + }, + { + "test": "computation_hira_grid_correct_sure_11", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 1/1 after a correct SURE grid answer" + }, + { + "test": "computation_hira_grid_correct_maybe_11", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 1/1 after a correct MAYBE grid answer" + }, + { + "test": "computation_hira_grid_wrong_01", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 0/1 + NEXT after a wrong grid answer" + }, + { + "test": "computation_hira_grid_dontknow_01", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 0/1 + NEXT after DON'T KNOW on the grid" + }, + { + "test": "computation_hira_grid_two_correct_22", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 2/2 after two correct grid answers" + }, + { + "test": "computation_hira_grid_correct_then_wrong_12", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 1/2 after one correct then one wrong" + }, + { + "test": "computation_hira_grid_dontknow_then_correct_12", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 1/2 after DON'T KNOW then a correct answer" + }, + { + "test": "computation_kata_grid_correct_11", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 1/1 after a correct katakana grid answer" + }, + { + "test": "computation_kata_grid_dontknow_01", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 0/1 + NEXT after DON'T KNOW on katakana grid" + }, + { + "test": "computation_kata_grid_two_correct_22", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 2/2 after two correct katakana grid answers" + }, + { + "test": "computation_writing_start_score_00", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 0/0 on a fresh hiragana writing test" + }, + { + "test": "computation_writing_correct_11", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 1/1 after typing the correct romaji + SURE" + }, + { + "test": "computation_writing_wrong_01", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 0/1 + NEXT + correct romaji after a wrong typed answer" + }, + { + "test": "computation_writing_dontknow_01", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 0/1 + NEXT after DON'T KNOW on the writing test" + }, + { + "test": "computation_writing_two_correct_22", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 2/2 after two correct typed answers" + }, + { + "test": "computation_kata_writing_correct_11", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 1/1 after a correct katakana typed answer" + } + ] +} \ No newline at end of file diff --git a/android/blastrock-kakugo/tests/android_interaction_eval.json b/android/blastrock-kakugo/tests/android_interaction_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..a84294baaa9098dbd6c13c6a07ec862126253e01 --- /dev/null +++ b/android/blastrock-kakugo/tests/android_interaction_eval.json @@ -0,0 +1,207 @@ +{ + "module": "interaction", + "total": 19, + "passed": 18, + "failed": 1, + "pass_rate": 0.9474, + "rule": { + "total": 15, + "passed": 15, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 4, + "passed": 3, + "failed": 1, + "pass_rate": 0.75 + }, + "vlm_ratio": 0.2667, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 19, + "depth_ge1": 19, + "depth_ge2": 19, + "value": 15, + "vlm_fine": 4 + }, + "results": [ + { + "test": "interaction_item_toggle_statsbar", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "StatsBar good 80->79, disabled segment appears" + }, + { + "test": "interaction_item_persist_reopen", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "checkbox #0 still unchecked after reopen" + }, + { + "test": "interaction_item_persist_process_death", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "checkbox #0 still unchecked after force_stop_and_relaunch" + }, + { + "test": "interaction_multi_record_integrity", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "rows 0&2 checked, row 1 unchecked" + }, + { + "test": "interaction_multi_record_integrity_vlm", + "passed": true, + "message": "VLM: Q='Look at the thin horizontal status bar directly under the blue toolbar. Is it split into TWO differently coloured segments (a wide coloured segment and a separate smaller segment of a different colour), rather than being one single solid colour?' A=YES expect=YES", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Look at the thin horizontal status bar directly under the blue toolbar. Is it split into TWO differently coloured segments (a wide coloured segment and a separate smaller segment of a different colour), rather than being one single solid colour?", + "tag": "color" + }, + { + "test": "interaction_quiz_score_correct", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score 0/0 -> 1/1 on correct answer" + }, + { + "test": "interaction_quiz_score_wrong", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score 0/0 -> 0/1 + NEXT on wrong answer" + }, + { + "test": "interaction_quiz_score_wrong_vlm", + "passed": true, + "message": "VLM: Q='In the answer grid, exactly one answer cell has a PINK/RED background and exactly one other answer cell has a GREEN background (the rest are white). Is that the case?' A=YES expect=YES", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In the answer grid, exactly one answer cell has a PINK/RED background and exactly one other answer cell has a GREEN background (the rest are white). Is that the case?", + "tag": "color" + }, + { + "test": "interaction_quiz_multistep_tally", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score 3/3 after three correct answers" + }, + { + "test": "interaction_quiz_mixed_tally", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score 2/3 after two correct + one wrong" + }, + { + "test": "interaction_quiz_history_sheet", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "history sheet lists answered romaji 'u'" + }, + { + "test": "interaction_quiz_history_sheet_vlm", + "passed": false, + "message": "behavior_wrong: VLM Q='A history panel is shown listing answered items. Is each answered item shown as a small ROUND coloured circle (green and/or pink/red) next to its romaji text?' A=NO expect=YES", + "depth": 3, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: A history panel is shown listing answered items. Is each answered item shown as a small ROUND coloured circle (green and/or pink/red) next to its romaji text?", + "tag": "color" + }, + { + "test": "interaction_lastitemrow_updates", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "LastItemRow shows the just-answered glyph after each answer" + }, + { + "test": "interaction_singlebutton_longpress", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "denominator (0, 0)->(0,1) after long-press" + }, + { + "test": "interaction_custom_test_launch", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "TestActivity (Session score) opens, dialog dismissed" + }, + { + "test": "interaction_wrong_lastitem_circles_vlm", + "passed": true, + "message": "VLM: Q='Look ONLY at the thin strip along the very BOTTOM of the screen (below the answer grid and the NEXT button). Does it show two small ROUND coloured circles side by side — one PINK/RED and one GREEN — each containing a Japanese character?' A=YES expect=YES", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Look ONLY at the thin strip along the very BOTTOM of the screen (below the answer grid and the NEXT button). Does it show two small ROUND coloured circles side by side — one PINK/RED and one GREEN — each containing a Japanese character?", + "tag": "color" + }, + { + "test": "interaction_katakana_score_correct", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score 0/0 -> 1/1 on correct katakana answer" + }, + { + "test": "interaction_dontknow_counts_wrong", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score 0/0 -> 0/1 + NEXT after DON'T KNOW" + }, + { + "test": "interaction_next_advances_question", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "NEXT loads a new question and holds the denominator" + } + ] +} \ No newline at end of file diff --git a/android/blastrock-kakugo/tests/android_navigation_eval.json b/android/blastrock-kakugo/tests/android_navigation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..0d8e1cac01c20fbdff6735eedee086a9f54ad1a3 --- /dev/null +++ b/android/blastrock-kakugo/tests/android_navigation_eval.json @@ -0,0 +1,196 @@ +{ + "module": "navigation", + "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": 2, + "liveness": 0, + "interactive": 16, + "depth_ge1": 16, + "depth_ge2": 9, + "value": 0, + "vlm_fine": 2 + }, + "results": [ + { + "test": "nav_reach_hiragana", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "HiraganaMenu shown (title 'Hiragana'); main 'SETTINGS' button gone" + }, + { + "test": "nav_reach_katakana", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "KatakanaMenu shown (title 'Katakana'); main 'SETTINGS' button gone" + }, + { + "test": "nav_reach_vocabulary", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "VocabularyMenu shown (title 'Vocabulary'); main 'SETTINGS' button gone" + }, + { + "test": "nav_reach_progress", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "StatsActivity shown ('Questions answered' heading); main 'SETTINGS' gone" + }, + { + "test": "nav_reach_settings", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Settings shown ('Enable dark theme' preference); main 'PROGRESS' gone" + }, + { + "test": "nav_reach_kanji_menu", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "KanjiMenu shown (title 'Kanji'); main 'SETTINGS' button gone" + }, + { + "test": "nav_reach_kanji_selection", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "ClassSelection shown ('Kanji selection' title + class rows); Kanji-menu-only 'CUSTOM TEST' button gone" + }, + { + "test": "nav_reach_quiz", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "TestActivity shown ('Session score: 0/0'); menu 'HIRAGANA SELECTION' gone" + }, + { + "test": "nav_reach_quiz_vlm", + "passed": true, + "message": "VLM: Q='Is there a left-pointing back arrow icon at the very top-left corner of this screen, to the left of the title text?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is there a left-pointing back arrow icon at the very top-left corner of this screen, to the left of the title text?", + "tag": "position" + }, + { + "test": "nav_reach_hiragana_selection", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "ItemSelection (hiragana) shown (kana 'あ' row); menu 'HIRAGANA DRAWING' gone" + }, + { + "test": "nav_reach_item_selection", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "ItemSelection (kanji) shown (glyph '一' + checkboxes); class row 'JLPT level 4' gone" + }, + { + "test": "nav_reach_terminate_dialog", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "'Terminate session' AlertDialog shown; quiz 'Session score' hidden behind it" + }, + { + "test": "nav_reach_kanji_detail", + "passed": true, + "message": "", + "depth": 4, + "jump_kind": "reach", + "tier": 2, + "expect": "KanjiDisplay shown (\"On'yomi:\" section); ItemSelection title 'Kanji selection' gone" + }, + { + "test": "nav_reach_kanji_detail_vlm", + "passed": true, + "message": "VLM: Q='Near the top of this screen, are there two side-by-side tab labels reading 'Kanji' (left) and 'Words' (right)?' A=YES expect=YES", + "depth": 4, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Near the top of this screen, are there two side-by-side tab labels reading 'Kanji' (left) and 'Words' (right)?", + "tag": "position" + }, + { + "test": "nav_backstack_submenu_to_main", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Main menu restored ('Kakugo' title back); Kanji-menu 'CUSTOM TEST' gone" + }, + { + "test": "nav_backstack_detail_to_itemsel", + "passed": true, + "message": "", + "depth": 4, + "jump_kind": "reach", + "tier": 2, + "expect": "ItemSelection restored (title 'Kanji selection'); detail \"On'yomi:\" gone" + }, + { + "test": "nav_backstack_deep_unwind", + "passed": true, + "message": "", + "depth": 4, + "jump_kind": "reach", + "tier": 2, + "expect": "Four BACKs pop detail->item-sel->class-sel->Kanji menu->main, each surface's token restored in turn" + }, + { + "test": "nav_backstack_quiz_cancel_stays", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "After CANCEL: quiz 'Session score' visible again; 'Terminate session' dialog gone (quiz NOT popped)" + } + ] +} \ No newline at end of file diff --git a/android/blastrock-kakugo/tests/android_states_eval.json b/android/blastrock-kakugo/tests/android_states_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..c6baffbcff19f9288fdb36e89e8d3aef4a64ab7e --- /dev/null +++ b/android/blastrock-kakugo/tests/android_states_eval.json @@ -0,0 +1,150 @@ +{ + "module": "states", + "total": 13, + "passed": 13, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 12, + "passed": 12, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 1, + "passed": 1, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.0833, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 13, + "depth_ge1": 13, + "depth_ge2": 5, + "value": 6, + "vlm_fine": 1 + }, + "results": [ + { + "test": "states_dark_theme_toggle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "dark theme Switch false->true" + }, + { + "test": "states_dark_theme_persist_reopen", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "dark theme still ON after reopen" + }, + { + "test": "states_dark_theme_persist_processdeath", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "dark theme still ON after force-stop+relaunch" + }, + { + "test": "states_dark_theme_applied_vlm", + "passed": true, + "message": "VLM: Q='Is the background of this screen dark (near-black or very dark) with light-colored (white) text and dark button cards?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Is the background of this screen dark (near-black or very dark) with light-colored (white) text and dark button cards?", + "tag": "color" + }, + { + "test": "states_single_button_toggle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "single button mode false->true; persists on reopen" + }, + { + "test": "states_single_button_consequence", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "single mode ON -> quiz has no SURE/MAYBE buttons" + }, + { + "test": "states_keep_screen_on_toggle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "keep screen on false->true; persists on reopen" + }, + { + "test": "states_custom_font_toggle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "custom font false->true; 'Pick a custom font' row enabled" + }, + { + "test": "states_hide_answers_toggle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "hide answers Switch true->false" + }, + { + "test": "states_hide_answers_off_consequence", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "hide OFF -> quiz shows SURE grid, no SHOW ANSWERS" + }, + { + "test": "states_hide_answers_on_consequence", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "hide ON -> quiz shows SHOW ANSWERS, no SURE grid yet" + }, + { + "test": "states_show_answers_flip", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "answers hidden->shown; SHOW ANSWERS gone, SURE grid present" + }, + { + "test": "states_wrong_answer_next_flip", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "DON'T KNOW -> NEXT after answering" + } + ] +} \ No newline at end of file diff --git a/android/blastrock-kakugo/tests/android_structure_eval.json b/android/blastrock-kakugo/tests/android_structure_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..4312bd2131db919ae2c6593ae7797a0f614d9040 --- /dev/null +++ b/android/blastrock-kakugo/tests/android_structure_eval.json @@ -0,0 +1,181 @@ +{ + "module": "structure", + "total": 16, + "passed": 16, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 11, + "passed": 11, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 5, + "passed": 5, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.4545, + "audit": { + "kit_api_version": 1, + "existence": 3, + "liveness": 0, + "interactive": 13, + "depth_ge1": 13, + "depth_ge2": 7, + "value": 0, + "vlm_fine": 5 + }, + "results": [ + { + "test": "structure_gate_launch", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_main_six_buttons", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_hiragana_menu_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Main's 6 buttons replaced by >=4 hiragana test-type Buttons under the 'Hiragana' title" + }, + { + "test": "structure_kanji_menu_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Kanji menu shows >=6 test-type Buttons under the 'Kanji' title" + }, + { + "test": "structure_settings_pref_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Settings is a RecyclerView with >=5 preference title rows and >=5 Switch toggles" + }, + { + "test": "structure_quiz_show_answers_delta", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "SURE 0->6 & MAYBE 0->6 & DON'T KNOW 0->1, node count grows, SHOW ANSWERS disappears; restored to zero cells on quiz restart" + }, + { + "test": "structure_quiz_grid_two_columns", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "answer grid lays SURE cells in exactly 2 x-columns (>=4 cells total)" + }, + { + "test": "structure_custom_test_dialog_delta", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "CUSTOM TEST adds a dialog window layer (prompt + OK/CANCEL); surface changes and restores on CANCEL" + }, + { + "test": "structure_classsel_overflow_delta", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "More-options adds a dropdown with >=2 named actions (Save/Load/Import) over the class list; removed on BACK" + }, + { + "test": "structure_drawing_canvas_shape", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "drawing test shows one large canvas region + HINT + DON'T KNOW and NO SURE/MAYBE answer grid" + }, + { + "test": "structure_stats_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Progress shows 'Questions answered' heading + a chart ViewGroup; main-menu buttons gone" + }, + { + "test": "structure_main_layout_vlm", + "passed": true, + "message": "VLM: Q='Are there exactly six large rectangular buttons of equal width, stacked one directly below another in a single vertical column that spans the full width of the screen?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Are there exactly six large rectangular buttons of equal width, stacked one directly below another in a single vertical column that spans the full width of the screen?", + "tag": "position" + }, + { + "test": "structure_quiz_grid_vlm", + "passed": true, + "message": "VLM: Q='Are the answer options laid out in two side-by-side columns (a grid with a left column and a right column), each option showing a 'SURE' and a 'MAYBE' button?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Are the answer options laid out in two side-by-side columns (a grid with a left column and a right column), each option showing a 'SURE' and a 'MAYBE' button?", + "tag": "shape" + }, + { + "test": "structure_stats_chart_vlm", + "passed": true, + "message": "VLM: Q='Below the 'Questions answered' heading, is at least one large solid coloured vertical bar (green or pink/red) drawn, rather than an empty plot area or only a line of text?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Below the 'Questions answered' heading, is at least one large solid coloured vertical bar (green or pink/red) drawn, rather than an empty plot area or only a line of text?", + "tag": "color" + }, + { + "test": "structure_drawing_canvas_vlm", + "passed": true, + "message": "VLM: Q='Is there a large empty white square drawing area filling most of the middle of the screen, positioned directly above a row that contains a 'HINT' button and a \"DON'T KNOW\" button?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is there a large empty white square drawing area filling most of the middle of the screen, positioned directly above a row that contains a 'HINT' button and a \"DON'T KNOW\" button?", + "tag": "shape" + }, + { + "test": "structure_quiz_statsbar_vlm", + "passed": true, + "message": "VLM: Q='Near the very top of the content (just under the toolbar), is there a thin coloured horizontal bar, with the words 'Session score' shown on the line directly below that bar?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Near the very top of the content (just under the toolbar), is there a thin coloured horizontal bar, with the words 'Session score' shown on the line directly below that bar?", + "tag": "position" + } + ] +} \ No newline at end of file diff --git a/android/blastrock-kakugo/tests/android_testgen_kit.py b/android/blastrock-kakugo/tests/android_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6 --- /dev/null +++ b/android/blastrock-kakugo/tests/android_testgen_kit.py @@ -0,0 +1,1910 @@ +#!/usr/bin/env python3 +"""Android TestGen Kit — the single source of every test helper, so a test's +NAVIGATION 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 package +name differs): always use the module-level PACKAGE (argv[1]). Never write a package +name, an .apk path, a /data/data path, or a pixel coordinate as a literal. + python3 android_testgen_kit.py lint_sources # flags all of those + +SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery): + python3 android_testgen_kit.py audit + python3 android_testgen_kit.py lint + python3 android_testgen_kit.py lint_sources + python3 android_testgen_kit.py audit_depth [results_dir] +""" +from __future__ import annotations + +import ast +import base64 +import functools +import glob +import hashlib +import json +import math +import os +import re +import shlex +import subprocess +import sys +import time +import urllib.error +import 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.0 +SETTLE = { + "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 /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 " list[dict]: + """XML -> list of attribute dicts, each with _bounds and _center.""" + nodes = [] + for m in re.finditer(r"]+?)/?>", 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} \n" + " android_testgen_kit.py audit_depth [results_dir]\n" + " android_testgen_kit.py score [manifest_dir]") diff --git a/android/blastrock-kakugo/tests/android_text_eval.json b/android/blastrock-kakugo/tests/android_text_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..71ddf2037c6551ff2dfb4d44c3eb2b7219ac0879 --- /dev/null +++ b/android/blastrock-kakugo/tests/android_text_eval.json @@ -0,0 +1,258 @@ +{ + "module": "text", + "total": 25, + "passed": 25, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 24, + "passed": 24, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 1, + "passed": 1, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.0417, + "audit": { + "kit_api_version": 1, + "existence": 1, + "liveness": 0, + "interactive": 24, + "depth_ge1": 24, + "depth_ge2": 13, + "value": 24, + "vlm_fine": 1 + }, + "results": [ + { + "test": "text_score_label_start", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 0/0" + }, + { + "test": "text_score_after_correct", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Session score: 1/1" + }, + { + "test": "text_title_hiragana", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Hiragana" + }, + { + "test": "text_title_katakana", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Katakana" + }, + { + "test": "text_title_kanji", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Kanji" + }, + { + "test": "text_title_vocabulary", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Vocabulary" + }, + { + "test": "text_title_progress", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Progress" + }, + { + "test": "text_title_settings", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Settings" + }, + { + "test": "text_title_kanji_selection", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Kanji selection" + }, + { + "test": "text_show_answers_label", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "SHOW ANSWERS" + }, + { + "test": "text_answer_buttons_labels", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "SURE / MAYBE / DON'T KNOW" + }, + { + "test": "text_next_after_wrong", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "NEXT" + }, + { + "test": "text_terminate_dialog", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "value", + "tier": 3, + "expect": "Terminate session / Are you sure you want to end this quiz session?" + }, + { + "test": "text_settings_dark_theme", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Enable dark theme / Will update when leaving the settings screen" + }, + { + "test": "text_settings_hide_answers", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Hide answers / You will need to click on a button to show answers" + }, + { + "test": "text_settings_single_button", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Single button mode" + }, + { + "test": "text_settings_keep_screen_on", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Keep screen on / Keep screen lit during tests" + }, + { + "test": "text_kanji_display_readings", + "passed": true, + "message": "", + "depth": 4, + "jump_kind": "value", + "tier": 3, + "expect": "On'yomi: / Kun'yomi: / Definitions:" + }, + { + "test": "text_kanji_display_status", + "passed": true, + "message": "", + "depth": 4, + "jump_kind": "value", + "tier": 3, + "expect": "Learning status: / Reading: / Meaning: / Strokes: / Not known / Skip next review" + }, + { + "test": "text_kanji_display_open_dict_desc", + "passed": true, + "message": "", + "depth": 4, + "jump_kind": "value", + "tier": 3, + "expect": "Open in external dictionary" + }, + { + "test": "text_stats_heading", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Questions answered" + }, + { + "test": "text_stats_chart_legend_vlm", + "passed": true, + "message": "VLM: Q='In the chart legend near the bottom, is there a small GREEN colored square immediately to the LEFT of the text 'Correct answers'?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the chart legend near the bottom, is there a small GREEN colored square immediately to the LEFT of the text 'Correct answers'?", + "tag": "color" + }, + { + "test": "text_writing_correct_reveal", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "correct romaji 'ke'" + }, + { + "test": "text_class_level_names", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "JLPT level 5 / Additional kanji" + }, + { + "test": "text_class_selection_toolbar_descs", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Search / More options" + } + ] +} \ No newline at end of file diff --git a/android/blastrock-kakugo/tests/conftest.py b/android/blastrock-kakugo/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27 --- /dev/null +++ b/android/blastrock-kakugo/tests/conftest.py @@ -0,0 +1 @@ +pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"] diff --git a/android/blastrock-kakugo/tests/requirements.txt b/android/blastrock-kakugo/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c --- /dev/null +++ b/android/blastrock-kakugo/tests/requirements.txt @@ -0,0 +1,2 @@ +pytest +pillow diff --git a/android/blastrock-kakugo/tests/test_android_computation.py b/android/blastrock-kakugo/tests/test_android_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..d5953fd9686b20c4c880648eb49ad06138f0abe3 --- /dev/null +++ b/android/blastrock-kakugo/tests/test_android_computation.py @@ -0,0 +1,786 @@ +#!/usr/bin/env python3 +"""COMPUTATION lane for Kakugo (org.kaqui) — the QUIZ SCORING ENGINE. + +Core function = input (an answer choice / typed romaji) -> output (the deterministic +change to "Session score: X/Y" and the correct/wrong highlight state). Every test +asserts a SPECIFIC score value OBSERVED on the original app, never one computed only +from the source. + +The quizzes used are fully dump-readable: + * Hiragana / Katakana -> romaji GRID quiz: the question kana is a large TextView; + each grid option's romaji is a TextView; the correct romaji is derived via the + kana->romaji map below. We tap the SURE (or MAYBE) belonging to the correct + option, disambiguated by COLUMN (x-side) then nearest row (y) — a naive + euclidean-nearest is a coin-flip between the two same-row buttons. + * Hiragana / Katakana -> romaji WRITING (text-typing) test: we read the kana, + type its romaji into the OutlinedTextField, submit with SURE. + +Depth: every scoring test is depth 2 (Main -> script menu -> TestActivity), backed +by a directly-named and_enter_* navigation helper (each contains two and_enter() +calls). VLM allocation for this lane: EXACTLY 0 vlm_assert (all values are +dump-readable). + +Run: + python3 test_android_computation.py org.kaqui /workspace/testgen/eval/eval_results +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +# ── kana -> romaji maps (from recon.md; the app renders exactly these strings) ── +HIRA_MAP = { + "あ": "a", "い": "i", "う": "u", "え": "e", "お": "o", + "か": "ka", "き": "ki", "く": "ku", "け": "ke", "こ": "ko", + "さ": "sa", "し": "shi", "す": "su", "せ": "se", "そ": "so", + "た": "ta", "ち": "chi", "つ": "tsu", "て": "te", "と": "to", + "な": "na", "に": "ni", "ぬ": "nu", "ね": "ne", "の": "no", + "は": "ha", "ひ": "hi", "ふ": "fu", "へ": "he", "ほ": "ho", + "ま": "ma", "み": "mi", "む": "mu", "め": "me", "も": "mo", + "や": "ya", "ゆ": "yu", "よ": "yo", + "ら": "ra", "り": "ri", "る": "ru", "れ": "re", "ろ": "ro", + "わ": "wa", "を": "wo", "ん": "n", + "が": "ga", "ぎ": "gi", "ぐ": "gu", "げ": "ge", "ご": "go", + "ざ": "za", "じ": "ji", "ず": "zu", "ぜ": "ze", "ぞ": "zo", + "だ": "da", "ぢ": "ji", "づ": "zu", "で": "de", "ど": "do", + "ば": "ba", "び": "bi", "ぶ": "bu", "べ": "be", "ぼ": "bo", + "ぱ": "pa", "ぴ": "pi", "ぷ": "pu", "ぺ": "pe", "ぽ": "po", +} +KATA_MAP = { + "ア": "a", "イ": "i", "ウ": "u", "エ": "e", "オ": "o", + "カ": "ka", "キ": "ki", "ク": "ku", "ケ": "ke", "コ": "ko", + "サ": "sa", "シ": "shi", "ス": "su", "セ": "se", "ソ": "so", + "タ": "ta", "チ": "chi", "ツ": "tsu", "テ": "te", "ト": "to", + "ナ": "na", "ニ": "ni", "ヌ": "nu", "ネ": "ne", "ノ": "no", + "ハ": "ha", "ヒ": "hi", "フ": "fu", "ヘ": "he", "ホ": "ho", + "マ": "ma", "ミ": "mi", "ム": "mu", "メ": "me", "モ": "mo", + "ヤ": "ya", "ユ": "yu", "ヨ": "yo", + "ラ": "ra", "リ": "ri", "ル": "ru", "レ": "re", "ロ": "ro", + "ワ": "wa", "ヲ": "wo", "ン": "n", + "ガ": "ga", "ギ": "gi", "グ": "gu", "ゲ": "ge", "ゴ": "go", + "ザ": "za", "ジ": "ji", "ズ": "zu", "ゼ": "ze", "ゾ": "zo", + "ダ": "da", "ヂ": "ji", "ヅ": "zu", "デ": "de", "ド": "do", + "バ": "ba", "ビ": "bi", "ブ": "bu", "ベ": "be", "ボ": "bo", + "パ": "pa", "ピ": "pi", "プ": "pu", "ペ": "pe", "ポ": "po", +} + +_ANSWER_LABELS = {"SURE", "MAYBE", "DON'T KNOW", "NEXT", "SHOW ANSWERS"} + + +# ══════════════════════════════════════════════════════════════════════════════ +# Low-level readers / matchers (all dump-driven; re-dump before each use) +# ══════════════════════════════════════════════════════════════════════════════ + +def tap_contains(nodes, sub): + """Tap the first tappable node whose text/content-desc CONTAINS `sub` + (case-insensitive). Main-menu buttons carry BOTH scripts ("ひらがな\\nHIRAGANA") + so an exact match will not do — match the ASCII substring.""" + sub = sub.lower() + for n in nodes: + blob = (n.get("text", "") + " " + n.get("content-desc", "")).lower() + if sub in blob and "_center" in n: + if tap_node(n): + return True + return False + + +def read_score_text(nodes): + """The exact 'Session score: X/Y' string, or ''.""" + for n in nodes: + t = n.get("text", "").strip() + if t.lower().startswith("session score"): + return t + return "" + + +def read_score_pair(nodes): + """(numerator, denominator) parsed from the score line, or None.""" + t = read_score_text(nodes) + if "/" not in t: + return None + tail = t.split(":", 1)[-1].strip() + if "/" not in tail: + return None + a, b = tail.split("/", 1) + a, b = a.strip(), b.strip() + if a.isdigit() and b.isdigit(): + return int(a), int(b) + return None + + +def read_question_kana(nodes): + """The big question glyph: the tallest short (<=3 char) TextView below the + top bar. Works for both the grid quiz (kana centred in a big box) and the + writing test (kana above the input field).""" + best = None + best_h = 0 + for n in find_by_class(nodes, "TextView"): + b = n.get("_bounds") + t = n.get("text", "").strip() + if not b or not t or len(t) > 3: + continue + if b[1] < 250: + continue + h = b[3] - b[1] + if h > 300 and h > best_h: + best, best_h = t, h + return best or "" + + +def grid_options(nodes): + """List of (romaji, bounds) for each visible answer cell text. Answer texts + are ASCII TextViews in the mid band, excluding the button labels.""" + out = [] + for n in find_by_class(nodes, "TextView"): + t = n.get("text", "").strip() + b = n.get("_bounds") + if not b or not t: + continue + if t in _ANSWER_LABELS or t.lower().startswith("session"): + continue + if not all(ord(c) < 128 for c in t) or t[0].isdigit(): + continue + # answer cells sit between the question box and the DON'T KNOW/NEXT row + if 1000 < b[1] and b[3] < 1800: + out.append((t, b)) + return out + + +def label_button_centers(nodes, label): + """Centres of the clickable wrapper for each occurrence of `label` + (SURE / MAYBE). The label TextView is a child of a clickable View; we return + the smallest clickable View that geometrically contains the label.""" + clickables = [n for n in nodes + if n.get("clickable") == "true" and n.get("_bounds")] + out = [] + for n in nodes: + if n.get("text", "").strip() != label or not n.get("_bounds"): + continue + sb = n["_bounds"] + scx = (sb[0] + sb[2]) // 2 + scy = (sb[1] + sb[3]) // 2 + best = None + best_area = 1 << 60 + for c in clickables: + x1, y1, x2, y2 = c["_bounds"] + if x1 <= scx <= x2 and y1 <= scy <= y2: + area = (x2 - x1) * (y2 - y1) + if area < best_area: + best_area = area + best = c + out.append(best["_center"] if best else (scx, scy)) + return out + + +def pick_button_for_option(option_bounds, button_centers, mid_x): + """Choose the SURE/MAYBE that belongs to `option_bounds`: same COLUMN first + (a naive euclidean-nearest is a coin-flip between the two same-row buttons), + then nearest ROW. Returns (x, y) or None.""" + ox = (option_bounds[0] + option_bounds[2]) // 2 + oy = (option_bounds[1] + option_bounds[3]) // 2 + left = ox < mid_x + same_col = [c for c in button_centers if (c[0] < mid_x) == left] + if not same_col: + same_col = button_centers + if not same_col: + return None + same_col.sort(key=lambda c: abs(c[1] - oy)) + return same_col[0] + + +# ══════════════════════════════════════════════════════════════════════════════ +# Navigation helpers — self-contained (restart -> menu -> quiz). Each test calls +# ONE of these DIRECTLY BY NAME so the depth auditor can trace the two and_enter() +# calls that back the depth=2 declaration (a callable passed as an argument is +# invisible to the AST, so navigation is never routed through a parameter). +# ══════════════════════════════════════════════════════════════════════════════ + +def _open_from_menu(menu_sub, button_pred): + """restart_app() -> Main -> a script menu -> the quiz button matched by + button_pred(text). Returns True on the quiz surface (Session score present). + The two and_enter() calls mark the two crossed surfaces (menu, then quiz).""" + and_reset_depth() + restart_app() + wait_for_foreground() + if not tap_contains(ui(), menu_sub): + return False + and_enter(menu_sub) # crossed into the script menu + nodes = ui() + btn = next((n for n in find_by_class(nodes, "Button") + if button_pred(n.get("text", "").lower())), None) + if not btn or not tap_node(btn): + return False + and_enter("quiz") # crossed into TestActivity + return read_score_text(ui()) != "" + + +def and_enter_hiragana_grid_quiz(): + """Main -> HIRAGANA -> 'HIRAGANA TO ROMAJI QUIZ' (grid). depth 2.""" + return _open_from_menu("hiragana", lambda t: "romaji quiz" in t) + + +def and_enter_katakana_grid_quiz(): + """Main -> KATAKANA -> 'KATAKANA TO ROMAJI' (grid, kana->romaji). depth 2.""" + return _open_from_menu( + "katakana", lambda t: "katakana to romaji" in t and "writing" not in t) + + +def and_enter_hiragana_writing_quiz(): + """Main -> HIRAGANA -> 'HIRAGANA TO ROMAJI WRITING' (text typing). depth 2.""" + return _open_from_menu("hiragana", lambda t: "romaji writing" in t) + + +def and_enter_katakana_writing_quiz(): + """Main -> KATAKANA -> 'KATAKANA TO ROMAJI WRITING' (text typing). depth 2.""" + return _open_from_menu("katakana", lambda t: "romaji writing" in t) + + +# ══════════════════════════════════════════════════════════════════════════════ +# Composite quiz actions (operate on whatever quiz surface is currently open) +# ══════════════════════════════════════════════════════════════════════════════ + +def show_answers_if_needed(): + """Reveal the answer grid (default pref hides it). Idempotent.""" + nodes = ui() + if find_node_ci(nodes, "SURE"): + return True + if tap_contains(nodes, "show answers"): + return find_node_ci(ui(), "SURE") is not None + return find_node_ci(ui(), "SURE") is not None + + +def answer_grid_correct(kana_map, label="SURE"): + """On a fresh grid question: read the kana, reveal answers, tap the `label` + (SURE/MAYBE) of the option whose romaji matches the kana via `kana_map`. + + Returns (attempted, kana, romaji, score_pair_after). `attempted` is False when + the kana is not in the map or its option is not on screen (caller retries a + fresh question).""" + nodes = ui() + kana = read_question_kana(nodes) + romaji = kana_map.get(kana) + if not romaji: + return False, kana, None, None + if not show_answers_if_needed(): + return False, kana, romaji, None + nodes = ui() + mid_x = get_screen_info()["center_x"] + opts = grid_options(nodes) + co = next((o for o in opts if o[0] == romaji), None) + if co is None: + return False, kana, romaji, None + centers = label_button_centers(nodes, label) + target = pick_button_for_option(co[1], centers, mid_x) + if target is None: + return False, kana, romaji, None + tap(target[0], target[1]) + return True, kana, romaji, read_score_pair(ui()) + + +def answer_grid_wrong(kana_map): + """Tap the SURE of an option whose romaji is NOT the correct one. Requires the + kana to be in the map so wrongness is guaranteed; otherwise returns not- + attempted and the caller should use the always-wrong DON'T KNOW path. Returns + (attempted, chosen_romaji, score_pair_after).""" + nodes = ui() + kana = read_question_kana(nodes) + romaji = kana_map.get(kana) + if not show_answers_if_needed(): + return False, None, None + nodes = ui() + mid_x = get_screen_info()["center_x"] + opts = grid_options(nodes) + if not opts or romaji is None: + return False, None, None + wrong = next((o for o in opts if o[0] != romaji), None) + if wrong is None: + return False, None, None + centers = label_button_centers(nodes, "SURE") + target = pick_button_for_option(wrong[1], centers, mid_x) + if target is None: + return False, None, None + tap(target[0], target[1]) + return True, wrong[0], read_score_pair(ui()) + + +def answer_writing_correct(kana_map): + """Text-typing test: read the kana, type its romaji into the field, submit + with SURE (fallback IME Done). Returns (attempted, kana, romaji, pair_after).""" + nodes = ui() + kana = read_question_kana(nodes) + romaji = kana_map.get(kana) + if not romaji: + return False, kana, None, None + fields = find_by_class(nodes, "EditText") + if not fields: + return False, kana, romaji, None + if not type_text(fields[0], romaji): + return False, kana, romaji, None + nodes = ui() + if not tap_contains(nodes, "sure"): + enter() + settle("tap") + return True, kana, romaji, read_score_pair(ui()) + + +# ══════════════════════════════════════════════════════════════════════════════ +# Tests. Each declares depth=2, jump_kind="value". Retry loops call the specific +# and_enter_* helper BY NAME (so the AST backs the depth) — every hiragana/ +# katakana IS in the map, so the first fresh question normally succeeds; the retry +# only guards a rare unmapped glyph. Never delete a case: re-derive from what is +# observed instead. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_hira_grid_start_score_00",)) +def test_hira_grid_start_score_zero(): + """Before any answer the score is the observed baseline 0/0 — the ABSENT state + the correct answer must move away from.""" + ok_nav = and_enter_hiragana_grid_quiz() + pair = read_score_pair(ui()) + ok = ok_nav and pair == (0, 0) + record("computation_hira_grid_start_score_00", ok, + "" if ok else f"setup_failed: expected 0/0 on quiz start, got {pair!r}", + depth=2, jump_kind="value", + expect="Session score: 0/0 on a fresh hiragana grid quiz") + + +@and_test(expects=("computation_hira_grid_correct_sure_11",)) +def test_hira_grid_correct_sure(): + """C1: correct grid answer (SURE) -> score 0/0 -> 1/1 (both +1) and a new + question loads (SHOW ANSWERS returns / no NEXT).""" + ok = False + kana = romaji = None + p0 = p1 = None + advanced = False + for _ in range(6): + if not and_enter_hiragana_grid_quiz(): + continue + p0 = read_score_pair(ui()) + attempted, kana, romaji, p1 = answer_grid_correct(HIRA_MAP, "SURE") + if attempted: + nodes = ui() + advanced = (find_node_ci(nodes, "SHOW ANSWERS") is not None + and find_node_ci(nodes, "NEXT") is None) + ok = p0 == (0, 0) and p1 == (1, 1) and advanced + break + record("computation_hira_grid_correct_sure_11", ok, + "" if ok else + (f"behavior_wrong: kana={kana!r} romaji={romaji!r} score {p0}->{p1}, " + f"expected (0,0)->(1,1), advanced={advanced}" + if p1 is not None else + "setup_failed: could not reach a mappable grid question"), + depth=2, jump_kind="value", + expect="Session score: 1/1 after a correct SURE grid answer") + + +@and_test(expects=("computation_hira_grid_correct_maybe_11",)) +def test_hira_grid_correct_maybe(): + """A MAYBE on the correct option also advances and scores like SURE -> 1/1.""" + ok = False + kana = romaji = None + p0 = p1 = None + for _ in range(6): + if not and_enter_hiragana_grid_quiz(): + continue + p0 = read_score_pair(ui()) + attempted, kana, romaji, p1 = answer_grid_correct(HIRA_MAP, "MAYBE") + if attempted: + ok = p0 == (0, 0) and p1 == (1, 1) + break + record("computation_hira_grid_correct_maybe_11", ok, + "" if ok else + (f"behavior_wrong: kana={kana!r} romaji={romaji!r} score {p0}->{p1}, " + f"expected (0,0)->(1,1)" + if p1 is not None else + "setup_failed: could not reach a mappable grid question"), + depth=2, jump_kind="value", + expect="Session score: 1/1 after a correct MAYBE grid answer") + + +@and_test(expects=("computation_hira_grid_wrong_01",)) +def test_hira_grid_wrong(): + """C2: wrong grid answer (SURE on a non-matching option) -> score 0/0 -> 0/1 + (numerator unchanged, denominator +1) AND NEXT appears.""" + ok = False + chosen = None + p0 = p1 = None + has_next = False + for _ in range(6): + if not and_enter_hiragana_grid_quiz(): + continue + p0 = read_score_pair(ui()) + attempted, chosen, p1 = answer_grid_wrong(HIRA_MAP) + if attempted: + has_next = find_node_ci(ui(), "NEXT") is not None + ok = p0 == (0, 0) and p1 == (0, 1) and has_next + break + record("computation_hira_grid_wrong_01", ok, + "" if ok else + (f"behavior_wrong: chose {chosen!r} score {p0}->{p1}, expected " + f"(0,0)->(0,1) with NEXT (has_next={has_next})" + if p1 is not None else + "setup_failed: could not reach a mappable grid question"), + depth=2, jump_kind="value", + expect="Session score: 0/1 + NEXT after a wrong grid answer") + + +@and_test(expects=("computation_hira_grid_dontknow_01",)) +def test_hira_grid_dont_know(): + """C5: DON'T KNOW on the grid counts as wrong -> score 0/0 -> 0/1 + NEXT. + Deterministic regardless of the kana (no map needed).""" + ok_nav = and_enter_hiragana_grid_quiz() + p0 = read_score_pair(ui()) + shown = show_answers_if_needed() + tapped = tap_contains(ui(), "don't know") + nodes = ui() + p1 = read_score_pair(nodes) + has_next = find_node_ci(nodes, "NEXT") is not None + ok = ok_nav and shown and tapped and p0 == (0, 0) and p1 == (0, 1) and has_next + record("computation_hira_grid_dontknow_01", ok, + "" if ok else + f"behavior_wrong: DON'T KNOW score {p0}->{p1}, expected (0,0)->(0,1) " + f"with NEXT (nav={ok_nav}, shown={shown}, tapped={tapped})", + depth=2, jump_kind="value", + expect="Session score: 0/1 + NEXT after DON'T KNOW on the grid") + + +@and_test(expects=("computation_hira_grid_two_correct_22",)) +def test_hira_grid_two_correct(): + """Running tally: two correct SURE answers in a row -> 2/2 (a multi-step VALUE + with a specific expected accumulator).""" + ok = False + p1 = p2 = None + for _ in range(6): + if not and_enter_hiragana_grid_quiz(): + continue + a1, k1, r1, p1 = answer_grid_correct(HIRA_MAP, "SURE") + if not a1 or p1 != (1, 1): + continue + a2, k2, r2, p2 = answer_grid_correct(HIRA_MAP, "SURE") + if a2: + ok = p2 == (2, 2) + break + record("computation_hira_grid_two_correct_22", ok, + "" if ok else + (f"behavior_wrong: two correct answers -> {p2!r}, expected (2,2)" + if p1 == (1, 1) else + "setup_failed: could not reach two consecutive mappable questions"), + depth=2, jump_kind="value", + expect="Session score: 2/2 after two correct grid answers") + + +@and_test(expects=("computation_hira_grid_correct_then_wrong_12",)) +def test_hira_grid_correct_then_wrong(): + """Running tally: one correct + one wrong -> 1/2 (numerator stays 1, denom 2).""" + ok = False + p1 = p2 = None + for _ in range(6): + if not and_enter_hiragana_grid_quiz(): + continue + a1, k1, r1, p1 = answer_grid_correct(HIRA_MAP, "SURE") + if not a1 or p1 != (1, 1): + continue + a2, chosen, p2 = answer_grid_wrong(HIRA_MAP) + if a2: + ok = p2 == (1, 2) + break + record("computation_hira_grid_correct_then_wrong_12", ok, + "" if ok else + (f"behavior_wrong: correct-then-wrong -> {p2!r}, expected (1,2)" + if p1 == (1, 1) else + "setup_failed: could not reach two consecutive mappable questions"), + depth=2, jump_kind="value", + expect="Session score: 1/2 after one correct then one wrong") + + +@and_test(expects=("computation_hira_grid_dontknow_then_correct_12",)) +def test_hira_grid_dontknow_then_correct(): + """Running tally the other way: wrong-via-DON'T-KNOW then a correct answer -> + 1/2 (denominator 2, numerator 1).""" + ok = False + p1 = p2 = None + for _ in range(6): + if not and_enter_hiragana_grid_quiz(): + continue + if not show_answers_if_needed(): + continue + if not tap_contains(ui(), "don't know"): + continue + p1 = read_score_pair(ui()) # expect 0/1 + if p1 != (0, 1): + continue + tap_contains(ui(), "next") # advance to the next question + a2, k2, r2, p2 = answer_grid_correct(HIRA_MAP, "SURE") + if a2: + ok = p2 == (1, 2) + break + record("computation_hira_grid_dontknow_then_correct_12", ok, + "" if ok else + (f"behavior_wrong: dontknow-then-correct -> {p2!r}, expected (1,2)" + if p1 == (0, 1) else + "setup_failed: could not sequence DON'T KNOW then a mappable question"), + depth=2, jump_kind="value", + expect="Session score: 1/2 after DON'T KNOW then a correct answer") + + +@and_test(expects=("computation_kata_grid_correct_11",)) +def test_kata_grid_correct(): + """C6: katakana grid correct answer (SURE) -> score 0/0 -> 1/1 (katakana map).""" + ok = False + kana = romaji = None + p0 = p1 = None + for _ in range(6): + if not and_enter_katakana_grid_quiz(): + continue + p0 = read_score_pair(ui()) + attempted, kana, romaji, p1 = answer_grid_correct(KATA_MAP, "SURE") + if attempted: + ok = p0 == (0, 0) and p1 == (1, 1) + break + record("computation_kata_grid_correct_11", ok, + "" if ok else + (f"behavior_wrong: kata kana={kana!r} romaji={romaji!r} score {p0}->{p1}, " + f"expected (0,0)->(1,1)" + if p1 is not None else + "setup_failed: could not reach a mappable katakana question"), + depth=2, jump_kind="value", + expect="Session score: 1/1 after a correct katakana grid answer") + + +@and_test(expects=("computation_kata_grid_dontknow_01",)) +def test_kata_grid_dont_know(): + """Katakana DON'T KNOW -> 0/0 -> 0/1 + NEXT (deterministic, no map needed).""" + ok_nav = and_enter_katakana_grid_quiz() + p0 = read_score_pair(ui()) + shown = show_answers_if_needed() + tapped = tap_contains(ui(), "don't know") + nodes = ui() + p1 = read_score_pair(nodes) + has_next = find_node_ci(nodes, "NEXT") is not None + ok = ok_nav and shown and tapped and p0 == (0, 0) and p1 == (0, 1) and has_next + record("computation_kata_grid_dontknow_01", ok, + "" if ok else + f"behavior_wrong: kata DON'T KNOW score {p0}->{p1}, expected " + f"(0,0)->(0,1) with NEXT (nav={ok_nav}, shown={shown}, tapped={tapped})", + depth=2, jump_kind="value", + expect="Session score: 0/1 + NEXT after DON'T KNOW on katakana grid") + + +@and_test(expects=("computation_kata_grid_two_correct_22",)) +def test_kata_grid_two_correct(): + """Katakana running tally: two correct in a row -> 2/2.""" + ok = False + p1 = p2 = None + for _ in range(6): + if not and_enter_katakana_grid_quiz(): + continue + a1, k1, r1, p1 = answer_grid_correct(KATA_MAP, "SURE") + if not a1 or p1 != (1, 1): + continue + a2, k2, r2, p2 = answer_grid_correct(KATA_MAP, "SURE") + if a2: + ok = p2 == (2, 2) + break + record("computation_kata_grid_two_correct_22", ok, + "" if ok else + (f"behavior_wrong: two correct katakana -> {p2!r}, expected (2,2)" + if p1 == (1, 1) else + "setup_failed: could not reach two consecutive mappable katakana questions"), + depth=2, jump_kind="value", + expect="Session score: 2/2 after two correct katakana grid answers") + + +@and_test(expects=("computation_writing_start_score_00",)) +def test_writing_start_score_zero(): + """Text-typing test starts at the observed baseline 0/0 (ABSENT state).""" + ok_nav = and_enter_hiragana_writing_quiz() + has_field = len(find_by_class(ui(), "EditText")) >= 1 + pair = read_score_pair(ui()) + ok = ok_nav and has_field and pair == (0, 0) + record("computation_writing_start_score_00", ok, + "" if ok else + f"setup_failed: writing test start score {pair!r} field={has_field}, " + f"expected 0/0 with an input field", + depth=2, jump_kind="value", + expect="Session score: 0/0 on a fresh hiragana writing test") + + +@and_test(expects=("computation_writing_correct_11",)) +def test_writing_correct(): + """C3: type the correct romaji + SURE -> score 0/0 -> 1/1, field cleared, + new question loads.""" + ok = False + kana = romaji = None + p0 = p1 = None + field_after = None + for _ in range(6): + if not and_enter_hiragana_writing_quiz(): + continue + p0 = read_score_pair(ui()) + attempted, kana, romaji, p1 = answer_writing_correct(HIRA_MAP) + if attempted: + nodes = ui() + fields = find_by_class(nodes, "EditText") + field_after = fields[0].get("text", "") if fields else None + cleared = (field_after or "") == "" + ok = p0 == (0, 0) and p1 == (1, 1) and cleared + break + record("computation_writing_correct_11", ok, + "" if ok else + (f"behavior_wrong: kana={kana!r} typed={romaji!r} score {p0}->{p1}, " + f"field_after={field_after!r}, expected (0,0)->(1,1) cleared" + if p1 is not None else + "setup_failed: could not reach a mappable writing question"), + depth=2, jump_kind="value", + expect="Session score: 1/1 after typing the correct romaji + SURE") + + +@and_test(expects=("computation_writing_wrong_01",)) +def test_writing_wrong(): + """C4: type a deliberately wrong string ('zzz') + SURE -> score 0/0 -> 0/1, + NEXT appears, and the correct romaji for the shown kana is displayed.""" + ok = False + kana = romaji = None + p0 = p1 = None + shows_correct = False + has_next = False + for _ in range(6): + if not and_enter_hiragana_writing_quiz(): + continue + nodes = ui() + kana = read_question_kana(nodes) + romaji = HIRA_MAP.get(kana) + p0 = read_score_pair(nodes) + fields = find_by_class(nodes, "EditText") + if not fields: + continue + if not type_text(fields[0], "zzz"): + continue + if not tap_contains(ui(), "sure"): + enter() + settle("tap") + nodes = ui() + p1 = read_score_pair(nodes) + has_next = find_node_ci(nodes, "NEXT") is not None + if romaji: + shows_correct = any( + n.get("text", "").strip() == romaji + for n in find_by_class(nodes, "TextView")) + ok = (p0 == (0, 0) and p1 == (0, 1) and has_next + and (shows_correct if romaji else True)) + break + record("computation_writing_wrong_01", ok, + "" if ok else + (f"behavior_wrong: kana={kana!r} typed 'zzz' score {p0}->{p1}, " + f"has_next={has_next}, shows_correct({romaji!r})={shows_correct}, " + f"expected (0,0)->(0,1) with NEXT and the correct romaji shown" + if p1 is not None else + "setup_failed: could not reach the writing test input"), + depth=2, jump_kind="value", + expect="Session score: 0/1 + NEXT + correct romaji after a wrong typed answer") + + +@and_test(expects=("computation_writing_dontknow_01",)) +def test_writing_dont_know(): + """DON'T KNOW on the writing test counts as wrong -> 0/0 -> 0/1 + NEXT and + the correct romaji is revealed. The score change is deterministic; the map + only checks the revealed answer.""" + ok_nav = and_enter_hiragana_writing_quiz() + nodes = ui() + kana = read_question_kana(nodes) + romaji = HIRA_MAP.get(kana) + p0 = read_score_pair(nodes) + tapped = tap_contains(nodes, "don't know") + settle("tap") + nodes = ui() + p1 = read_score_pair(nodes) + has_next = find_node_ci(nodes, "NEXT") is not None + shows_correct = (any(n.get("text", "").strip() == romaji + for n in find_by_class(nodes, "TextView")) + if romaji else True) + ok = (ok_nav and tapped and p0 == (0, 0) and p1 == (0, 1) + and has_next and shows_correct) + record("computation_writing_dontknow_01", ok, + "" if ok else + f"behavior_wrong: writing DON'T KNOW score {p0}->{p1}, " + f"has_next={has_next}, shows_correct={shows_correct}, " + f"expected (0,0)->(0,1) with NEXT (nav={ok_nav}, tapped={tapped})", + depth=2, jump_kind="value", + expect="Session score: 0/1 + NEXT after DON'T KNOW on the writing test") + + +@and_test(expects=("computation_writing_two_correct_22",)) +def test_writing_two_correct(): + """Text-typing running tally: two correct typed answers -> 2/2.""" + ok = False + p1 = p2 = None + for _ in range(6): + if not and_enter_hiragana_writing_quiz(): + continue + a1, k1, r1, p1 = answer_writing_correct(HIRA_MAP) + if not a1 or p1 != (1, 1): + continue + a2, k2, r2, p2 = answer_writing_correct(HIRA_MAP) + if a2: + ok = p2 == (2, 2) + break + record("computation_writing_two_correct_22", ok, + "" if ok else + (f"behavior_wrong: two correct typed answers -> {p2!r}, expected (2,2)" + if p1 == (1, 1) else + "setup_failed: could not type two consecutive mappable answers"), + depth=2, jump_kind="value", + expect="Session score: 2/2 after two correct typed answers") + + +@and_test(expects=("computation_kata_writing_correct_11",)) +def test_kata_writing_correct(): + """Katakana text-typing correct -> score 0/0 -> 1/1 (katakana map).""" + ok = False + kana = romaji = None + p0 = p1 = None + for _ in range(6): + if not and_enter_katakana_writing_quiz(): + continue + p0 = read_score_pair(ui()) + attempted, kana, romaji, p1 = answer_writing_correct(KATA_MAP) + if attempted: + ok = p0 == (0, 0) and p1 == (1, 1) + break + record("computation_kata_writing_correct_11", ok, + "" if ok else + (f"behavior_wrong: kata kana={kana!r} typed={romaji!r} score {p0}->{p1}, " + f"expected (0,0)->(1,1)" + if p1 is not None else + "setup_failed: could not reach a mappable katakana writing question"), + depth=2, jump_kind="value", + expect="Session score: 1/1 after a correct katakana typed answer") + + +TESTS = [ + test_hira_grid_start_score_zero, + test_hira_grid_correct_sure, + test_hira_grid_correct_maybe, + test_hira_grid_wrong, + test_hira_grid_dont_know, + test_hira_grid_two_correct, + test_hira_grid_correct_then_wrong, + test_hira_grid_dontknow_then_correct, + test_kata_grid_correct, + test_kata_grid_dont_know, + test_kata_grid_two_correct, + test_writing_start_score_zero, + test_writing_correct, + test_writing_wrong, + test_writing_dont_know, + test_writing_two_correct, + test_kata_writing_correct, +] + + +if __name__ == "__main__": + if not device_online(): + print("Device offline — cannot run computation suite.") + sys.exit(1) + run_suite(TESTS, "computation") diff --git a/android/blastrock-kakugo/tests/test_android_interaction.py b/android/blastrock-kakugo/tests/test_android_interaction.py new file mode 100644 index 0000000000000000000000000000000000000000..fbb4a7f5a25a40f02306ffc5b9a5f0f47cc6acf4 --- /dev/null +++ b/android/blastrock-kakugo/tests/test_android_interaction.py @@ -0,0 +1,938 @@ +#!/usr/bin/env python3 +"""INTERACTION lane for Kakugo (org.kaqui). + +Owner of EFFECT-BY-CONSEQUENCE on user DATA: the item-selection DB (checkbox -> +StatsBar count -> persistence across process death), multi-record integrity, +the multi-step quiz score/history sequence, and long-press (single-button mode). + +Every test drives the app through the real USER PATH from its own entry point +(restart_app), performs the action, then reads the consequence back out of a +FRESH ui() and asserts it against what was observed on the running original. +All paths below were confirmed live on the original before authoring: + + * Item selection (Main->KANJI->KANJI SELECTION->JLPT level 5): unchecking the + first (checked) CheckBox flips the top StatsBar from ['80'] to ['1','79'] + (1 disabled segment appears, the good segment drops 80->79). The unchecked + bit SURVIVES force_stop_and_relaunch() and re-navigation — an in-memory-only + recreation cannot pass interaction_item_persist_process_death. Every mutation + test RE-CHECKS the item before finishing so later quiz-start tests keep >=10 + enabled (kanji is a separate DB from hiragana/katakana). + * Grid quiz (Main->HIRAGANA->"HIRAGANA TO ROMAJI QUIZ"): after SHOW ANSWERS the + correct romaji option is always present; tapping the SURE of the option whose + romaji matches the question kana (via KANA2ROMAJI) increments both halves of + "Session score: n/d". A wrong SURE holds the numerator, increments the + denominator, highlights the chosen cell red + correct cell green, and flips + DON'T KNOW -> NEXT. An answer-cell's SURE is disambiguated by COLUMN (x-side) + then nearest row (y) — the two same-row SUREs are mirror-equidistant, so a + plain euclidean nearest is a coin-flip and must not be used. + * A green "Show history" FAB appears after >=1 answer; tapping it opens a bottom + sheet listing the answered glyph+romaji pairs (dump-readable) rendered as + colored circles (VLM). + * Single button mode (Settings): when ON the answer cells are single buttons + (no SURE); a LONG-PRESS on a cell = a "maybe" answer that advances (denom +1). + * Kanji CUSTOM TEST: a dialog "Select the desired types of questions:" with + CheckedTextView rows; checking a type then OK opens TestActivity (a quiz). + +Match text case-insensitively and by ASCII SUBSTRING — Compose uppercases labels +and the main-menu buttons carry both scripts ("漢字\\nKANJI"). +""" +import os, re, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403 + + +# ══════════════════════════════════════════════════════════════════════════════ +# Domain data & local element helpers +# ══════════════════════════════════════════════════════════════════════════════ + +# basic gojūon + dakuten/handakuten -> the romaji strings the app renders. +KANA2ROMAJI = { + "あ": "a", "い": "i", "う": "u", "え": "e", "お": "o", + "か": "ka", "き": "ki", "く": "ku", "け": "ke", "こ": "ko", + "さ": "sa", "し": "shi", "す": "su", "せ": "se", "そ": "so", + "た": "ta", "ち": "chi", "つ": "tsu", "て": "te", "と": "to", + "な": "na", "に": "ni", "ぬ": "nu", "ね": "ne", "の": "no", + "は": "ha", "ひ": "hi", "ふ": "fu", "へ": "he", "ほ": "ho", + "ま": "ma", "み": "mi", "む": "mu", "め": "me", "も": "mo", + "や": "ya", "ゆ": "yu", "よ": "yo", + "ら": "ra", "り": "ri", "る": "ru", "れ": "re", "ろ": "ro", + "わ": "wa", "を": "wo", "ん": "n", + "が": "ga", "ぎ": "gi", "ぐ": "gu", "げ": "ge", "ご": "go", + "ざ": "za", "じ": "ji", "ず": "zu", "ぜ": "ze", "ぞ": "zo", + "だ": "da", "ぢ": "ji", "づ": "zu", "で": "de", "ど": "do", + "ば": "ba", "び": "bi", "ぶ": "bu", "べ": "be", "ぼ": "bo", + "ぱ": "pa", "ぴ": "pi", "ぷ": "pu", "ぺ": "pe", "ぽ": "po", +} +KATAKANA2ROMAJI = { + "ア": "a", "イ": "i", "ウ": "u", "エ": "e", "オ": "o", + "カ": "ka", "キ": "ki", "ク": "ku", "ケ": "ke", "コ": "ko", + "サ": "sa", "シ": "shi", "ス": "su", "セ": "se", "ソ": "so", + "タ": "ta", "チ": "chi", "ツ": "tsu", "テ": "te", "ト": "to", + "ナ": "na", "ニ": "ni", "ヌ": "nu", "ネ": "ne", "ノ": "no", + "ハ": "ha", "ヒ": "hi", "フ": "fu", "ヘ": "he", "ホ": "ho", + "マ": "ma", "ミ": "mi", "ム": "mu", "メ": "me", "モ": "mo", + "ヤ": "ya", "ユ": "yu", "ヨ": "yo", + "ラ": "ra", "リ": "ri", "ル": "ru", "レ": "re", "ロ": "ro", + "ワ": "wa", "ヲ": "wo", "ン": "n", + "ガ": "ga", "ギ": "gi", "グ": "gu", "ゲ": "ge", "ゴ": "go", + "ザ": "za", "ジ": "ji", "ズ": "zu", "ゼ": "ze", "ゾ": "zo", + "ダ": "da", "ヂ": "ji", "ヅ": "zu", "デ": "de", "ド": "do", + "バ": "ba", "ビ": "bi", "ブ": "bu", "ベ": "be", "ボ": "bo", + "パ": "pa", "ピ": "pi", "プ": "pu", "ペ": "pe", "ポ": "po", +} +_ANSWER_LABELS = {"SURE", "MAYBE", "DON'T KNOW", "NEXT", "HINT", "SHOW ANSWERS"} + + +def contains_node(nodes, token): + """First node whose text OR content-desc contains `token` (case-insensitive + substring). Compose uppercases labels and dual-script buttons carry the ASCII + token as a substring, so this is the robust menu/label matcher.""" + t = token.strip().lower() + for n in nodes: + if (t in n.get("text", "").strip().lower() + or t in n.get("content-desc", "").strip().lower()): + return n + return None + + +def fresh_main(): + """Own entry point: relaunch to a clean main menu, return its tree (or None).""" + restart_app() + return ui() if wait_for_foreground() else None + + +def statsbar_numbers(nodes): + """The top StatsBar segment counts as a left-to-right list of number strings. + They are numeric TextViews in the toolbar-adjacent strip (y roughly 200-320).""" + out = [] + for n in nodes: + b = n.get("_bounds") + t = n.get("text", "").strip() + if (b and "TextView" in n.get("class", "") and t.isdigit() + and b[1] < 320 and b[3] <= 340): + out.append((b[0], t)) + out.sort() + return [t for _x, t in out] + + +def score_pair(nodes): + """(numerator, denominator) parsed from the "Session score: n/d" TextView.""" + for n in nodes: + if n.get("text", "").strip().lower().startswith("session score"): + m = re.search(r"(\d+)\s*/\s*(\d+)", n["text"]) + if m: + return int(m.group(1)), int(m.group(2)) + return None + + +def checkboxes(nodes): + """Item-selection CheckBox nodes, top-to-bottom by y.""" + cbs = [c for c in find_by_class(nodes, "CheckBox") if c.get("_center")] + cbs.sort(key=lambda c: c["_center"][1]) + return cbs + + +def question_glyph(nodes, table): + """The large question kana/glyph: a TextView in the top question area whose + text is a key of `table`.""" + for n in nodes: + t = n.get("text", "").strip() + b = n.get("_bounds") + if (b and "TextView" in n.get("class", "") and b[1] < 1060 and b[3] > 316 + and t in table): + return t + return None + + +def answer_options(nodes): + """(text, center) for each answer romaji option in the answer grid (below the + question, above the LastItemRow), excluding button labels.""" + out = [] + for n in nodes: + t = n.get("text", "").strip() + c = n.get("_center") + if (c and "TextView" in n.get("class", "") and 1060 <= c[1] < 2100 + and t and t.upper() not in _ANSWER_LABELS): + out.append((t, c)) + return out + + +def sure_for_option(nodes, option_center): + """The SURE button belonging to the answer cell at `option_center`. + + The two SURE buttons in the same row are mirror-equidistant from a centered + option label, so a plain euclidean nearest is a coin-flip. Disambiguate by + COLUMN (same screen half as the option) first, THEN nearest row (y).""" + ox, oy = option_center + mid = get_screen_info()["width"] // 2 + sures = [s for s in nodes if s.get("text", "").strip() == "SURE" and s.get("_center")] + same_col = [s for s in sures if (s["_center"][0] < mid) == (ox < mid)] + pool = same_col or sures + if not pool: + return None + pool.sort(key=lambda s: abs(s["_center"][1] - oy)) + return pool[0] + + +def show_answers_if_present(nodes, tries=4): + """Tap SHOW ANSWERS if the grid is gated, then return a tree where the answer + grid (>=2 SURE cells) is actually rendered — the lazy grid can lag a dump.""" + sa = contains_node(nodes, "SHOW ANSWERS") + if sa: + tap_node(sa) + n = ui() + for _ in range(tries): + if len([s for s in n if s.get("text", "").strip() == "SURE"]) >= 2: + break + settle("tap") + n = ui() + return n + + +def open_hiragana_quiz(): + """Main -> HIRAGANA menu -> 'HIRAGANA TO ROMAJI QUIZ'. Returns the quiz tree + (score present) or None. Records one surface via and_enter on success.""" + n = fresh_main() + if n is None: + return None + b = contains_node(n, "HIRAGANA") + if not b or not tap_node(b): + return None + and_enter("hiragana_menu") + n = ui() + q = contains_node(n, "HIRAGANA TO ROMAJI QUIZ") + if not q or not tap_node(q): + return None + and_enter("quiz") + n = ui() + return n if score_pair(n) is not None else None + + +def and_reach_item_selection(): + """Main -> KANJI -> KANJI SELECTION -> JLPT level 5 (ItemSelectionActivity). + Returns the item-selection tree (checkboxes present) or None. The and_reach_* + NAME backs the depth-3 declaration; each and_enter marks one crossed surface.""" + n = fresh_main() + if n is None: + return None + b = contains_node(n, "KANJI") + if not b or not tap_node(b): + return None + and_enter("kanji_menu") + n = ui() + sel = contains_node(n, "KANJI SELECTION") + if not sel or not tap_node(sel): + return None + and_enter("class_selection") + n = ui() + lvl = contains_node(n, "JLPT level 5") + if not lvl or not tap_node(lvl): + return None + and_enter("item_selection") + n = ui() + return n if checkboxes(n) else None + + +def navigate_kanji_item_selection_only(): + """Re-navigate to JLPT-level-5 item selection WITHOUT touching depth counters + (used inside persistence tests, which already declared their depth). Returns + the tree or None.""" + n = ui() + b = contains_node(n, "KANJI") + if not b or not tap_node(b): + return None + n = ui() + sel = contains_node(n, "KANJI SELECTION") + if not sel or not tap_node(sel): + return None + n = ui() + lvl = contains_node(n, "JLPT level 5") + if not lvl or not tap_node(lvl): + return None + n = ui() + return n if checkboxes(n) else None + + +def restore_checkbox(index=0): + """Ensure item-selection CheckBox #index is CHECKED, re-navigating from a + fresh main menu. Called by every kanji-selection-mutating test so it never + leaves the kanji DB below the >=10 quiz-start threshold.""" + n = fresh_main() + if n is None: + return + n = navigate_kanji_item_selection_only() + if not n: + return + cbs = checkboxes(n) + if index < len(cbs) and cbs[index].get("checked") == "false": + tap_node(cbs[index]) + + +def answer_one(correct=True, table=None): + """Answer the CURRENT grid question. correct=True taps the SURE of the correct + option; correct=False taps the SURE of a wrong option. Returns (before, after) + score pairs, or (before, None) if it could not act. Does NOT press NEXT.""" + table = table or KANA2ROMAJI + n = show_answers_if_present(ui()) + before = score_pair(n) + glyph = question_glyph(n, table) + want = table.get(glyph) if glyph else None + opts = answer_options(n) + if not want or not opts: + return before, None + if correct: + target = next((c for (t, c) in opts if t == want), None) + else: + target = next((c for (t, c) in opts if t != want), None) + if target is None: + return before, None + sb = sure_for_option(n, target) + if not sb or not tap_node(sb): + return before, None + return before, score_pair(ui()) + + +def press_next_if_present(): + nxt = contains_node(ui(), "NEXT") + if nxt: + tap_node(nxt) + + +# ══════════════════════════════════════════════════════════════════════════════ +# TESTS +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_item_toggle_statsbar",)) +def test_item_toggle_statsbar(): + """Uncheck one enabled kanji -> the StatsBar good-count drops and a disabled + segment appears (observed 80 -> 79 good, plus a '1' disabled segment).""" + name = "interaction_item_toggle_statsbar" + n = and_reach_item_selection() + if n is None: + record(name, False, "setup_failed: could not reach JLPT level 5 item selection", + depth=3, jump_kind="value", expect="StatsBar good-count decreases by 1") + return + before = statsbar_numbers(n) + cbs = checkboxes(n) + if not before or not cbs or cbs[0].get("checked") != "true": + record(name, False, "setup_failed: no enabled checkbox / StatsBar to toggle", + depth=3, jump_kind="value", expect="StatsBar good-count decreases by 1") + return + good_before = max(int(x) for x in before) # the enabled segment = largest + tap_node(cbs[0]) + n2 = ui() + after = statsbar_numbers(n2) + cb0_after = checkboxes(n2)[0].get("checked") if checkboxes(n2) else None + good_after = max(int(x) for x in after) if after else None + ok = (cb0_after == "false" and good_after == good_before - 1 + and len(after) > len(before)) + record(name, ok, + "" if ok else f"behavior_wrong: StatsBar {before}->{after} on uncheck " + f"(expected good {good_before}->{good_before-1} + a disabled segment)", + depth=3, jump_kind="value", + expect=f"StatsBar good {good_before}->{good_before-1}, disabled segment appears") + restore_checkbox(0) + + +@and_test(expects=("interaction_item_persist_reopen",)) +def test_item_persist_reopen(): + """Uncheck an item, LEAVE the selection screen and REOPEN it -> the checkbox + is still unchecked (the change is written to the DB, not just view state).""" + name = "interaction_item_persist_reopen" + n = and_reach_item_selection() + if n is None: + record(name, False, "setup_failed: could not reach item selection", + depth=3, jump_kind="value", expect="checkbox #0 still unchecked after reopen") + return + cbs = checkboxes(n) + if not cbs or cbs[0].get("checked") != "true": + record(name, False, "setup_failed: checkbox #0 not initially checked", + depth=3, jump_kind="value", expect="checkbox #0 still unchecked after reopen") + return + tap_node(cbs[0]) + unchecked_now = checkboxes(ui())[0].get("checked") == "false" + # leave to the main menu, then re-navigate to the SAME screen + restart_app(); wait_for_foreground() + n2 = navigate_kanji_item_selection_only() + still = bool(n2) and checkboxes(n2) and checkboxes(n2)[0].get("checked") == "false" + ok = unchecked_now and still + record(name, ok, + "" if ok else "behavior_wrong: checkbox reverted to checked after leaving+reopening", + depth=3, jump_kind="value", expect="checkbox #0 still unchecked after reopen") + restore_checkbox(0) + + +@and_test(expects=("interaction_item_persist_process_death",)) +def test_item_persist_process_death(): + """HIGHEST-VALUE: uncheck an item, kill the process with + force_stop_and_relaunch(), re-navigate to the SAME item-selection screen -> + the checkbox is STILL unchecked. An in-memory-only recreation cannot pass.""" + name = "interaction_item_persist_process_death" + n = and_reach_item_selection() + if n is None: + record(name, False, "setup_failed: could not reach item selection", + depth=3, jump_kind="value", + expect="checkbox #0 unchecked after process death") + return + cbs = checkboxes(n) + if not cbs or cbs[0].get("checked") != "true": + record(name, False, "setup_failed: checkbox #0 not initially checked", + depth=3, jump_kind="value", + expect="checkbox #0 unchecked after process death") + return + tap_node(cbs[0]) + unchecked_now = checkboxes(ui())[0].get("checked") == "false" + force_stop_and_relaunch() + wait_for_foreground() + n2 = navigate_kanji_item_selection_only() + survived = bool(n2) and checkboxes(n2) and checkboxes(n2)[0].get("checked") == "false" + ok = unchecked_now and survived + record(name, ok, + "" if ok else "behavior_wrong: checkbox reverted after force-stop+relaunch " + "(state was not persisted to disk)", + depth=3, jump_kind="value", + expect="checkbox #0 still unchecked after force_stop_and_relaunch") + restore_checkbox(0) + + +@and_test(expects=("interaction_multi_record_integrity", + "interaction_multi_record_integrity_vlm")) +def test_multi_record_integrity(): + """Uncheck the 2nd of the first three items; assert the 1st and 3rd are STILL + checked and only the 2nd flipped — a recreation that rebuilds the whole list + from one row cannot keep the other two intact. VLM confirms the StatsBar + segment visibly changed colour/width.""" + name = "interaction_multi_record_integrity" + vlm = "interaction_multi_record_integrity_vlm" + n = and_reach_item_selection() + if n is None: + record(name, False, "setup_failed: could not reach item selection", + depth=3, jump_kind="value", + expect="rows 0&2 checked, row 1 unchecked") + record(vlm, False, "setup_failed: could not reach item selection", + depth=3, jump_kind="transition", tag="color") + return + cbs = checkboxes(n) + if len(cbs) < 3 or any(cbs[i].get("checked") != "true" for i in range(3)): + record(name, False, "setup_failed: first three items not all initially checked", + depth=3, jump_kind="value", + expect="rows 0&2 checked, row 1 unchecked") + record(vlm, False, "setup_failed: first three items not all checked", + depth=3, jump_kind="transition", tag="color") + return + before = statsbar_numbers(n) + tap_node(cbs[1]) # flip only the SECOND item + n2 = ui() + cbs2 = checkboxes(n2) + after = statsbar_numbers(n2) + ok = (len(cbs2) >= 3 + and cbs2[0].get("checked") == "true" + and cbs2[1].get("checked") == "false" + and cbs2[2].get("checked") == "true") + record(name, ok, + "" if ok else f"behavior_wrong: after unchecking row1, checked states are " + f"{[cbs2[i].get('checked') for i in range(min(3,len(cbs2)))]} " + f"(expected [true,false,true])", + depth=3, jump_kind="value", expect="rows 0&2 checked, row 1 unchecked") + # VLM: the StatsBar changed (a disabled segment now colours part of the bar) + changed = after != before + vlm_assert(vlm, + "Look at the thin horizontal status bar directly under the blue " + "toolbar. Is it split into TWO differently coloured segments (a wide " + "coloured segment and a separate smaller segment of a different " + "colour), rather than being one single solid colour?", + expect="YES", depth=3, jump_kind="transition", tag="color") + if not changed: + print(" [note] StatsBar numbers did not change after toggle:", before, after) + restore_checkbox(1) + + +@and_test(expects=("interaction_quiz_score_correct",)) +def test_quiz_score_correct(): + """Grid quiz: answer CORRECT (SURE of the option matching the question kana) + -> Session score 0/0 -> 1/1 (both halves increment).""" + name = "interaction_quiz_score_correct" + n = open_hiragana_quiz() + if n is None: + record(name, False, "setup_failed: could not start the hiragana grid quiz", + depth=2, jump_kind="value", expect="Session score 0/0 -> 1/1") + return + before, after = answer_one(correct=True) + ok = before == (0, 0) and after == (1, 1) + record(name, ok, + "" if ok else f"behavior_wrong: score {before}->{after} on a correct answer " + f"(expected (0,0)->(1,1))", + depth=2, jump_kind="value", expect="Session score 0/0 -> 1/1 on correct answer") + + +@and_test(expects=("interaction_quiz_score_wrong", + "interaction_quiz_score_wrong_vlm")) +def test_quiz_score_wrong(): + """Grid quiz: answer WRONG -> numerator held, denominator +1 (0/0 -> 0/1) and + DON'T KNOW becomes NEXT. VLM confirms the chosen cell is red/pink and the + correct cell green.""" + name = "interaction_quiz_score_wrong" + vlm = "interaction_quiz_score_wrong_vlm" + n = open_hiragana_quiz() + if n is None: + record(name, False, "setup_failed: could not start the hiragana grid quiz", + depth=2, jump_kind="value", expect="Session score 0/0 -> 0/1 + NEXT") + record(vlm, False, "setup_failed: could not start quiz", + depth=2, jump_kind="value", tag="color") + return + before, after = answer_one(correct=False) + has_next = contains_node(ui(), "NEXT") is not None + ok = before == (0, 0) and after == (0, 1) and has_next + record(name, ok, + "" if ok else f"behavior_wrong: score {before}->{after}, NEXT={has_next} " + f"on a wrong answer (expected (0,0)->(0,1) + NEXT)", + depth=2, jump_kind="value", expect="Session score 0/0 -> 0/1 + NEXT on wrong answer") + vlm_assert(vlm, + "In the answer grid, exactly one answer cell has a PINK/RED " + "background and exactly one other answer cell has a GREEN " + "background (the rest are white). Is that the case?", + expect="YES", depth=2, jump_kind="value", tag="color") + + +@and_test(expects=("interaction_quiz_multistep_tally",)) +def test_quiz_multistep_tally(): + """3+ step sequence: answer THREE questions correctly in a row -> the running + Session score tally reaches 3/3. A dead shell that echoes the first answer + cannot advance the denominator three times.""" + name = "interaction_quiz_multistep_tally" + n = open_hiragana_quiz() + if n is None: + record(name, False, "setup_failed: could not start the hiragana grid quiz", + depth=2, jump_kind="value", expect="Session score reaches 3/3") + return + seq = [] + for i in range(3): + before, after = answer_one(correct=True) + seq.append((before, after)) + if after is None: + record(name, False, f"behavior_wrong: could not answer question {i+1} " + f"(score stuck at {before})", + depth=2, jump_kind="value", expect="Session score reaches 3/3") + return + press_next_if_present() + final = score_pair(ui()) + ok = final == (3, 3) + record(name, ok, + "" if ok else f"behavior_wrong: final score {final} after 3 correct answers " + f"(expected (3,3)); steps={seq}", + depth=2, jump_kind="value", expect="Session score 3/3 after three correct answers") + + +@and_test(expects=("interaction_quiz_mixed_tally",)) +def test_quiz_mixed_tally(): + """3+ step sequence with a running tally: two CORRECT then one WRONG -> + 2/3 (numerator counts only the two correct, denominator counts all three).""" + name = "interaction_quiz_mixed_tally" + n = open_hiragana_quiz() + if n is None: + record(name, False, "setup_failed: could not start the hiragana grid quiz", + depth=2, jump_kind="value", expect="Session score 2/3 (2 correct, 1 wrong)") + return + plan = [True, True, False] + seq = [] + for i, correct in enumerate(plan): + before, after = answer_one(correct=correct) + seq.append((correct, before, after)) + if after is None: + record(name, False, f"behavior_wrong: could not answer question {i+1} " + f"(score stuck at {before})", + depth=2, jump_kind="value", expect="Session score 2/3 (2 correct, 1 wrong)") + return + press_next_if_present() + final = score_pair(ui()) + ok = final == (2, 3) + record(name, ok, + "" if ok else f"behavior_wrong: final score {final} after 2 correct + 1 wrong " + f"(expected (2,3)); steps={seq}", + depth=2, jump_kind="value", expect="Session score 2/3 after two correct + one wrong") + + +@and_test(expects=("interaction_quiz_history_sheet", + "interaction_quiz_history_sheet_vlm")) +def test_quiz_history_sheet(): + """After answering, the green 'Show history' FAB opens a bottom sheet that + lists the answered item(s). Assert the answered glyph+romaji reappear in the + sheet (dump-readable), and VLM confirms the coloured item circles.""" + name = "interaction_quiz_history_sheet" + vlm = "interaction_quiz_history_sheet_vlm" + n = open_hiragana_quiz() + if n is None: + record(name, False, "setup_failed: could not start the hiragana grid quiz", + depth=3, jump_kind="value", expect="history sheet lists the answered romaji") + record(vlm, False, "setup_failed: could not start quiz", + depth=3, jump_kind="transition", tag="color") + return + # answer once, remembering the romaji we answered + ntree = show_answers_if_present(ui()) + glyph = question_glyph(ntree, KANA2ROMAJI) + answered_romaji = KANA2ROMAJI.get(glyph) + before, after = answer_one(correct=True) + if after is None or answered_romaji is None: + record(name, False, "setup_failed: could not answer the first question", + depth=3, jump_kind="value", expect="history sheet lists the answered romaji") + record(vlm, False, "setup_failed: could not answer", depth=3, + jump_kind="transition", tag="color") + return + press_next_if_present() + fab = find_node(ui(), content_desc="Show history") + if not fab or not tap_node(fab): + record(name, False, "feature_missing: no 'Show history' FAB after answering", + depth=3, jump_kind="value", expect="history sheet lists the answered romaji") + record(vlm, False, "feature_missing: no history FAB", depth=3, + jump_kind="transition", tag="color") + return + and_enter("history_sheet") + sheet = ui() + # the answered romaji reappears in the sheet as a row label + listed = any(x.get("text", "").strip() == answered_romaji for x in sheet) + record(name, listed, + "" if listed else f"behavior_wrong: answered romaji {answered_romaji!r} not " + f"listed in the history sheet", + depth=3, jump_kind="value", + expect=f"history sheet lists answered romaji {answered_romaji!r}") + vlm_assert(vlm, + "Near the top-left of the screen, is there a small ROUND coloured " + "circle (green or pink/red) with a Japanese character inside it?", + expect="YES", depth=3, jump_kind="transition", tag="color") + + +@and_test(expects=("interaction_lastitemrow_updates",)) +def test_lastitemrow_updates(): + """After the first answer, the bottom LastItemRow shows the just-answered + glyph; after a SECOND (different) answer it shows the new glyph — the row + tracks the latest answered item (data effect across two steps).""" + name = "interaction_lastitemrow_updates" + n = open_hiragana_quiz() + if n is None: + record(name, False, "setup_failed: could not start the hiragana grid quiz", + depth=2, jump_kind="value", expect="LastItemRow shows each just-answered glyph") + return + + def lastrow_glyphs(nodes): + # LastItemRow sits at the very bottom (y >= 2150); its glyph circles are + # single-kana TextViews there. + gl = [] + for x in nodes: + t = x.get("text", "").strip() + c = x.get("_center") + if c and c[1] >= 2150 and t in KANA2ROMAJI: + gl.append(t) + return gl + + tree1 = show_answers_if_present(ui()) + g1 = question_glyph(tree1, KANA2ROMAJI) + b1, a1 = answer_one(correct=True) + row_after_1 = lastrow_glyphs(ui()) + shows1 = g1 in row_after_1 + press_next_if_present() + + tree2 = show_answers_if_present(ui()) + g2 = question_glyph(tree2, KANA2ROMAJI) + b2, a2 = answer_one(correct=True) + row_after_2 = lastrow_glyphs(ui()) + shows2 = g2 in row_after_2 + + ok = a1 is not None and a2 is not None and shows1 and shows2 + record(name, ok, + "" if ok else f"behavior_wrong: LastItemRow did not track answered glyphs " + f"(q1={g1!r} row1={row_after_1}; q2={g2!r} row2={row_after_2})", + depth=2, jump_kind="value", + expect="LastItemRow shows the just-answered glyph after each answer") + + +@and_test(expects=("interaction_singlebutton_longpress",)) +def test_singlebutton_longpress(): + """LONG-PRESS (interaction-lane-owned). Enable Single button mode so answer + cells are single buttons whose LONG-PRESS = a 'maybe' answer that advances; + long-press one -> the score denominator increments (0/0 -> 0/1). Restores the + switch to OFF so later grid-quiz tests keep their SURE buttons.""" + name = "interaction_singlebutton_longpress" + n = fresh_main() + if n is None: + record(name, False, "setup_failed: could not reach main menu", + depth=2, jump_kind="value", expect="denominator +1 after long-press") + return + s = contains_node(n, "SETTINGS") + if not s or not tap_node(s): + record(name, False, "setup_failed: could not open Settings", + depth=2, jump_kind="value", expect="denominator +1 after long-press") + return + n = ui() + sbm = contains_node(n, "Single button mode") + if not sbm or not tap_node(sbm): + record(name, False, "feature_missing: no Single button mode preference", + depth=2, jump_kind="value", expect="denominator +1 after long-press") + return + settle("tap") + try: + # start a hiragana grid quiz (own path from main) + q = open_hiragana_quiz() + if q is None: + record(name, False, "setup_failed: could not start quiz in single-button mode", + depth=2, jump_kind="value", expect="denominator +1 after long-press") + return + tree = ui() + sa = contains_node(tree, "SHOW ANSWERS") + if sa: + tap_node(sa) + tree = ui() + before = score_pair(tree) + opts = answer_options(tree) + if before is None or not opts: + record(name, False, "setup_failed: no answer cells in single-button mode", + depth=2, jump_kind="value", expect="denominator +1 after long-press") + return + # in single-button mode the option label IS the tappable/long-pressable cell + cell = None + for x in tree: + if x.get("text", "").strip() == opts[0][0] and x.get("_center"): + cell = x + break + if cell is None or not long_press(cell): + record(name, False, "behavior_wrong: long-press on answer cell did not register", + depth=2, jump_kind="value", expect="denominator +1 after long-press") + return + after = score_pair(ui()) + ok = after is not None and after[1] == before[1] + 1 + record(name, ok, + "" if ok else f"behavior_wrong: score {before}->{after} after long-press " + f"(expected denominator +1)", + depth=2, jump_kind="value", + expect=f"denominator {before}->({before[0]},{before[1]+1}) after long-press") + finally: + # ALWAYS restore Single button mode -> OFF (else grid quizzes lose SURE). + m = fresh_main() + if m is not None: + st = contains_node(m, "SETTINGS") + if st and tap_node(st): + cur = ui() + row = contains_node(cur, "Single button mode") + sw = find_by_class(cur, "Switch") + # the single-button switch is the 4th switch (index 3) in Behavior + if row and len(sw) >= 4 and sw[3].get("checked") == "true": + tap_node(row) + + +@and_test(expects=("interaction_custom_test_launch",)) +def test_custom_test_launch(): + """Multi-step selection -> launch: Kanji CUSTOM TEST opens a multi-choice + dialog; check a question type then OK -> TestActivity opens (a quiz with a + Session score). Assert the dialog vanished and the quiz surface appeared.""" + name = "interaction_custom_test_launch" + n = fresh_main() + if n is None: + record(name, False, "setup_failed: could not reach main menu", + depth=2, jump_kind="reach", expect="TestActivity opens after selecting a type + OK") + return + k = contains_node(n, "KANJI") + if not k or not tap_node(k): + record(name, False, "setup_failed: could not open Kanji menu", + depth=2, jump_kind="reach", expect="TestActivity opens after selecting a type + OK") + return + and_enter("kanji_menu") + n = ui() + ct = contains_node(n, "CUSTOM TEST") + if not ct or not tap_node(ct): + record(name, False, "feature_missing: no CUSTOM TEST button in the Kanji menu", + depth=2, jump_kind="reach", expect="TestActivity opens after selecting a type + OK") + return + dialog = ui() + before = and_showing(dialog) + if contains_node(dialog, "Select the desired types of questions") is None: + record(name, False, "feature_missing: CUSTOM TEST did not open the type-selection dialog", + depth=2, jump_kind="reach", expect="TestActivity opens after selecting a type + OK") + return + row = contains_node(dialog, "Kanji to reading") + if not row: + record(name, False, "setup_failed: could not find a question type row", + depth=2, jump_kind="reach", expect="TestActivity opens after selecting a type + OK") + return + # The dialog REMEMBERS the previous selection, so the row may already be + # checked. Only tap it if it is currently unchecked, so a type ends up + # checked=true (an already-checked row would toggle OFF and OK would refuse). + if row.get("checked") == "false": + tap_node(row) + row = contains_node(ui(), "Kanji to reading") + if not row or row.get("checked") != "true": + record(name, False, "setup_failed: could not check a question type", + depth=2, jump_kind="reach", expect="TestActivity opens after selecting a type + OK") + return + ok_btn = contains_node(ui(), "OK") + if not ok_btn or not tap_node(ok_btn): + record(name, False, "setup_failed: no OK button in the dialog", + depth=2, jump_kind="reach", expect="TestActivity opens after selecting a type + OK") + return + settle("tap") + after_tree = ui() + after = and_showing(after_tree) + # the quiz opened iff a Session score appeared and the dialog title vanished + quiz_up = score_pair(after_tree) is not None + dialog_gone = not any("select the desired" in k.lower() for k in after) + reached = and_reach(before, after, "Session score", "Select the desired") or (quiz_up and dialog_gone) + if reached: + and_enter("custom_test_quiz") + record(name, reached, + "" if reached else "behavior_wrong: TestActivity did not open after selecting a " + "type and pressing OK", + depth=2, jump_kind="reach", + expect="TestActivity (Session score) opens, dialog dismissed") + + +@and_test(expects=("interaction_wrong_lastitem_circles_vlm",)) +def test_wrong_lastitem_circles_vlm(): + """After a WRONG grid answer, the bottom LastItemRow renders the two answered + items as coloured CIRCLES — the wrong choice in a PINK/RED circle and the + correct kana in a GREEN circle. That colour coding is not readable from the + dump and is produced only by actually processing the answer, so a dead shell + fails it. (The drawing-canvas ink is NOT asserted: that DrawView discards any + stroke that does not match the target kana's stroke order, so `input swipe` + cannot reliably leave ink on the original — an unobservable behaviour.)""" + vlm = "interaction_wrong_lastitem_circles_vlm" + n = open_hiragana_quiz() + if n is None: + record(vlm, False, "setup_failed: could not start the hiragana grid quiz", + depth=2, jump_kind="value", tag="color") + return + before, after = answer_one(correct=False) + if after is None: + record(vlm, False, "setup_failed: could not submit a wrong answer", + depth=2, jump_kind="value", tag="color") + return + settle("tap") + vlm_assert(vlm, + "Look ONLY at the thin strip along the very BOTTOM of the screen " + "(below the answer grid and the NEXT button). Does it show two small " + "ROUND coloured circles side by side — one PINK/RED and one GREEN — " + "each containing a Japanese character?", + expect="YES", depth=2, jump_kind="value", tag="color") + +@and_test(expects=("interaction_katakana_score_correct",)) +def test_katakana_score_correct(): + """Second quiz DB: Katakana grid quiz correct answer -> Session score 0/0 -> + 1/1 (confirms the score engine is per-quiz, not a hardcoded hiragana echo).""" + name = "interaction_katakana_score_correct" + n = fresh_main() + if n is None: + record(name, False, "setup_failed: could not reach main menu", + depth=2, jump_kind="value", expect="Session score 0/0 -> 1/1 (katakana)") + return + k = contains_node(n, "KATAKANA") + if not k or not tap_node(k): + record(name, False, "setup_failed: could not open Katakana menu", + depth=2, jump_kind="value", expect="Session score 0/0 -> 1/1 (katakana)") + return + and_enter("katakana_menu") + n = ui() + q = contains_node(n, "KATAKANA TO ROMAJI") + if not q or not tap_node(q): + record(name, False, "feature_missing: no katakana-to-romaji quiz button", + depth=2, jump_kind="value", expect="Session score 0/0 -> 1/1 (katakana)") + return + and_enter("quiz") + if score_pair(ui()) is None: + record(name, False, "setup_failed: katakana quiz did not start (no Session score)", + depth=2, jump_kind="value", expect="Session score 0/0 -> 1/1 (katakana)") + return + before, after = answer_one(correct=True, table=KATAKANA2ROMAJI) + ok = before == (0, 0) and after == (1, 1) + record(name, ok, + "" if ok else f"behavior_wrong: katakana score {before}->{after} on a correct " + f"answer (expected (0,0)->(1,1))", + depth=2, jump_kind="value", expect="Session score 0/0 -> 1/1 on correct katakana answer") + + +@and_test(expects=("interaction_dontknow_counts_wrong",)) +def test_dontknow_counts_wrong(): + """DON'T KNOW is treated as a wrong answer: Session score 0/0 -> 0/1 and the + button flips to NEXT (a distinct interaction from tapping a wrong SURE).""" + name = "interaction_dontknow_counts_wrong" + n = open_hiragana_quiz() + if n is None: + record(name, False, "setup_failed: could not start the hiragana grid quiz", + depth=2, jump_kind="value", expect="Session score 0/0 -> 0/1 + NEXT after DON'T KNOW") + return + tree = show_answers_if_present(ui()) + before = score_pair(tree) + dk = contains_node(tree, "DON'T KNOW") + if before is None or not dk or not tap_node(dk): + record(name, False, "feature_missing: no DON'T KNOW button on the grid quiz", + depth=2, jump_kind="value", expect="Session score 0/0 -> 0/1 + NEXT after DON'T KNOW") + return + after = score_pair(ui()) + has_next = contains_node(ui(), "NEXT") is not None + ok = before == (0, 0) and after == (0, 1) and has_next + record(name, ok, + "" if ok else f"behavior_wrong: score {before}->{after}, NEXT={has_next} after " + f"DON'T KNOW (expected (0,0)->(0,1) + NEXT)", + depth=2, jump_kind="value", expect="Session score 0/0 -> 0/1 + NEXT after DON'T KNOW") + + +@and_test(expects=("interaction_next_advances_question",)) +def test_next_advances_question(): + """After a wrong answer, tapping NEXT loads a NEW question: the denominator + stays put (NEXT is not itself an answer) and the quiz re-gates to SHOW ANSWERS + — a 3-step sequence (answer -> NEXT -> observe fresh question).""" + name = "interaction_next_advances_question" + n = open_hiragana_quiz() + if n is None: + record(name, False, "setup_failed: could not start the hiragana grid quiz", + depth=2, jump_kind="transition", expect="new question after NEXT (denominator held)") + return + tree = show_answers_if_present(ui()) + q1 = question_glyph(tree, KANA2ROMAJI) + before, after = answer_one(correct=False) + if after is None: + record(name, False, "setup_failed: could not submit a wrong answer", + depth=2, jump_kind="transition", expect="new question after NEXT (denominator held)") + return + nxt = contains_node(ui(), "NEXT") + if not nxt or not tap_node(nxt): + record(name, False, "behavior_wrong: no NEXT button appeared after a wrong answer", + depth=2, jump_kind="transition", expect="new question after NEXT (denominator held)") + return + post = ui() + denom_after_next = score_pair(post) + # after NEXT the grid re-gates (SHOW ANSWERS returns) OR a fresh question glyph is shown + regated = contains_node(post, "SHOW ANSWERS") is not None + q2 = question_glyph(show_answers_if_present(post), KANA2ROMAJI) if not regated else "gated" + advanced = regated or (q2 is not None and q2 != q1) + denom_held = denom_after_next is not None and denom_after_next[1] == after[1] + ok = advanced and denom_held + record(name, ok, + "" if ok else f"behavior_wrong: NEXT did not advance cleanly " + f"(q1={q1!r} regated={regated} q2={q2!r} " + f"denom {after}->{denom_after_next})", + depth=2, jump_kind="transition", + expect="NEXT loads a new question and holds the denominator") + + +TESTS = [ + # ---- item-selection DB: toggle, persistence, multi-record integrity ---- + test_item_toggle_statsbar, + test_item_persist_reopen, + test_item_persist_process_death, + test_multi_record_integrity, + # ---- quiz score engine + multi-step running tally ---- + test_quiz_score_correct, + test_quiz_score_wrong, + test_quiz_multistep_tally, + test_quiz_mixed_tally, + # ---- history sheet, last-item row, long-press, custom test, bottom-row circles ---- + test_quiz_history_sheet, + test_lastitemrow_updates, + test_singlebutton_longpress, + test_custom_test_launch, + test_wrong_lastitem_circles_vlm, + # ---- second quiz DB + wrong-answer variants ---- + test_katakana_score_correct, + test_dontknow_counts_wrong, + test_next_advances_question, +] + +if __name__ == "__main__": + run_suite(TESTS, "interaction") diff --git a/android/blastrock-kakugo/tests/test_android_navigation.py b/android/blastrock-kakugo/tests/test_android_navigation.py new file mode 100644 index 0000000000000000000000000000000000000000..939b81e4e09473c71c750b5cd99d5e98db489d5a --- /dev/null +++ b/android/blastrock-kakugo/tests/test_android_navigation.py @@ -0,0 +1,453 @@ +#!/usr/bin/env python3 +"""NAVIGATION lane for Kakugo (org.kaqui). + +Owner of jump_kind="reach" and of depth>=2 chains. Every jump is proven with +and_reach(before, after, target, source): the TARGET surface's discriminating +element APPEARED and the SOURCE surface's element DISAPPEARED. All targets/sources +were confirmed on the running original before authoring. + +Each destination is reached through a named `and_reach_()` helper that +opens its OWN entry point (restart_app) and then navigates by TAPPING a trigger +and proving the jump — so tests stay isolated (hard requirement) while the reach +itself is a genuine tap-driven surface jump, never a relaunch shortcut. + +Collision notes discovered live and encoded below: + * Kanji menu button "KANJI SELECTION" is a case-insensitive SUBSTRING of the + ClassSelection title "Kanji selection", so it can never be the source-vanished + token when navigating INTO Kanji selection. We use the kanji-menu-only buttons + "CUSTOM TEST" / "KANJI DRAWING" as the source tokens instead. + * ClassSelectionActivity and ItemSelectionActivity BOTH carry the title + "Kanji selection". So class-sel -> item-sel uses a kanji GLYPH ("一") as the + appeared token and a sibling class row ("JLPT level 4") as the vanished token. + * ItemSelection -> KanjiDisplay uses the item-sel title "Kanji selection" as the + vanished token ("一" is present on BOTH surfaces, so it cannot be the source). +""" +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403 + + +# ── local element helpers ───────────────────────────────────────────────────── +def menu_button(nodes, token): + """A main/sub-menu Button whose UPPERCASED text contains `token`. Compose + uppercases labels and the main-menu buttons carry both scripts + ("ひらがな\\nHIRAGANA"), so a contains-match on the ASCII token is robust.""" + t = token.upper() + return next((n for n in nodes if n.get("class", "").endswith("Button") + and t in n.get("text", "").upper()), None) + + +def _fresh_main(): + """Own entry point: relaunch to a clean main menu, return its tree (or None).""" + restart_app() + return ui() if wait_for_foreground() else None + + +# ── the depth family (the and_reach_* NAME is what the depth audit keys off; the +# body is ours). Each opens its own entry point, taps a trigger, and PROVES the +# jump, leaving the destination surface open. Returns True only on a proven jump. +def and_reach_hiragana(): + n = _fresh_main() + if n is None: + return False + b = menu_button(n, "HIRAGANA") + return b is not None and and_reach_surface(b, "Hiragana", "SETTINGS") + + +def and_reach_katakana(): + n = _fresh_main() + if n is None: + return False + b = menu_button(n, "KATAKANA") + return b is not None and and_reach_surface(b, "Katakana", "SETTINGS") + + +def and_reach_vocabulary(): + n = _fresh_main() + if n is None: + return False + b = menu_button(n, "VOCABULARY") + return b is not None and and_reach_surface(b, "Vocabulary", "SETTINGS") + + +def and_reach_progress(): + n = _fresh_main() + if n is None: + return False + b = menu_button(n, "PROGRESS") + # StatsActivity heading 'Questions answered' is dump-readable. + return b is not None and and_reach_surface(b, "Questions answered", "SETTINGS") + + +def and_reach_settings(): + n = _fresh_main() + if n is None: + return False + b = menu_button(n, "SETTINGS") + # 'Enable dark theme' preference is dump-readable; source main-only 'PROGRESS'. + return b is not None and and_reach_surface(b, "Enable dark theme", "PROGRESS") + + +def and_reach_kanji_menu_from_main(nodes): + """Main -> KanjiMenuActivity. Source 'SETTINGS' (a main-only button).""" + b = menu_button(nodes, "KANJI") + return b is not None and and_reach_surface(b, "Kanji", "SETTINGS") + + +def and_reach_kanji_menu(): + n = _fresh_main() + return n is not None and and_reach_kanji_menu_from_main(n) + + +def and_reach_kanji_selection_from_menu(nodes): + """KanjiMenu -> ClassSelectionActivity. Collision-safe source 'CUSTOM TEST'.""" + b = menu_button(nodes, "KANJI SELECTION") + return b is not None and and_reach_surface(b, "Kanji selection", "CUSTOM TEST") + + +def and_reach_kanji_selection(): + """Main -> Kanji -> Kanji selection (depth 2).""" + n = _fresh_main() + if n is None or not and_reach_kanji_menu_from_main(n): + return False + return and_reach_kanji_selection_from_menu(ui()) + + +def and_reach_item_selection_from_class(nodes): + """ClassSelection -> ItemSelectionActivity via 'JLPT level 5'. Appeared token + is the kanji glyph '一'; vanished token is the sibling row 'JLPT level 4' + (both surfaces share the title 'Kanji selection').""" + row = find_node_ci(nodes, "JLPT level 5") + return row is not None and and_reach_surface(row, "一", "JLPT level 4") + + +def and_reach_item_selection(): + """Main -> Kanji -> Kanji selection -> JLPT level 5 (depth 3).""" + n = _fresh_main() + if n is None or not and_reach_kanji_menu_from_main(n): + return False + if not and_reach_kanji_selection_from_menu(ui()): + return False + return and_reach_item_selection_from_class(ui()) + + +def and_reach_kanji_detail_from_item(nodes): + """ItemSelection -> KanjiDisplayActivity by tapping a kanji row body. Appeared + token \"On'yomi:\"; vanished token 'Kanji selection' (the item-sel title; the + glyph '一' is on BOTH surfaces so cannot be the source).""" + glyph = find_node_ci(nodes, "一") + return glyph is not None and and_reach_surface(glyph, "On'yomi:", "Kanji selection") + + +def and_reach_kanji_detail(): + """Main -> Kanji -> Kanji selection -> JLPT5 -> kanji row -> KanjiDisplay + (depth 4, the suite's deepest reach), leaving the detail surface open.""" + n = _fresh_main() + if n is None or not and_reach_kanji_menu_from_main(n): + return False + if not and_reach_kanji_selection_from_menu(ui()): + return False + if not and_reach_item_selection_from_class(ui()): + return False + return and_reach_kanji_detail_from_item(ui()) + + +def and_reach_hiragana_selection(): + """Main -> Hiragana -> HIRAGANA SELECTION (ItemSelectionActivity, depth 2). + Appeared token is the kana 'あ'; vanished token is the menu-only + 'HIRAGANA DRAWING' button.""" + n = _fresh_main() + if n is None: + return False + hira = menu_button(n, "HIRAGANA") + if hira is None or not and_reach_surface(hira, "Hiragana", "SETTINGS"): + return False + sel = menu_button(ui(), "HIRAGANA SELECTION") + return sel is not None and and_reach_surface(sel, "あ", "HIRAGANA DRAWING") + + +def and_reach_hiragana_quiz(): + """Main -> Hiragana -> HIRAGANA TO ROMAJI QUIZ (TestActivity, depth 2). Appeared + token 'Session score'; vanished token the menu-only 'HIRAGANA SELECTION'.""" + n = _fresh_main() + if n is None: + return False + hira = menu_button(n, "HIRAGANA") + if hira is None or not and_reach_surface(hira, "Hiragana", "SETTINGS"): + return False + q = menu_button(ui(), "HIRAGANA TO ROMAJI QUIZ") + return q is not None and and_reach_surface(q, "Session score", "HIRAGANA SELECTION") + + +def and_reach_terminate_dialog(): + """Depth 3: reach the quiz, then BACK to raise the 'Terminate session' dialog. + Leaves the dialog OPEN (caller decides how to dismiss).""" + if not and_reach_hiragana_quiz(): + return False + before = and_showing() + back() # BACK inside the quiz raises the dialog + and_enter("Terminate session") + after = and_showing() + return and_reach(before, after, "Terminate session", "Session score") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Top-level destinations (depth 1) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_hiragana",)) +def test_reach_hiragana(): + ok = and_reach_hiragana() + record("nav_reach_hiragana", ok, + "" if ok else "feature_missing: Hiragana menu not reachable from main", + depth=1, jump_kind="reach", + expect="HiraganaMenu shown (title 'Hiragana'); main 'SETTINGS' button gone") + + +@and_test(expects=("nav_reach_katakana",)) +def test_reach_katakana(): + ok = and_reach_katakana() + record("nav_reach_katakana", ok, + "" if ok else "feature_missing: Katakana menu not reachable from main", + depth=1, jump_kind="reach", + expect="KatakanaMenu shown (title 'Katakana'); main 'SETTINGS' button gone") + + +@and_test(expects=("nav_reach_vocabulary",)) +def test_reach_vocabulary(): + ok = and_reach_vocabulary() + record("nav_reach_vocabulary", ok, + "" if ok else "feature_missing: Vocabulary menu not reachable from main", + depth=1, jump_kind="reach", + expect="VocabularyMenu shown (title 'Vocabulary'); main 'SETTINGS' button gone") + + +@and_test(expects=("nav_reach_progress",)) +def test_reach_progress(): + ok = and_reach_progress() + record("nav_reach_progress", ok, + "" if ok else "feature_missing: Progress/Stats not reachable from main", + depth=1, jump_kind="reach", + expect="StatsActivity shown ('Questions answered' heading); main 'SETTINGS' gone") + + +@and_test(expects=("nav_reach_settings",)) +def test_reach_settings(): + ok = and_reach_settings() + record("nav_reach_settings", ok, + "" if ok else "feature_missing: Settings not reachable from main", + depth=1, jump_kind="reach", + expect="Settings shown ('Enable dark theme' preference); main 'PROGRESS' gone") + + +@and_test(expects=("nav_reach_kanji_menu",)) +def test_reach_kanji_menu(): + ok = and_reach_kanji_menu() + record("nav_reach_kanji_menu", ok, + "" if ok else "feature_missing: Kanji menu not reachable from main", + depth=1, jump_kind="reach", + expect="KanjiMenu shown (title 'Kanji'); main 'SETTINGS' button gone") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Depth 2 chains +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_kanji_selection",)) +def test_reach_kanji_selection(): + """Main -> Kanji -> Kanji selection (depth 2). Guards the substring collision: + the source token is the kanji-menu-only 'CUSTOM TEST', never 'KANJI SELECTION'.""" + ok = and_reach_kanji_selection() + record("nav_reach_kanji_selection", ok, + "" if ok else "feature_missing: ClassSelection not reachable via Kanji menu", + depth=2, jump_kind="reach", + expect="ClassSelection shown ('Kanji selection' title + class rows); " + "Kanji-menu-only 'CUSTOM TEST' button gone") + + +@and_test(expects=("nav_reach_quiz", "nav_reach_quiz_vlm")) +def test_reach_quiz(): + """Main -> Hiragana -> start the romaji quiz (TestActivity, depth 2).""" + ok = and_reach_hiragana_quiz() + record("nav_reach_quiz", ok, + "" if ok else "feature_missing: quiz (TestActivity) not startable from Hiragana menu", + depth=2, jump_kind="reach", + expect="TestActivity shown ('Session score: 0/0'); menu 'HIRAGANA SELECTION' gone") + # VLM: the quiz toolbar renders a back affordance at the top-left. + vlm_assert("nav_reach_quiz", + "Is there a left-pointing back arrow icon at the very top-left " + "corner of this screen, to the left of the title text?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("nav_reach_hiragana_selection",)) +def test_reach_hiragana_selection(): + """Main -> Hiragana -> HIRAGANA SELECTION (ItemSelectionActivity, depth 2).""" + ok = and_reach_hiragana_selection() + record("nav_reach_hiragana_selection", ok, + "" if ok else "feature_missing: hiragana ItemSelection not reachable", + depth=2, jump_kind="reach", + expect="ItemSelection (hiragana) shown (kana 'あ' row); menu 'HIRAGANA DRAWING' gone") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Depth 3+ chains +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_item_selection",)) +def test_reach_item_selection(): + """Main -> Kanji -> Kanji selection -> JLPT level 5 (ItemSelection, depth 3).""" + ok = and_reach_item_selection() + record("nav_reach_item_selection", ok, + "" if ok else "feature_missing: ItemSelection not reachable via JLPT level 5", + depth=3, jump_kind="reach", + expect="ItemSelection (kanji) shown (glyph '一' + checkboxes); " + "class row 'JLPT level 4' gone") + + +@and_test(expects=("nav_reach_terminate_dialog",)) +def test_reach_terminate_dialog(): + """Main -> Hiragana -> quiz -> BACK -> Terminate session dialog (depth 3). + The dialog is a real surface; CANCEL is used afterwards to stay safe.""" + dialog_ok = and_reach_terminate_dialog() + if dialog_ok: + # stay safe: dismiss with CANCEL, never terminate anything destructive. + cancel = find_node_ci(ui(), "CANCEL") + if cancel: + safe_tap(cancel) + record("nav_reach_terminate_dialog", dialog_ok, + "" if dialog_ok else "behavior_wrong: BACK in quiz did not raise the " + "'Terminate session' dialog", + depth=3, jump_kind="reach", + expect="'Terminate session' AlertDialog shown; quiz 'Session score' hidden behind it") + + +@and_test(expects=("nav_reach_kanji_detail", "nav_reach_kanji_detail_vlm")) +def test_reach_kanji_detail(): + """Main -> Kanji -> Kanji selection -> JLPT5 -> kanji row -> KanjiDisplay + (depth 4, the suite's deepest reach).""" + ok = and_reach_kanji_detail() + record("nav_reach_kanji_detail", ok, + "" if ok else "feature_missing: KanjiDisplay not reachable via the kanji row", + depth=4, jump_kind="reach", + expect="KanjiDisplay shown (\"On'yomi:\" section); ItemSelection title " + "'Kanji selection' gone") + # VLM: KanjiDisplay renders a two-tab header ('Kanji' | 'Words'); the reach + # end-state is visually distinctive. + vlm_assert("nav_reach_kanji_detail", + "Near the top of this screen, are there two side-by-side tab labels " + "reading 'Kanji' (left) and 'Words' (right)?", + RESULTS_DIR, tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Back-stack integrity +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_backstack_submenu_to_main",)) +def test_backstack_submenu_to_main(): + """Depth 1 then BACK: Kanji menu -> BACK -> main. 'Kakugo' reappears and the + kanji-menu-only 'CUSTOM TEST' button is gone.""" + down = and_reach_kanji_menu() + up = False + if down: + before = and_showing() + home_depth = and_back() # pop the Kanji menu + after = and_showing() + up = (home_depth == 0 + and and_reach(before, after, "Kakugo", "CUSTOM TEST")) + record("nav_backstack_submenu_to_main", down and up, + "" if down and up else "behavior_wrong: BACK from Kanji menu did not restore the main menu", + depth=1, jump_kind="reach", + expect="Main menu restored ('Kakugo' title back); Kanji-menu 'CUSTOM TEST' gone") + + +@and_test(expects=("nav_backstack_detail_to_itemsel",)) +def test_backstack_detail_to_itemsel(): + """Depth 4 then one BACK: KanjiDisplay -> BACK -> ItemSelection. The item-sel + title 'Kanji selection' reappears and \"On'yomi:\" is gone.""" + deep = and_reach_kanji_detail() + back_ok = False + if deep: + before = and_showing() + and_back() # pop KanjiDisplay + after = and_showing() + back_ok = and_reach(before, after, "Kanji selection", "On'yomi:") + record("nav_backstack_detail_to_itemsel", deep and back_ok, + "" if deep and back_ok else "behavior_wrong: one BACK from KanjiDisplay " + "did not return to ItemSelection", + depth=4, jump_kind="reach", + expect="ItemSelection restored (title 'Kanji selection'); detail \"On'yomi:\" gone") + + +@and_test(expects=("nav_backstack_deep_unwind",)) +def test_backstack_deep_unwind(): + """The deepest back stack: descend 4 surfaces, then BACK four times, asserting + the expected surface after EACH pop, all the way home to the main menu.""" + deep = and_reach_kanji_detail() # main->Kanji->Ksel->JLPT5->detail + pops_ok = False + if deep: + # pop 1: detail -> item-sel ('一' present again, "On'yomi:" gone) + b = and_showing(); and_back(); a = and_showing() + p1 = any(k == "TextView|一" for k in a) and not any("on'yomi" in k.lower() for k in a) + # pop 2: item-sel -> class-sel ('JLPT level 4' row back) + b = and_showing(); and_back(); a = and_showing() + p2 = and_reach(b, a, "JLPT level 4", None) + # pop 3: class-sel -> Kanji menu ('CUSTOM TEST' back, 'JLPT level 5' gone) + b = and_showing(); and_back(); a = and_showing() + p3 = and_reach(b, a, "CUSTOM TEST", "JLPT level 5") + # pop 4: Kanji menu -> main ('Kakugo' back, 'CUSTOM TEST' gone) + b = and_showing(); depth = and_back(); a = and_showing() + p4 = depth == 0 and and_reach(b, a, "Kakugo", "CUSTOM TEST") + pops_ok = p1 and p2 and p3 and p4 + record("nav_backstack_deep_unwind", deep and pops_ok, + "" if deep and pops_ok else "behavior_wrong: the 4-hop back stack did not " + "unwind surface-by-surface to the main menu", + depth=4, jump_kind="reach", + expect="Four BACKs pop detail->item-sel->class-sel->Kanji menu->main, " + "each surface's token restored in turn") + + +@and_test(expects=("nav_backstack_quiz_cancel_stays",)) +def test_backstack_quiz_cancel_stays(): + """CANCEL on the Terminate dialog keeps you on the quiz surface (does NOT pop + it). Reach the dialog (depth 3), CANCEL, assert the quiz remains.""" + dialog_ok = and_reach_terminate_dialog() + stays = False + if dialog_ok: + before = and_showing() + cancel = find_node_ci(ui(), "CANCEL") + if cancel and safe_tap(cancel): + after = and_showing() + # dialog dismissed AND the quiz's Session score is showing again, + # while the dialog title is gone. + stays = (and_reach(before, after, "Session score", "Terminate session")) + record("nav_backstack_quiz_cancel_stays", stays, + "" if stays else "behavior_wrong: CANCEL on the terminate dialog did not " + "keep the quiz surface open", + depth=3, jump_kind="reach", + expect="After CANCEL: quiz 'Session score' visible again; " + "'Terminate session' dialog gone (quiz NOT popped)") + + +TESTS = [ + test_reach_hiragana, + test_reach_katakana, + test_reach_vocabulary, + test_reach_progress, + test_reach_settings, + test_reach_kanji_menu, + test_reach_kanji_selection, + test_reach_quiz, + test_reach_hiragana_selection, + test_reach_item_selection, + test_reach_terminate_dialog, + test_reach_kanji_detail, + test_backstack_submenu_to_main, + test_backstack_detail_to_itemsel, + test_backstack_deep_unwind, + test_backstack_quiz_cancel_stays, +] + +if __name__ == "__main__": + run_suite(TESTS, "navigation") diff --git a/android/blastrock-kakugo/tests/test_android_states.py b/android/blastrock-kakugo/tests/test_android_states.py new file mode 100644 index 0000000000000000000000000000000000000000..df21398e1f655fa2b855aba854dbab098ae19b86 --- /dev/null +++ b/android/blastrock-kakugo/tests/test_android_states.py @@ -0,0 +1,974 @@ +#!/usr/bin/env python3 +"""STATES lane for org.kaqui (Kakugo). + +Owner of checked / selected / enabled / focused transitions PAIRED with their +app-authored consequence, page-level state machines, conditional enable/disable, +and SETTINGS / mode persistence across process death. + +Every test opens its own entry via restart_app(); every toggled setting or +checkbox is RESTORED in a finally so later tests / quiz-starts (which need >=10 +enabled items) are never poisoned. All coordinates come from node _center; the +package is the module-level PACKAGE (argv[1]) — never a literal. + +Run: python3 test_android_states.py org.kaqui /workspace/testgen/eval/eval_results +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +require_kit(1) + +# ── Local navigation helpers (no kit re-implementation) ────────────────────── +# Main-menu buttons carry BOTH scripts, e.g. "ひらがな\nHIRAGANA", so match by the +# ASCII substring case-insensitively. Compose uppercases button labels. + +def tap_main(nodes, sub): + """Tap a main-menu / any Button whose label CONTAINS `sub` (case-insensitive).""" + for n in nodes: + if "Button" in n.get("class", "") and sub.lower() in n.get("text", "").lower(): + return tap_node(n) + return False + + +def tap_contains(nodes, sub): + """Tap the first node whose text CONTAINS `sub` (case-insensitive).""" + s = sub.lower() + for n in nodes: + if s in n.get("text", "").lower(): + return tap_node(n) + return False + + +def switch_for_label(nodes, label): + """The android.widget.Switch on the same preference row as the title TextView + `label`. The Switch node itself has empty text, so we anchor on the sibling + title's y and pick the nearest Switch. Returns None if not on screen.""" + titles = [n for n in nodes + if n.get("resource-id", "").endswith("title") + and n.get("text", "").strip().lower() == label.lower()] + if not titles: + return None + ty = titles[0].get("_center", (0, 0))[1] + best, best_dy = None, 10 ** 9 + for sw in find_by_class(nodes, "Switch"): + dy = abs(sw.get("_center", (0, 0))[1] - ty) + if dy < best_dy: + best, best_dy = sw, dy + return best if best_dy < 120 else None + + +def tab_container(nodes, tab_text): + """The clickable tab View (KanjiDisplay 'Kanji'/'Words') that CONTAINS the tab + TextView's centre. That parent View carries the `selected` attribute; the + TextView itself does not.""" + tv = None + for n in nodes: + if (n.get("text", "").strip() == tab_text + and n.get("class", "").endswith("TextView")): + tv = n + break + if not tv or "_center" not in tv: + return None + cx, cy = tv["_center"] + best, best_area = None, 10 ** 18 + for n in nodes: + if n.get("class", "") == "android.view.View" and "_bounds" in n: + x1, y1, x2, y2 = n["_bounds"] + if x1 <= cx <= x2 and y1 <= cy <= y2: + w, h = x2 - x1, y2 - y1 + area = w * h + if w > 100 and h < 300 and area < best_area: + best, best_area = n, area + return best + + +def open_settings(): + """restart_app -> main -> SETTINGS. Returns (ok, nodes). Counts one surface.""" + restart_app() + wait_for_foreground() + if not tap_main(ui(), "SETTINGS"): + return False, [] + and_enter("settings") # backs depth>=1 + nodes = ui() + if "MainSettingsActivity" not in get_current_activity(): + return False, nodes + return True, nodes + + +def and_reach_settings_switch(label): + """Open Settings and return (ok, switch_node, nodes) for preference `label`, + scrolling it into view if it is below the fold. Counts one surface (Settings).""" + ok, nodes = open_settings() + if not ok: + return False, None, nodes + sw = switch_for_label(nodes, label) + for _ in range(3): + if sw is not None: + return True, sw, nodes + scroll_down(0.4) + nodes = ui() + sw = switch_for_label(nodes, label) + return (sw is not None), sw, nodes + + +def and_reach_hiragana_quiz(variant="HIRAGANA TO ROMAJI QUIZ"): + """restart_app -> main -> HIRAGANA menu -> a quiz. Counts two surfaces. + Returns (ok, nodes).""" + restart_app() + wait_for_foreground() + if not tap_main(ui(), "HIRAGANA"): + return False, [] + and_enter("hiragana_menu") + if not tap_contains(ui(), variant): + return False, ui() + and_enter("quiz") + nodes = ui() + return ("TestActivity" in get_current_activity()), nodes + + +def and_reach_jlpt5(): + """restart_app -> KANJI -> KANJI SELECTION -> JLPT level 5 (ItemSelection). + Counts three surfaces. Returns (ok, nodes).""" + restart_app() + wait_for_foreground() + if not tap_main(ui(), "KANJI"): + return False, [] + and_enter("kanji_menu") + if not tap_contains(ui(), "KANJI SELECTION"): + return False, ui() + and_enter("class_selection") + if not tap_contains(ui(), "JLPT level 5"): + return False, ui() + and_enter("item_selection") + nodes = ui() + return ("ItemSelectionActivity" in get_current_activity()), nodes + + +def and_reach_kanji_display(): + """... JLPT5 -> tap a kanji ROW -> KanjiDisplayActivity (Kanji/Words tabs). + Counts four surfaces. Returns (ok, nodes).""" + ok, nodes = and_reach_jlpt5() + if not ok: + return False, nodes + glyphs = [n for n in nodes + if len(n.get("text", "")) == 1 and n.get("class", "").endswith("TextView")] + if not glyphs: + return False, nodes + tap_node(glyphs[0]) + and_enter("kanji_display") + nodes = ui() + return ("KanjiDisplayActivity" in get_current_activity()), nodes + + +# Basic gojūon + dakuten/handakuten romaji, for locating the question kana in a quiz. +KANA2ROMAJI = { + 'あ': 'a', 'い': 'i', 'う': 'u', 'え': 'e', 'お': 'o', + 'か': 'ka', 'き': 'ki', 'く': 'ku', 'け': 'ke', 'こ': 'ko', + 'さ': 'sa', 'し': 'shi', 'す': 'su', 'せ': 'se', 'そ': 'so', + 'た': 'ta', 'ち': 'chi', 'つ': 'tsu', 'て': 'te', 'と': 'to', + 'な': 'na', 'に': 'ni', 'ぬ': 'nu', 'ね': 'ne', 'の': 'no', + 'は': 'ha', 'ひ': 'hi', 'ふ': 'fu', 'へ': 'he', 'ほ': 'ho', + 'ま': 'ma', 'み': 'mi', 'む': 'mu', 'め': 'me', 'も': 'mo', + 'や': 'ya', 'ゆ': 'yu', 'よ': 'yo', + 'ら': 'ra', 'り': 'ri', 'る': 'ru', 'れ': 're', 'ろ': 'ro', + 'わ': 'wa', 'を': 'wo', 'ん': 'n', + 'が': 'ga', 'ぎ': 'gi', 'ぐ': 'gu', 'げ': 'ge', 'ご': 'go', + 'ざ': 'za', 'じ': 'ji', 'ず': 'zu', 'ぜ': 'ze', 'ぞ': 'zo', + 'だ': 'da', 'ぢ': 'ji', 'づ': 'zu', 'で': 'de', 'ど': 'do', + 'ば': 'ba', 'び': 'bi', 'ぶ': 'bu', 'べ': 'be', 'ぼ': 'bo', + 'ぱ': 'pa', 'ぴ': 'pi', 'ぷ': 'pu', 'ぺ': 'pe', 'ぽ': 'po', +} + + +def enabled_answer_cells(nodes): + """The clickable answer cells (SURE/MAYBE Views) that are ENABLED — used to + detect the 'answered' state where they all disable after a wrong answer. + + An answer cell is a clickable View that (a) wraps a 'SURE' or 'MAYBE' TextView + child and (b) is NOT the full-width NEXT/DON'T KNOW button (that button stays + enabled after answering, so a width filter excludes it).""" + labels = [n for n in nodes + if n.get("text", "") in ("SURE", "MAYBE") and "_center" in n] + out = [] + for n in nodes: + if (n.get("class", "") != "android.view.View" + or n.get("clickable") != "true" or "_bounds" not in n): + continue + x1, y1, x2, y2 = n["_bounds"] + if (x2 - x1) >= 700: # exclude the full-width button + continue + for lb in labels: # must wrap a SURE/MAYBE label + lx, ly = lb["_center"] + if x1 <= lx <= x2 and y1 <= ly <= y2: + if n.get("enabled") == "true": + out.append(n) + break + return out + + +# ══════════════════════════════════════════════════════════════════════════════ +# SETTINGS — checked transitions + persistence (this lane owns persistence) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_dark_theme_toggle",)) +def test_dark_theme_toggle(): + """Enable dark theme Switch: false -> true (in-Settings flip).""" + ok, sw, _ = and_reach_settings_switch("Enable dark theme") + if not ok or sw is None: + record("states_dark_theme_toggle", False, + "feature_missing: no 'Enable dark theme' Switch in Settings", + depth=1, jump_kind="transition", + expect="dark theme Switch false->true") + return + before = sw.get("checked") + try: + tap_node(sw) + after = (find_closest_match(ui(), sw) or {}).get("checked") + okk = before == "false" and after == "true" + record("states_dark_theme_toggle", okk, + "" if okk else f"behavior_wrong: dark Switch {before}->{after}, " + f"expected false->true", + depth=1, jump_kind="transition", + expect="dark theme Switch false->true") + finally: + cur = switch_for_label(ui(), "Enable dark theme") + if cur is not None and cur.get("checked") == "true": + tap_node(cur) # restore OFF + + +@and_test(expects=("states_dark_theme_persist_reopen",)) +def test_dark_theme_persist_reopen(): + """Flip dark theme ON, leave Settings to the main menu, reopen Settings -> + still ON (value = the specific persisted state).""" + ok, sw, _ = and_reach_settings_switch("Enable dark theme") + if not ok or sw is None: + record("states_dark_theme_persist_reopen", False, + "feature_missing: no 'Enable dark theme' Switch", + depth=1, jump_kind="value", expect="dark theme still ON after reopen") + return + try: + if sw.get("checked") == "false": + tap_node(sw) + back() # Settings -> main menu + settle("tap") + on_main = "MainActivity" in get_current_activity() + tap_main(ui(), "SETTINGS") + settle("tap") + again = switch_for_label(ui(), "Enable dark theme") + okk = on_main and again is not None and again.get("checked") == "true" + record("states_dark_theme_persist_reopen", okk, + "" if okk else "behavior_wrong: dark theme did not stay ON after " + "leaving+reopening Settings", + depth=1, jump_kind="value", expect="dark theme still ON after reopen") + finally: + cur = switch_for_label(ui(), "Enable dark theme") + if cur is not None and cur.get("checked") == "true": + tap_node(cur) + + +@and_test(expects=("states_dark_theme_persist_processdeath",)) +def test_dark_theme_persist_processdeath(): + """The killer for a stateless recreation: flip dark theme ON, force-stop + + relaunch, reopen Settings -> still ON.""" + ok, sw, _ = and_reach_settings_switch("Enable dark theme") + if not ok or sw is None: + record("states_dark_theme_persist_processdeath", False, + "feature_missing: no 'Enable dark theme' Switch", + depth=1, jump_kind="value", + expect="dark theme still ON after force-stop+relaunch") + return + try: + if sw.get("checked") == "false": + tap_node(sw) + force_stop_and_relaunch() + wait_for_foreground() + tap_main(ui(), "SETTINGS") + settle("tap") + again = switch_for_label(ui(), "Enable dark theme") + okk = again is not None and again.get("checked") == "true" + record("states_dark_theme_persist_processdeath", okk, + "" if okk else "behavior_wrong: dark theme not persisted across " + "process death (recreation likely stateless)", + depth=1, jump_kind="value", + expect="dark theme still ON after force-stop+relaunch") + finally: + # relaunch clean and turn it back OFF through the GUI + restart_app() + wait_for_foreground() + tap_main(ui(), "SETTINGS") + settle("tap") + cur = switch_for_label(ui(), "Enable dark theme") + if cur is not None and cur.get("checked") == "true": + tap_node(cur) + + +@and_test(expects=("states_dark_theme_applied_vlm",)) +def test_dark_theme_applied_vlm(): + """After turning dark theme ON and relaunching, the main menu repaints dark: + near-black background with light text (canvas-independent color property).""" + ok, sw, _ = and_reach_settings_switch("Enable dark theme") + if not ok or sw is None: + vlm_assert("states_dark_theme_applied", "Is the app background dark " + "(near-black) with light-colored text?", RESULTS_DIR, + depth=1, jump_kind="value", tag="color") # will fail: no control + return + try: + if sw.get("checked") == "false": + tap_node(sw) + force_stop_and_relaunch() + wait_for_foreground() + settle("launch") + vlm_assert("states_dark_theme_applied", + "Is the background of this screen dark (near-black or very dark) " + "with light-colored (white) text and dark button cards?", + RESULTS_DIR, depth=1, jump_kind="value", tag="color") + finally: + restart_app() + wait_for_foreground() + tap_main(ui(), "SETTINGS") + settle("tap") + cur = switch_for_label(ui(), "Enable dark theme") + if cur is not None and cur.get("checked") == "true": + tap_node(cur) + + +@and_test(expects=("states_single_button_toggle",)) +def test_single_button_toggle(): + """Single button mode Switch: false -> true, and persists across reopen.""" + ok, sw, _ = and_reach_settings_switch("Single button mode") + if not ok or sw is None: + record("states_single_button_toggle", False, + "feature_missing: no 'Single button mode' Switch", + depth=1, jump_kind="transition", + expect="single button mode false->true; persists on reopen") + return + try: + before = sw.get("checked") + tap_node(sw) + after = (find_closest_match(ui(), sw) or {}).get("checked") + back() # leave + reopen to prove persist + settle("tap") + tap_main(ui(), "SETTINGS") + settle("tap") + again = switch_for_label(ui(), "Single button mode") + persisted = again is not None and again.get("checked") == "true" + okk = before == "false" and after == "true" and persisted + record("states_single_button_toggle", okk, + "" if okk else f"behavior_wrong: single-button {before}->{after}, " + f"persisted={persisted}", + depth=1, jump_kind="transition", + expect="single button mode false->true; persists on reopen") + finally: + cur = switch_for_label(ui(), "Single button mode") + if cur is not None and cur.get("checked") == "true": + tap_node(cur) + + +@and_test(expects=("states_single_button_consequence",)) +def test_single_button_consequence(): + """Single button mode ON changes quiz behavior: the two-button (SURE/MAYBE) + cells collapse to a single tappable answer, so no SURE/MAYBE appears. + (Hide answers is also turned OFF so the grid is visible immediately.)""" + # enable single button mode + reveal grid + ok, sw, _ = and_reach_settings_switch("Single button mode") + if not ok or sw is None: + record("states_single_button_consequence", False, + "feature_missing: no 'Single button mode' Switch", + depth=2, jump_kind="value", + expect="single mode ON -> quiz has no SURE/MAYBE buttons") + return + restored = {"single": False, "hide": False} + try: + if sw.get("checked") == "false": + tap_node(sw) + swh = switch_for_label(ui(), "Hide answers") + if swh is not None and swh.get("checked") == "true": + tap_node(swh) + # start a hiragana grid quiz + back() + settle("tap") + tap_main(ui(), "HIRAGANA") + and_enter("hiragana_menu") + tap_contains(ui(), "HIRAGANA TO ROMAJI QUIZ") + and_enter("quiz") + nodes = ui() + in_quiz = "TestActivity" in get_current_activity() + has_sure = find_node_ci(nodes, "SURE") is not None + has_maybe = find_node_ci(nodes, "MAYBE") is not None + okk = in_quiz and not has_sure and not has_maybe + record("states_single_button_consequence", okk, + "" if okk else f"behavior_wrong: single mode quiz still shows " + f"SURE={has_sure}/MAYBE={has_maybe}", + depth=2, jump_kind="value", + expect="single mode ON -> quiz has no SURE/MAYBE buttons") + finally: + restart_app() + wait_for_foreground() + tap_main(ui(), "SETTINGS") + settle("tap") + cur = switch_for_label(ui(), "Single button mode") + if cur is not None and cur.get("checked") == "true": + tap_node(cur) + curh = switch_for_label(ui(), "Hide answers") + if curh is not None and curh.get("checked") == "false": + tap_node(curh) + + +@and_test(expects=("states_keep_screen_on_toggle",)) +def test_keep_screen_on_toggle(): + """Keep screen on Switch: false -> true, and persists across reopen.""" + ok, sw, _ = and_reach_settings_switch("Keep screen on") + if not ok or sw is None: + record("states_keep_screen_on_toggle", False, + "feature_missing: no 'Keep screen on' Switch", + depth=1, jump_kind="transition", + expect="keep screen on false->true; persists on reopen") + return + try: + before = sw.get("checked") + tap_node(sw) + after = (find_closest_match(ui(), sw) or {}).get("checked") + back() + settle("tap") + tap_main(ui(), "SETTINGS") + settle("tap") + again = switch_for_label(ui(), "Keep screen on") + persisted = again is not None and again.get("checked") == "true" + okk = before == "false" and after == "true" and persisted + record("states_keep_screen_on_toggle", okk, + "" if okk else f"behavior_wrong: keep-screen-on {before}->{after}, " + f"persisted={persisted}", + depth=1, jump_kind="transition", + expect="keep screen on false->true; persists on reopen") + finally: + cur = switch_for_label(ui(), "Keep screen on") + if cur is not None and cur.get("checked") == "true": + tap_node(cur) + + +@and_test(expects=("states_custom_font_toggle",)) +def test_custom_font_toggle(): + """Use a custom font Switch: false -> true, with the app-authored consequence + that the previously-disabled 'Pick a custom Japanese font' row becomes enabled.""" + ok, sw, nodes = and_reach_settings_switch("Use a custom font") + if not ok or sw is None: + record("states_custom_font_toggle", False, + "feature_missing: no 'Use a custom font' Switch", + depth=1, jump_kind="transition", + expect="custom font false->true; 'Pick a custom font' row enabled") + return + try: + before = sw.get("checked") + pick_before = find_node(nodes, text="Pick a custom Japanese font") + pick_en_before = pick_before.get("enabled") if pick_before else None + tap_node(sw) + fresh = ui() + after = (find_closest_match(fresh, sw) or {}).get("checked") + pick_after = find_node(fresh, text="Pick a custom Japanese font") + pick_en_after = pick_after.get("enabled") if pick_after else None + okk = (before == "false" and after == "true" + and pick_en_before == "false" and pick_en_after == "true") + record("states_custom_font_toggle", okk, + "" if okk else f"behavior_wrong: font {before}->{after}, " + f"pick-row enabled {pick_en_before}->{pick_en_after}", + depth=1, jump_kind="transition", + expect="custom font false->true; 'Pick a custom font' row enabled") + finally: + cur = switch_for_label(ui(), "Use a custom font") + if cur is not None and cur.get("checked") == "true": + tap_node(cur) + + +@and_test(expects=("states_hide_answers_toggle",)) +def test_hide_answers_toggle(): + """Hide answers Switch is default ON: tap -> OFF (transition), restore ON.""" + ok, sw, _ = and_reach_settings_switch("Hide answers") + if not ok or sw is None: + record("states_hide_answers_toggle", False, + "feature_missing: no 'Hide answers' Switch", + depth=1, jump_kind="transition", + expect="hide answers Switch true->false") + return + try: + before = sw.get("checked") + tap_node(sw) + after = (find_closest_match(ui(), sw) or {}).get("checked") + okk = before == "true" and after == "false" + record("states_hide_answers_toggle", okk, + "" if okk else f"behavior_wrong: hide-answers {before}->{after}, " + f"expected true->false", + depth=1, jump_kind="transition", + expect="hide answers Switch true->false") + finally: + cur = switch_for_label(ui(), "Hide answers") + if cur is not None and cur.get("checked") == "false": + tap_node(cur) # restore ON (default) + + +# ══════════════════════════════════════════════════════════════════════════════ +# Page-level state machine: settings state -> cross-screen quiz consequence +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_hide_answers_off_consequence",)) +def test_hide_answers_off_consequence(): + """Hide answers OFF -> the quiz answer grid (SURE buttons) is shown IMMEDIATELY + with NO 'SHOW ANSWERS' gate. Settings-state -> cross-screen page behaviour.""" + ok, sw, _ = and_reach_settings_switch("Hide answers") + if not ok or sw is None: + record("states_hide_answers_off_consequence", False, + "feature_missing: no 'Hide answers' Switch", + depth=2, jump_kind="value", + expect="hide OFF -> quiz shows SURE grid, no SHOW ANSWERS") + return + try: + if sw.get("checked") == "true": + tap_node(sw) # turn OFF + back() + settle("tap") + tap_main(ui(), "HIRAGANA") + and_enter("hiragana_menu") + tap_contains(ui(), "HIRAGANA TO ROMAJI QUIZ") + and_enter("quiz") + nodes = ui() + in_quiz = "TestActivity" in get_current_activity() + has_show = find_node_ci(nodes, "SHOW ANSWERS") is not None + has_sure = find_node_ci(nodes, "SURE") is not None + okk = in_quiz and has_sure and not has_show + record("states_hide_answers_off_consequence", okk, + "" if okk else f"behavior_wrong: hide-OFF quiz SHOW ANSWERS=" + f"{has_show} SURE={has_sure} (expected grid immediately)", + depth=2, jump_kind="value", + expect="hide OFF -> quiz shows SURE grid, no SHOW ANSWERS") + finally: + restart_app() + wait_for_foreground() + tap_main(ui(), "SETTINGS") + settle("tap") + cur = switch_for_label(ui(), "Hide answers") + if cur is not None and cur.get("checked") == "false": + tap_node(cur) # restore ON + + +@and_test(expects=("states_hide_answers_on_consequence",)) +def test_hide_answers_on_consequence(): + """Hide answers ON (default) -> the quiz gates the grid behind a 'SHOW ANSWERS' + button and shows no SURE cells yet. The complement of the OFF consequence.""" + ok, nodes = and_reach_hiragana_quiz() + if not ok: + record("states_hide_answers_on_consequence", False, + "setup_failed: could not start a hiragana quiz", + depth=2, jump_kind="value", + expect="hide ON -> quiz shows SHOW ANSWERS, no SURE grid yet") + return + has_show = find_node_ci(nodes, "SHOW ANSWERS") is not None + has_sure = find_node_ci(nodes, "SURE") is not None + okk = has_show and not has_sure + record("states_hide_answers_on_consequence", okk, + "" if okk else f"behavior_wrong: hide-ON quiz SHOW ANSWERS={has_show} " + f"SURE={has_sure} (expected gated)", + depth=2, jump_kind="value", + expect="hide ON -> quiz shows SHOW ANSWERS, no SURE grid yet") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Quiz state machine (in-page transitions) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_show_answers_flip",)) +def test_show_answers_flip(): + """SHOW ANSWERS tap -> answersVisible flips: the SURE/MAYBE grid appears and + the SHOW ANSWERS button disappears (same Activity throughout).""" + ok, nodes = and_reach_hiragana_quiz() + if not ok: + record("states_show_answers_flip", False, + "setup_failed: could not start a hiragana quiz", + depth=2, jump_kind="transition", + expect="answers hidden->shown; SHOW ANSWERS gone, SURE grid present") + return + act = get_current_activity() + show_before = find_node_ci(nodes, "SHOW ANSWERS") is not None + sure_before = find_node_ci(nodes, "SURE") is not None + tap_contains(nodes, "SHOW ANSWERS") + fresh = ui() + same_act = get_current_activity() == act + show_after = find_node_ci(fresh, "SHOW ANSWERS") is not None + sure_after = find_node_ci(fresh, "SURE") is not None + okk = (same_act and show_before and not sure_before + and not show_after and sure_after) + record("states_show_answers_flip", okk, + "" if okk else f"behavior_wrong: SHOW ANSWERS {show_before}->{show_after}, " + f"SURE {sure_before}->{sure_after}", + depth=2, jump_kind="transition", + expect="answers hidden->shown; SHOW ANSWERS gone, SURE grid present") + + +@and_test(expects=("states_wrong_answer_next_flip",)) +def test_wrong_answer_next_flip(): + """After a wrong answer (DON'T KNOW counts as wrong), the 'DON'T KNOW' button + flips to 'NEXT' — the answered-state label transition.""" + ok, nodes = and_reach_hiragana_quiz() + if not ok: + record("states_wrong_answer_next_flip", False, + "setup_failed: could not start a hiragana quiz", + depth=2, jump_kind="transition", + expect="DON'T KNOW -> NEXT after answering") + return + tap_contains(nodes, "SHOW ANSWERS") + nodes = ui() + act = get_current_activity() + dk_before = find_node_ci(nodes, "DON'T KNOW") is not None + next_before = find_node_ci(nodes, "NEXT") is not None + dk = find_node_ci(nodes, "DON'T KNOW") + if dk is None: + record("states_wrong_answer_next_flip", False, + "setup_failed: DON'T KNOW button not present after SHOW ANSWERS", + depth=2, jump_kind="transition", + expect="DON'T KNOW -> NEXT after answering") + return + tap_node(dk) + fresh = ui() + same_act = get_current_activity() == act + dk_after = find_node_ci(fresh, "DON'T KNOW") is not None + next_after = find_node_ci(fresh, "NEXT") is not None + okk = (same_act and dk_before and not next_before + and not dk_after and next_after) + record("states_wrong_answer_next_flip", okk, + "" if okk else f"behavior_wrong: DON'T KNOW {dk_before}->{dk_after}, " + f"NEXT {next_before}->{next_after}", + depth=2, jump_kind="transition", + expect="DON'T KNOW -> NEXT after answering") + + +@and_test(expects=("states_wrong_answer_cells_disabled",)) +def test_wrong_answer_cells_disabled(): + """After a wrong answer the answer cells become non-interactive: the count of + ENABLED clickable answer cells drops from >0 to 0 (enabled true->false).""" + ok, nodes = and_reach_hiragana_quiz() + if not ok: + record("states_wrong_answer_cells_disabled", False, + "setup_failed: could not start a hiragana quiz", + depth=2, jump_kind="transition", + expect="answer cells enabled->disabled after answering") + return + tap_contains(nodes, "SHOW ANSWERS") + nodes = ui() + act = get_current_activity() + enabled_before = len(enabled_answer_cells(nodes)) + dk = find_node_ci(nodes, "DON'T KNOW") + if dk is None: + record("states_wrong_answer_cells_disabled", False, + "setup_failed: DON'T KNOW not present after SHOW ANSWERS", + depth=2, jump_kind="transition", + expect="answer cells enabled->disabled after answering") + return + tap_node(dk) + fresh = ui() + same_act = get_current_activity() == act + enabled_after = len(enabled_answer_cells(fresh)) + okk = same_act and enabled_before > 0 and enabled_after == 0 + record("states_wrong_answer_cells_disabled", okk, + "" if okk else f"behavior_wrong: enabled answer cells " + f"{enabled_before}->{enabled_after} (expected >0 -> 0)", + depth=2, jump_kind="transition", + expect="answer cells enabled->disabled after answering") + + +@and_test(expects=("states_quiz_wrong_highlight_vlm",)) +def test_quiz_wrong_highlight_vlm(): + """A wrong SURE tap highlights the correct cell GREEN and the wrong-chosen cell + RED/pink — a rendered color property the dump cannot expose.""" + ok, nodes = and_reach_hiragana_quiz() + if not ok: + vlm_assert("states_quiz_wrong_highlight", + "In the answer grid, is one cell highlighted green and a " + "different cell highlighted red or pink?", RESULTS_DIR, + depth=2, jump_kind="value", tag="color") # will fail + return + tap_contains(nodes, "SHOW ANSWERS") + nodes = ui() + # find the question kana and its correct romaji + qkana = None + for n in nodes: + t = n.get("text", "") + if len(t) == 1 and t in KANA2ROMAJI: + qkana = t + break + correct = KANA2ROMAJI.get(qkana) + romaji_vals = set(KANA2ROMAJI.values()) + options = [n for n in nodes + if n.get("text", "") in romaji_vals and n.get("class", "").endswith("TextView")] + wrong = [o for o in options if o.get("text") != correct] + sure_texts = [n for n in nodes if n.get("text") == "SURE"] + if not wrong or not sure_texts: + vlm_assert("states_quiz_wrong_highlight", + "In the answer grid, is one cell highlighted green and a " + "different cell highlighted red or pink?", RESULTS_DIR, + depth=2, jump_kind="value", tag="color") # will fail + return + # tap the SURE nearest (same row, same column side) to a wrong option + tgt = wrong[0] + tx, ty = tgt["_center"] + best, best_d = None, 10 ** 9 + for s in sure_texts: + sx, sy = s["_center"] + d = abs(sy - ty) + abs(sx - tx) * 0.2 + if d < best_d: + best, best_d = s, d + tap_node(best) + settle("tap") + vlm_assert("states_quiz_wrong_highlight", + "In the answer grid, is exactly one answer cell highlighted with a " + "green background and a different cell highlighted with a red or pink " + "background?", RESULTS_DIR, depth=2, jump_kind="value", tag="color") + + +@and_test(expects=("states_writing_field_focused",)) +def test_writing_field_focused(): + """The text-typing writing test opens with its answer EditText already holding + focus (focused=true) — this lane owns `focused`.""" + ok, nodes = and_reach_hiragana_quiz(variant="HIRAGANA TO ROMAJI WRITING") + if not ok: + record("states_writing_field_focused", False, + "setup_failed: could not start the writing test", + depth=2, jump_kind="value", + expect="answer EditText focused=true on entry") + return + ets = find_by_class(nodes, "EditText") + if not ets: + record("states_writing_field_focused", False, + "feature_missing: no EditText in the writing test", + depth=2, jump_kind="value", + expect="answer EditText focused=true on entry") + return + focused = any(e.get("focused") == "true" for e in ets) + record("states_writing_field_focused", focused, + "" if focused else "behavior_wrong: writing test's EditText is not focused", + depth=2, jump_kind="value", + expect="answer EditText focused=true on entry") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Selected state — KanjiDisplay Kanji/Words tabs (this lane owns selected) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_tab_kanji_selected_default", "states_tab_kanji_selected_default_vlm")) +def test_tab_kanji_selected_default(): + """On entry to KanjiDisplay the 'Kanji' tab is selected and 'Words' is not.""" + ok, nodes = and_reach_kanji_display() + if not ok: + record("states_tab_kanji_selected_default", False, + "setup_failed: could not reach KanjiDisplayActivity", + depth=4, jump_kind="value", + expect="Kanji tab selected=true, Words tab selected=false") + vlm_assert("states_tab_kanji_selected_default", + "Is the LEFT tab labeled 'Kanji' the selected/highlighted one?", + RESULTS_DIR, depth=4, jump_kind="value", tag="position") + return + kc = tab_container(nodes, "Kanji") + wc = tab_container(nodes, "Words") + okk = (kc is not None and wc is not None + and kc.get("selected") == "true" and wc.get("selected") == "false") + record("states_tab_kanji_selected_default", okk, + "" if okk else f"behavior_wrong: Kanji.selected=" + f"{kc.get('selected') if kc else None} " + f"Words.selected={wc.get('selected') if wc else None}", + depth=4, jump_kind="value", + expect="Kanji tab selected=true, Words tab selected=false") + vlm_assert("states_tab_kanji_selected_default", + "Near the top there are two tabs, 'Kanji' on the LEFT and 'Words' on " + "the RIGHT. Is the LEFT 'Kanji' tab the selected one (highlighted or " + "underlined) rather than 'Words'?", + RESULTS_DIR, depth=4, jump_kind="value", tag="position") + + +@and_test(expects=("states_tab_words_select", "states_tab_words_select_vlm")) +def test_tab_words_select(): + """Tapping the 'Words' tab flips the selection: Words selected=true, Kanji + selected=false (before->after selected transition).""" + ok, nodes = and_reach_kanji_display() + if not ok: + record("states_tab_words_select", False, + "setup_failed: could not reach KanjiDisplayActivity", + depth=4, jump_kind="transition", + expect="Words tab selected false->true; Kanji true->false") + vlm_assert("states_tab_words_select", + "Is the RIGHT tab labeled 'Words' the selected/highlighted one?", + RESULTS_DIR, depth=4, jump_kind="transition", tag="position") + return + kc_b = tab_container(nodes, "Kanji") + wc_b = tab_container(nodes, "Words") + wt = find_node_ci(nodes, "Words") + tap_node(wt) + fresh = ui() + kc_a = tab_container(fresh, "Kanji") + wc_a = tab_container(fresh, "Words") + okk = (wc_b is not None and wc_b.get("selected") == "false" + and wc_a is not None and wc_a.get("selected") == "true" + and kc_a is not None and kc_a.get("selected") == "false") + record("states_tab_words_select", okk, + "" if okk else f"behavior_wrong: Words.selected " + f"{wc_b.get('selected') if wc_b else None}->" + f"{wc_a.get('selected') if wc_a else None}, Kanji.selected now " + f"{kc_a.get('selected') if kc_a else None}", + depth=4, jump_kind="transition", + expect="Words tab selected false->true; Kanji true->false") + vlm_assert("states_tab_words_select", + "Near the top there are two tabs, 'Kanji' on the LEFT and 'Words' on " + "the RIGHT. Is the RIGHT 'Words' tab now the selected one (the " + "highlight/underline indicator is under 'Words')?", + RESULTS_DIR, depth=4, jump_kind="transition", tag="position") + + +@and_test(expects=("states_tab_content_changes",)) +def test_tab_content_changes(): + """The tab selection drives content: the Kanji tab shows "On'yomi:"; after + tapping Words that heading is gone (replaced by the word list).""" + ok, nodes = and_reach_kanji_display() + if not ok: + record("states_tab_content_changes", False, + "setup_failed: could not reach KanjiDisplayActivity", + depth=4, jump_kind="transition", + expect="On'yomi: present on Kanji tab -> absent on Words tab") + return + act = get_current_activity() + onyomi_before = find_node_ci(nodes, "On'yomi:") is not None + tap_node(find_node_ci(nodes, "Words")) + fresh = ui() + same_act = get_current_activity() == act + onyomi_after = find_node_ci(fresh, "On'yomi:") is not None + okk = same_act and onyomi_before and not onyomi_after + record("states_tab_content_changes", okk, + "" if okk else f"behavior_wrong: On'yomi present " + f"{onyomi_before}->{onyomi_after} across the tab switch", + depth=4, jump_kind="transition", + expect="On'yomi: present on Kanji tab -> absent on Words tab") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Checked state — item-selection checkboxes (this lane owns checked) + persistence +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_checkbox_toggle", "states_checkbox_checked_vlm")) +def test_checkbox_toggle(): + """An enabled kanji row CheckBox: checked true -> false (CHECKED transition). + Restored to checked afterward so quiz-start (needs >=10) is not poisoned.""" + ok, nodes = and_reach_jlpt5() + if not ok: + record("states_checkbox_toggle", False, + "setup_failed: could not reach JLPT level 5 item selection", + depth=3, jump_kind="transition", + expect="row CheckBox checked true->false") + vlm_assert("states_checkbox_checked", + "Are the list-row checkboxes filled/checked rather than empty?", + RESULTS_DIR, depth=3, jump_kind="transition", tag="shape") + return + cbs = find_by_class(nodes, "CheckBox") + if not cbs: + record("states_checkbox_toggle", False, + "feature_missing: no CheckBox rows in item selection", + depth=3, jump_kind="transition", + expect="row CheckBox checked true->false") + vlm_assert("states_checkbox_checked", + "Are the list-row checkboxes filled/checked rather than empty?", + RESULTS_DIR, depth=3, jump_kind="transition", tag="shape") + return + cb0 = cbs[0] + # VLM on the default all-checked state BEFORE we toggle anything. + vlm_assert("states_checkbox_checked", + "On the left of each list row there are checkboxes. Are they filled / " + "checked (a filled box with a checkmark) rather than empty outlines?", + RESULTS_DIR, depth=3, jump_kind="transition", tag="shape") + try: + before = cb0.get("checked") + tap_node(cb0) + after = (find_by_class(ui(), "CheckBox") or [{}])[0].get("checked") + okk = before == "true" and after == "false" + record("states_checkbox_toggle", okk, + "" if okk else f"behavior_wrong: CheckBox {before}->{after}, " + f"expected true->false", + depth=3, jump_kind="transition", + expect="row CheckBox checked true->false") + finally: + cur = find_by_class(ui(), "CheckBox") + if cur and cur[0].get("checked") == "false": + tap_node(cur[0]) # restore checked + + +@and_test(expects=("states_checkbox_persist",)) +def test_checkbox_persist(): + """An unchecked item stays unchecked after leaving the item-selection screen + and reopening it — the CHECKED state persists to the DB. Restore afterward.""" + ok, nodes = and_reach_jlpt5() + if not ok: + record("states_checkbox_persist", False, + "setup_failed: could not reach JLPT level 5 item selection", + depth=3, jump_kind="value", + expect="unchecked CheckBox still unchecked after reopen") + return + cbs = find_by_class(nodes, "CheckBox") + if not cbs: + record("states_checkbox_persist", False, + "feature_missing: no CheckBox rows in item selection", + depth=3, jump_kind="value", + expect="unchecked CheckBox still unchecked after reopen") + return + try: + cb0 = cbs[0] + if cb0.get("checked") == "true": + tap_node(cb0) # uncheck it + # leave item selection -> class selection, then reopen the same class + back() + settle("tap") + on_class = "ClassSelectionActivity" in get_current_activity() + tap_contains(ui(), "JLPT level 5") + settle("tap") + again = find_by_class(ui(), "CheckBox") + persisted = bool(again) and again[0].get("checked") == "false" + okk = on_class and persisted + record("states_checkbox_persist", okk, + "" if okk else "behavior_wrong: CheckBox did not stay unchecked " + "after reopening the item selection screen", + depth=3, jump_kind="value", + expect="unchecked CheckBox still unchecked after reopen") + finally: + cur = find_by_class(ui(), "CheckBox") + if cur and cur[0].get("checked") == "false": + tap_node(cur[0]) # restore checked (keep >=10 enabled) + + +TESTS = [ + # Settings toggles + persistence (this lane owns checked + persistence) + test_dark_theme_toggle, + test_dark_theme_persist_reopen, + test_dark_theme_persist_processdeath, + test_dark_theme_applied_vlm, + test_single_button_toggle, + test_single_button_consequence, + test_keep_screen_on_toggle, + test_custom_font_toggle, + test_hide_answers_toggle, + # Settings-state -> cross-screen quiz consequence + test_hide_answers_off_consequence, + test_hide_answers_on_consequence, + # Quiz state machine + test_show_answers_flip, + test_wrong_answer_next_flip, + test_wrong_answer_cells_disabled, + test_quiz_wrong_highlight_vlm, + test_writing_field_focused, + # Selected — KanjiDisplay tabs + test_tab_kanji_selected_default, + test_tab_words_select, + test_tab_content_changes, + # Checked — item-selection checkboxes + persistence + test_checkbox_toggle, + test_checkbox_persist, +] + +if __name__ == "__main__": + if not device_online(): + print("Device offline — the tunnel may have dropped; aborting.") + sys.exit(2) + run_suite(TESTS, "states") diff --git a/android/blastrock-kakugo/tests/test_android_structure.py b/android/blastrock-kakugo/tests/test_android_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..f66e4e809d9a08e430ce9550ea671f0f0c5e9614 --- /dev/null +++ b/android/blastrock-kakugo/tests/test_android_structure.py @@ -0,0 +1,582 @@ +#!/usr/bin/env python3 +"""STRUCTURE lane for Kakugo (org.kaqui) — the launch GATE and tree-SHAPE deltas. + +This module owns exactly two things: + 1. THE GATE — the app launches, is foregrounded, and its top-level surfaces + exist (main container + the six main-menu buttons + the "Kakugo" title). + These are jump_kind="none" and kept a small minority of the suite. + 2. TREE-SHAPE DELTAS — an interaction that changes the view tree's SHAPE: + a class of widget appears/disappears (the SHOW-ANSWERS answer grid), a + dialog adds a new window layer (Kanji CUSTOM TEST), an overflow adds a + dropdown (class-selection More options). Each records the shape DELTA only + (via and_showing()/surface_changed + class/text counts) and, where it can, + reverses the change and asserts the shape restores. + +Everything asserted here was OBSERVED on the running original. Strings/states/ +values/reachability are ceded to the other lanes — this file proves SHAPE. + +Run: python3 test_android_structure.py org.kaqui +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +# The six main-menu buttons carry BOTH scripts, e.g. "ひらがな\nHIRAGANA"; Compose +# uppercases them. We match by the ASCII substring, case-insensitively. +MAIN_LABELS = ("HIRAGANA", "KATAKANA", "KANJI", "VOCABULARY", "PROGRESS", "SETTINGS") + + +# ── small local helpers (READ-ONLY kit; these only compose kit primitives) ────── + +def _btn_containing(nodes, ascii_sub): + """First Button whose text CONTAINS `ascii_sub` (case-insensitive).""" + s = ascii_sub.lower() + for n in find_by_class(nodes, "Button"): + if s in n.get("text", "").lower(): + return n + return None + + +def _count_text(nodes, text): + """How many nodes have exactly this text (case-insensitive).""" + t = text.strip().lower() + return sum(1 for n in nodes if n.get("text", "").strip().lower() == t) + + +def _x_columns(nodes, text, tol=60): + """Distinct x-centre columns of the nodes whose text == `text`. Used to prove + the answer grid lays SURE cells out in TWO columns, not one.""" + xs = [] + t = text.strip().lower() + for n in nodes: + if n.get("text", "").strip().lower() == t and "_center" in n: + xs.append(n["_center"][0]) + cols = [] + for x in sorted(xs): + if not any(abs(x - c) <= tol for c in cols): + cols.append(x) + return len(cols) + + +# ── named depth-family navigators (back a real depth>=1 / depth>=2) ───────────── + +def and_enter_menu(ascii_sub): + """Main -> a top-level menu (Hiragana/Kanji/Vocabulary...). Returns (ok, nodes).""" + restart_app() + wait_for_foreground() + nodes = ui() + btn = _btn_containing(nodes, ascii_sub) + if btn is None: + return False, nodes + before = and_showing(nodes) + if not tap_node(btn): + return False, nodes + after = and_showing() + if not surface_changed(before, after): + return False, ui() + and_enter(ascii_sub) # one surface crossed + return True, ui() + + +def and_enter_settings(): + """Main -> Settings (MainSettingsActivity). Returns (ok, nodes).""" + return and_enter_menu("SETTINGS") + + +def and_enter_stats(): + """Main -> Progress (StatsActivity). Returns (ok, nodes).""" + return and_enter_menu("PROGRESS") + + +def and_enter_quiz(menu_sub, quiz_text): + """Main -> -> a named quiz button (TestActivity). depth 2 on success. + Returns (ok, nodes) with nodes = the quiz's virgin SHOW-ANSWERS surface.""" + ok, nodes = and_enter_menu(menu_sub) + if not ok: + return False, nodes + qb = None + for n in find_by_class(nodes, "Button"): + if quiz_text.lower() in n.get("text", "").lower(): + qb = n + break + if qb is None: + return False, nodes + if not tap_node(qb): + return False, ui() + and_enter(quiz_text) # second surface crossed + return True, ui() + + +def and_reach_class_selection(): + """Main -> Kanji -> KANJI SELECTION (ClassSelectionActivity). depth 2. + Uses and_reach* so the jump is PROVEN. The SOURCE token must be unique to the + Kanji MENU and absent from the class-selection screen, so 'CUSTOM TEST' is used + rather than 'KANJI SELECTION' (whose substring collides with the destination + title 'Kanji selection').""" + ok, nodes = and_enter_menu("KANJI") + if not ok: + return False, nodes + sel = None + for n in find_by_class(nodes, "Button"): + if "kanji selection" in n.get("text", "").lower(): + sel = n + break + if sel is None: + return False, nodes + reached = and_reach_surface(sel, "Kanji selection", source="CUSTOM TEST") + return reached, ui() + + +def and_answer_one_quiz_question(): + """Navigate into the hiragana grid quiz, reveal the grid and register ONE + answer (any cell), so the Progress chart has data to draw. Returns to the main + menu. Best-effort — used only to give the stats chart VLM something to render.""" + ok, nodes = and_enter_quiz("HIRAGANA", "HIRAGANA TO ROMAJI QUIZ") + if not ok: + restart_app() + wait_for_foreground() + return False + show = find_node_ci(nodes, "SHOW ANSWERS") + if show: + tap_node(show) + nodes = ui() + # Tap the first answer cell's SURE (any answer counts toward the chart). + sure = None + for n in nodes: + if n.get("text", "").strip().lower() == "sure" and "_center" in n: + sure = n + break + if sure: + tap(sure["_center"][0], sure["_center"][1]) + # Leave the quiz cleanly: BACK raises the terminate dialog; OK returns to menu. + back() + nodes = ui() + if find_node_ci(nodes, "Terminate session") is not None: + ok_btn = find_node_ci(nodes, "OK") + if ok_btn: + tap_node(ok_btn) + restart_app() + wait_for_foreground() + return True + + +# ════════════════════════════════════════════════════════════════════════════════ +# GATE (jump_kind="none") — kept a small minority of the suite +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_gate_launch",)) +def test_gate_launch(): + restart_app() + fg = wait_for_foreground() + nodes = ui() + # Top-level container of the launcher surface. + container = (find_by_class(nodes, "FrameLayout") + or find_by_class(nodes, "ViewGroup") + or find_by_class(nodes, "LinearLayout")) + scroller = find_by_class(nodes, "ScrollView") + ok = bool(fg and container and scroller) + record("structure_gate_launch", ok, + "" if ok else "setup_failed: app did not reach the foreground with a " + "top-level scroll container", + depth=0, jump_kind="none") + + +@and_test(expects=("structure_main_six_buttons",)) +def test_main_six_buttons(): + restart_app() + wait_for_foreground() + nodes = ui() + btns = find_by_class(nodes, "Button") + present = [lbl for lbl in MAIN_LABELS if _btn_containing(nodes, lbl) is not None] + title = find_node_ci(nodes, "Kakugo") is not None + ok = len(btns) == 6 and len(present) == 6 and title + record("structure_main_six_buttons", ok, + "" if ok else f"feature_missing: expected 6 menu buttons " + f"{MAIN_LABELS} + 'Kakugo' title; got buttons={len(btns)} " + f"matched={present} title={title}", + depth=0, jump_kind="none") + + +# ════════════════════════════════════════════════════════════════════════════════ +# TREE-SHAPE DELTAS (jump_kind="transition") — the core of this lane +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_hiragana_menu_shape",)) +def test_hiragana_menu_shape(): + """Main -> HIRAGANA: the menu surface replaces the 6 main-menu buttons with a + class of >=4 test-type Buttons (quiz/writing/drawing/selection).""" + before = and_showing(ui() if wait_for_foreground() else None) + ok_nav, nodes = and_enter_menu("HIRAGANA") + btns = find_by_class(nodes, "Button") + title = find_node_ci(nodes, "Hiragana") is not None + main_gone = _btn_containing(nodes, "VOCABULARY") is None + ok = bool(ok_nav and title and len(btns) >= 4 and main_gone) + record("structure_hiragana_menu_shape", ok, + "" if ok else f"behavior_wrong: hiragana menu shape wrong " + f"(nav={ok_nav} title={title} buttons={len(btns)} main_gone={main_gone})", + depth=1, jump_kind="transition", + expect="Main's 6 buttons replaced by >=4 hiragana test-type Buttons " + "under the 'Hiragana' title") + + +@and_test(expects=("structure_kanji_menu_shape",)) +def test_kanji_menu_shape(): + """Main -> KANJI: kanji menu exposes a larger class of test-type Buttons + (>=6: readings/meanings/composition/drawing/custom/selection).""" + ok_nav, nodes = and_enter_menu("KANJI") + btns = find_by_class(nodes, "Button") + title = find_node_ci(nodes, "Kanji") is not None + ok = bool(ok_nav and title and len(btns) >= 6) + record("structure_kanji_menu_shape", ok, + "" if ok else f"behavior_wrong: kanji menu shape wrong " + f"(nav={ok_nav} title={title} buttons={len(btns)})", + depth=1, jump_kind="transition", + expect="Kanji menu shows >=6 test-type Buttons under the 'Kanji' title") + + +@and_test(expects=("structure_settings_pref_shape",)) +def test_settings_pref_shape(): + """Main -> Settings: a RecyclerView-backed preference list whose SHAPE is a + long stack of labelled rows and a class of >=5 Switch toggles.""" + ok_nav, nodes = and_enter_settings() + recycler = node_by_id(nodes, "recycler_view") is not None + titles = [n for n in nodes if n.get("resource-id", "").endswith("/title")] + switches = find_by_class(nodes, "Switch") + ok = bool(ok_nav and recycler and len(titles) >= 5 and len(switches) >= 5) + record("structure_settings_pref_shape", ok, + "" if ok else f"behavior_wrong: settings shape wrong " + f"(nav={ok_nav} recycler={recycler} rows={len(titles)} " + f"switches={len(switches)})", + depth=1, jump_kind="transition", + expect="Settings is a RecyclerView with >=5 preference title rows and " + ">=5 Switch toggles") + + +@and_test(expects=("structure_quiz_show_answers_delta",)) +def test_quiz_show_answers_delta(): + """SHOW ANSWERS is the canonical shape delta: the virgin grid quiz shows a + single SHOW-ANSWERS control and ZERO answer cells; tapping it grows the tree + (SURE/MAYBE cells + DON'T KNOW appear, SHOW ANSWERS vanishes). Reversed by + restarting the quiz to its virgin state, which restores the zero-cell shape.""" + ok_nav, nodes = and_enter_quiz("HIRAGANA", "HIRAGANA TO ROMAJI QUIZ") + if not ok_nav: + record("structure_quiz_show_answers_delta", False, + "setup_failed: could not reach the hiragana grid quiz", + depth=2, jump_kind="transition", + expect="node count grows after SHOW ANSWERS; grid of SURE/MAYBE " + "appears and restores to zero on restart") + return + before_sure = _count_text(nodes, "SURE") + before_maybe = _count_text(nodes, "MAYBE") + before_show = find_node_ci(nodes, "SHOW ANSWERS") + before_keys = and_showing(nodes) + before_n = len(nodes) + + tapped = tap_node(before_show) if before_show else False + nodes2 = ui() + after_sure = _count_text(nodes2, "SURE") + after_maybe = _count_text(nodes2, "MAYBE") + after_dk = _count_text(nodes2, "DON'T KNOW") + after_show = find_node_ci(nodes2, "SHOW ANSWERS") + after_keys = and_showing(nodes2) + after_n = len(nodes2) + + grew = (before_sure == 0 and before_maybe == 0 and after_sure >= 2 + and after_maybe >= 2 and after_dk >= 1 and after_n > before_n + and after_show is None and surface_changed(before_keys, after_keys, 4)) + + # Reverse: a fresh quiz session must return to the virgin (zero-cell) shape. + ok_nav2, nodes3 = and_enter_quiz("HIRAGANA", "HIRAGANA TO ROMAJI QUIZ") + restored = (ok_nav2 and _count_text(nodes3, "SURE") == 0 + and _count_text(nodes3, "MAYBE") == 0 + and find_node_ci(nodes3, "SHOW ANSWERS") is not None) + + ok = bool(tapped and grew and restored) + record("structure_quiz_show_answers_delta", ok, + "" if ok else f"behavior_wrong: SHOW ANSWERS shape delta failed " + f"(before sure/maybe={before_sure}/{before_maybe} n={before_n}; " + f"after sure/maybe/dk={after_sure}/{after_maybe}/{after_dk} n={after_n} " + f"show_gone={after_show is None}; restored={restored})", + depth=2, jump_kind="transition", + expect="SURE 0->6 & MAYBE 0->6 & DON'T KNOW 0->1, node count grows, " + "SHOW ANSWERS disappears; restored to zero cells on quiz restart") + + +@and_test(expects=("structure_quiz_grid_two_columns",)) +def test_quiz_grid_two_columns(): + """After SHOW ANSWERS the answer cells form a 2-column grid: the SURE cells + occupy exactly two distinct x-columns (shape, not the strings themselves).""" + ok_nav, nodes = and_enter_quiz("HIRAGANA", "HIRAGANA TO ROMAJI QUIZ") + show = find_node_ci(nodes, "SHOW ANSWERS") if ok_nav else None + tapped = tap_node(show) if show else False + nodes2 = ui() + n_sure = _count_text(nodes2, "SURE") + cols = _x_columns(nodes2, "SURE") + ok = bool(ok_nav and tapped and n_sure >= 4 and cols == 2) + record("structure_quiz_grid_two_columns", ok, + "" if ok else f"behavior_wrong: answer grid not 2-column " + f"(nav={ok_nav} tapped={tapped} sure_cells={n_sure} x_columns={cols})", + depth=2, jump_kind="transition", + expect="answer grid lays SURE cells in exactly 2 x-columns " + "(>=4 cells total)") + + +@and_test(expects=("structure_custom_test_dialog_delta",)) +def test_custom_test_dialog_delta(): + """Kanji CUSTOM TEST opens a dialog = a NEW window layer over the menu: the + prompt + OK/CANCEL appear and the surface changes. Reversed with CANCEL, + which pops the layer back to the menu shape.""" + ok_nav, nodes = and_enter_menu("KANJI") + ct = None + for n in find_by_class(nodes, "Button"): + if "custom test" in n.get("text", "").lower(): + ct = n + break + if not (ok_nav and ct): + record("structure_custom_test_dialog_delta", False, + "setup_failed: could not reach the Kanji CUSTOM TEST button", + depth=1, jump_kind="transition", + expect="dialog window layer (prompt + OK/CANCEL) appears and is " + "removed on CANCEL") + return + before = and_showing(nodes) + tapped = tap_node(ct) + nodes2 = ui() + after = and_showing(nodes2) + prompt = find_node_ci(nodes2, "Select the desired types of questions:") is not None + ok_btn = find_node_ci(nodes2, "OK") is not None + cancel_btn = find_node_ci(nodes2, "CANCEL") is not None + opened = tapped and prompt and ok_btn and cancel_btn and surface_changed(before, after, 4) + + # Reverse: CANCEL removes the dialog layer and the prompt is gone again. + cancel = find_node_ci(nodes2, "CANCEL") + dismissed = False + if cancel and safe_tap(cancel): + nodes3 = ui() + dismissed = find_node_ci(nodes3, "Select the desired types of questions:") is None + + ok = bool(opened and dismissed) + record("structure_custom_test_dialog_delta", ok, + "" if ok else f"behavior_wrong: custom-test dialog delta failed " + f"(opened={opened} prompt={prompt} ok={ok_btn} cancel={cancel_btn} " + f"dismissed={dismissed})", + depth=1, jump_kind="transition", + expect="CUSTOM TEST adds a dialog window layer (prompt + OK/CANCEL); " + "surface changes and restores on CANCEL") + + +@and_test(expects=("structure_classsel_overflow_delta",)) +def test_classsel_overflow_delta(): + """Class-selection 'More options' adds a dropdown = shape delta (the four + dropdown actions appear over the list). depth 2 (Main->Kanji->KanjiSelection). + Reversed with BACK, which pops the dropdown and restores the list shape.""" + reached, nodes = and_reach_class_selection() + overflow = None + for n in nodes: + if n.get("content-desc", "").strip().lower() in ("more options", "overflow"): + overflow = n + break + if not (reached and overflow): + record("structure_classsel_overflow_delta", False, + "setup_failed: could not reach class selection with a More-options " + "control", + depth=2, jump_kind="transition", + expect="More-options dropdown adds Save/Load/Import actions; " + "restored on BACK") + return + before = and_showing(nodes) + tapped = tap_node(overflow) + nodes2 = ui() + after = and_showing(nodes2) + # Count the dropdown actions by their labels (avoid depending on the + # destructive 'Select none' entry other than to note it exists). + actions = sum(1 for t in ("Save current selection", "Load selection", + "Import selection") + if find_node_ci(nodes2, t) is not None) + opened = tapped and actions >= 2 and surface_changed(before, after, 4) + + # Reverse: BACK removes the dropdown; the action labels are gone again. + back() + nodes3 = ui() + closed = find_node_ci(nodes3, "Save current selection") is None + + ok = bool(opened and closed) + record("structure_classsel_overflow_delta", ok, + "" if ok else f"behavior_wrong: overflow dropdown delta failed " + f"(opened={opened} actions={actions} closed={closed})", + depth=2, jump_kind="transition", + expect="More-options adds a dropdown with >=2 named actions " + "(Save/Load/Import) over the class list; removed on BACK") + + +@and_test(expects=("structure_drawing_canvas_shape",)) +def test_drawing_canvas_shape(): + """The drawing test has a DIFFERENT shape from the grid quizzes: a single + large canvas region (no SURE/MAYBE class of cells) between the question and + the HINT + DON'T KNOW controls.""" + ok_nav, nodes = and_enter_menu("HIRAGANA") + db = None + for n in find_by_class(nodes, "Button"): + if "hiragana drawing" in n.get("text", "").lower(): + db = n + break + if not (ok_nav and db): + record("structure_drawing_canvas_shape", False, + "setup_failed: could not reach the HIRAGANA DRAWING test", + depth=2, jump_kind="transition", + expect="large canvas region + HINT + DON'T KNOW, and no SURE/MAYBE " + "answer grid") + return + tap_node(db) + and_enter("HIRAGANA DRAWING") # second surface crossed + nodes2 = ui() + s = get_screen_info() + # A large drawing region: wide, tall, below the question glyph. + big = None + for n in nodes2: + b = n.get("_bounds") + if not b: + continue + x1, y1, x2, y2 = b + if (x2 - x1) > s["width"] * 0.7 and (y2 - y1) > 500 and y1 > 900: + big = b + break + hint = find_node_ci(nodes2, "HINT") is not None + dk = find_node_ci(nodes2, "DON'T KNOW") is not None + no_grid = _count_text(nodes2, "SURE") == 0 and _count_text(nodes2, "MAYBE") == 0 + ok = bool(big and hint and dk and no_grid) + record("structure_drawing_canvas_shape", ok, + "" if ok else f"behavior_wrong: drawing shape wrong " + f"(canvas={big is not None} hint={hint} dk={dk} no_grid={no_grid})", + depth=2, jump_kind="transition", + expect="drawing test shows one large canvas region + HINT + DON'T KNOW " + "and NO SURE/MAYBE answer grid") + + +@and_test(expects=("structure_stats_shape",)) +def test_stats_shape(): + """Main -> Progress: the stats surface replaces the menu with a scrollable + stats host carrying the 'Questions answered' heading, and none of the main-menu + buttons remain. (Whether the chart itself is drawn is data-dependent and is + left to the chart VLM; the surface SHAPE change is asserted here.)""" + ok_nav, nodes = and_enter_stats() + heading = find_node_ci(nodes, "Questions answered") is not None + stats_host = len(find_by_class(nodes, "ScrollView")) >= 1 + main_gone = _btn_containing(nodes, "VOCABULARY") is None + title = find_node_ci(nodes, "Progress") is not None + ok = bool(ok_nav and heading and stats_host and main_gone and title) + record("structure_stats_shape", ok, + "" if ok else f"behavior_wrong: stats shape wrong " + f"(nav={ok_nav} heading={heading} stats_host={stats_host} " + f"main_gone={main_gone} title={title})", + depth=1, jump_kind="transition", + expect="Progress shows 'Questions answered' heading + a chart " + "ViewGroup; main-menu buttons gone") + + +# ════════════════════════════════════════════════════════════════════════════════ +# VLM (exactly 5) — each asks a SPECIFIC rendered property a blank shell would fail +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_main_layout_vlm",)) +def test_main_layout_vlm(): + """Gate surface: six full-width buttons evenly stacked in ONE vertical column.""" + restart_app() + wait_for_foreground() + ui() + vlm_assert("structure_main_layout", + "Are there exactly six large rectangular buttons of equal width, " + "stacked one directly below another in a single vertical column that " + "spans the full width of the screen?", + RESULTS_DIR, tag="position", jump_kind="none", depth=0) + + +@and_test(expects=("structure_quiz_grid_vlm",)) +def test_quiz_grid_vlm(): + """Quiz answer grid: two side-by-side columns of answer cells.""" + ok_nav, nodes = and_enter_quiz("HIRAGANA", "HIRAGANA TO ROMAJI QUIZ") + show = find_node_ci(nodes, "SHOW ANSWERS") if ok_nav else None + if show: + tap_node(show) + ui() + vlm_assert("structure_quiz_grid", + "Are the answer options laid out in two side-by-side columns (a grid " + "with a left column and a right column), each option showing a 'SURE' " + "and a 'MAYBE' button?", + RESULTS_DIR, tag="shape", jump_kind="transition", depth=2) + + +@and_test(expects=("structure_stats_chart_vlm",)) +def test_stats_chart_vlm(): + """Progress bar chart: a large coloured (green/pink) vertical bar is drawn. + A quiz answer is registered first so the chart has data to render.""" + and_answer_one_quiz_question() + ok_nav, _ = and_enter_stats() + ui() + vlm_assert("structure_stats_chart", + "Below the 'Questions answered' heading, is at least one large solid " + "coloured vertical bar (green or pink/red) drawn, rather than an " + "empty plot area or only a line of text?", + RESULTS_DIR, tag="color", jump_kind="transition", depth=1) + + +@and_test(expects=("structure_drawing_canvas_vlm",)) +def test_drawing_canvas_vlm(): + """Drawing test: a large empty white square canvas above HINT / DON'T KNOW.""" + ok_nav, nodes = and_enter_menu("HIRAGANA") + db = None + if ok_nav: + for n in find_by_class(nodes, "Button"): + if "hiragana drawing" in n.get("text", "").lower(): + db = n + break + if db: + tap_node(db) + and_enter("HIRAGANA DRAWING") + ui() + vlm_assert("structure_drawing_canvas", + "Is there a large empty white square drawing area filling most of " + "the middle of the screen, positioned directly above a row that " + "contains a 'HINT' button and a \"DON'T KNOW\" button?", + RESULTS_DIR, tag="shape", jump_kind="transition", depth=2) + + +@and_test(expects=("structure_quiz_statsbar_vlm",)) +def test_quiz_statsbar_vlm(): + """Quiz header: a thin coloured status bar sits at the top with 'Session + score' text positioned directly beneath it.""" + and_enter_quiz("HIRAGANA", "HIRAGANA TO ROMAJI QUIZ") + ui() + vlm_assert("structure_quiz_statsbar", + "Near the very top of the content (just under the toolbar), is there " + "a thin coloured horizontal bar, with the words 'Session score' " + "shown on the line directly below that bar?", + RESULTS_DIR, tag="position", jump_kind="transition", depth=2) + + +TESTS = [ + # gate (jump_kind="none") — minority + test_gate_launch, + test_main_six_buttons, + # shape deltas (jump_kind="transition") + test_hiragana_menu_shape, + test_kanji_menu_shape, + test_settings_pref_shape, + test_quiz_show_answers_delta, + test_quiz_grid_two_columns, + test_custom_test_dialog_delta, + test_classsel_overflow_delta, + test_drawing_canvas_shape, + test_stats_shape, + # VLM (exactly 5) + test_main_layout_vlm, + test_quiz_grid_vlm, + test_stats_chart_vlm, + test_drawing_canvas_vlm, + test_quiz_statsbar_vlm, +] + +if __name__ == "__main__": + run_suite(TESTS, "structure") diff --git a/android/blastrock-kakugo/tests/test_android_text.py b/android/blastrock-kakugo/tests/test_android_text.py new file mode 100644 index 0000000000000000000000000000000000000000..4a2a26bd1dfbe5f78543487a68d06dbdb399003a --- /dev/null +++ b/android/blastrock-kakugo/tests/test_android_text.py @@ -0,0 +1,850 @@ +#!/usr/bin/env python3 +"""TEXT lane for Kakugo (org.kaqui). + +Owner of exact-string equality of CONTENT that an ACTION produces. Every test +navigates or acts, then asserts the SPECIFIC string an interaction rendered: +- the produced quiz status line "Session score: 0/0" / "1/1" +- screen titles that change with the selected menu ("Hiragana", "Katakana", ...) +- quiz answer-button labels the SHOW-ANSWERS gate produces ("SURE"/"MAYBE"/ + "DON'T KNOW"/"NEXT") +- the terminate dialog's exact wording +- settings preference labels + summaries +- KanjiDisplay content labels (On'yomi:/Kun'yomi:/... and status chips) +- the correct-romaji string a wrong text-typing answer reveals +- content-desc on icon-only controls (Open in external dictionary / Search) + +Every string below was OBSERVED on the running original before authoring. The +discriminating half is the CHANGE: each produced string is asserted ABSENT before +its trigger and PRESENT after, so a dead shell that hardcodes a label cannot pass. +The "before" surface for a string that appears as soon as a screen opens is the +PREVIOUS screen (e.g. a Settings label is absent on the main menu, present in +Settings) — never the same screen, where it would already be present. + +VLM budget for this lane: exactly ONE. Reserved for the Stats "Progress" chart +legend, which is drawn on the MPAndroidChart canvas and NEVER reaches the view +tree (confirmed live: the dump on that screen holds only "Questions answered" and +"Progress"). Everything else here is dump-readable and stays a rule assertion. + +Live gotchas encoded below: + * Compose UPPERCASES button labels; the main-menu buttons carry BOTH scripts as + a single string with a literal " " entity, e.g. "漢字 KANJI" (the dump + does not decode the newline). So main-menu buttons are matched by their ASCII + token as a case-insensitive SUBSTRING, never by split("\\n"). + * ClassSelectionActivity and ItemSelectionActivity BOTH show the title + "Kanji selection"; the two are told apart by content (a kanji glyph / a row). + * A kanji row's tap target is the full-width clickable row View; tapping the + glyph "一" (center well away from the left-edge checkbox) navigates to + KanjiDisplay — the proven path. + * In a grid quiz cell the SURE button sits slightly ABOVE its answer-text + center and in the SAME COLUMN, so the correct SURE is paired by column + and + nearest y, never by a below-only filter. +""" +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403 + + +# ── kana -> romaji (the app's romaji strings; used to derive the writing-test +# correct answer and the grid correct option at runtime from the shown kana). ─── +KANA2ROMAJI = { + "あ": "a", "い": "i", "う": "u", "え": "e", "お": "o", + "か": "ka", "き": "ki", "く": "ku", "け": "ke", "こ": "ko", + "さ": "sa", "し": "shi", "す": "su", "せ": "se", "そ": "so", + "た": "ta", "ち": "chi", "つ": "tsu", "て": "te", "と": "to", + "な": "na", "に": "ni", "ぬ": "nu", "ね": "ne", "の": "no", + "は": "ha", "ひ": "hi", "ふ": "fu", "へ": "he", "ほ": "ho", + "ま": "ma", "み": "mi", "む": "mu", "め": "me", "も": "mo", + "や": "ya", "ゆ": "yu", "よ": "yo", + "ら": "ra", "り": "ri", "る": "ru", "れ": "re", "ろ": "ro", + "わ": "wa", "を": "wo", "ん": "n", + "が": "ga", "ぎ": "gi", "ぐ": "gu", "げ": "ge", "ご": "go", + "ざ": "za", "じ": "ji", "ず": "zu", "ぜ": "ze", "ぞ": "zo", + "だ": "da", "ぢ": "ji", "づ": "zu", "で": "de", "ど": "do", + "ば": "ba", "び": "bi", "ぶ": "bu", "べ": "be", "ぼ": "bo", + "ぱ": "pa", "ぴ": "pi", "ぷ": "pu", "ぺ": "pe", "ぽ": "po", +} + + +# ── generic string helpers ──────────────────────────────────────────────────── +def all_text(nodes): + """All non-empty text values, joined for a fast substring probe.""" + return " | ".join(n.get("text", "") for n in nodes if n.get("text")) + + +def has_text(nodes, s): + """Exact-string presence anywhere in the tree (text or content-desc).""" + return find_node(nodes, text=s) is not None or find_node(nodes, content_desc=s) is not None + + +def has_text_ci(nodes, s): + """Case-insensitive presence (text or content-desc).""" + return find_node_ci(nodes, s) is not None + + +def fresh_main(): + """This test's own entry point: relaunch to a clean main menu; return the + tree, or None if the app never came to the foreground.""" + restart_app() + return ui() if wait_for_foreground() else None + + +def menu_button(nodes, ascii_token): + """A main-menu Button matched by its ASCII token as a case-insensitive + substring — the buttons carry ' ' and must never be split. + Excludes the sub-menu buttons that also contain the token.""" + t = ascii_token.upper() + for n in nodes: + if not n.get("class", "").endswith("Button"): + continue + up = n.get("text", "").upper() + if t in up and "SELECTION" not in up and " TO " not in up and "CUSTOM" not in up: + return n + return None + + +def sub_button(nodes, token): + """Any Button whose UPPERCASED text CONTAINS token (sub-menu buttons).""" + t = token.upper() + return next((n for n in nodes if n.get("class", "").endswith("Button") + and t in n.get("text", "").upper()), None) + + +def question_kana(nodes): + """The large question glyph on a hiragana test == the first single-kana text + that is in the romaji map.""" + for n in nodes: + t = n.get("text", "").strip() + if t in KANA2ROMAJI: + return t + return None + + +def sure_for_option(nodes, romaji): + """The SURE button paired with the answer cell whose text == `romaji`. + + Each grid cell lays out [answer text | SURE (top) / MAYBE (below)]: the SURE + sits just to the RIGHT of its answer text and on the SAME ROW (its y-center is + ~60px above the answer-text center). Columns are ~500px apart, so a naive + |dx| threshold mis-pairs a right-column option with a left-column SURE. We + therefore take, among SUREs whose center is to the RIGHT of the option and on + the same row (|dy| small), the one closest in x.""" + opt = None + for n in nodes: + if n.get("text", "").strip() == romaji and "_center" in n: + opt = n + break + if not opt: + return None + ox, oy = opt["_center"] + sures = [s for s in nodes if s.get("text", "").strip().upper() == "SURE" + and "_center" in s] + same_row = [s for s in sures + if s["_center"][0] > ox and abs(s["_center"][1] - oy) < 90] + if same_row: + return min(same_row, key=lambda s: s["_center"][0] - ox) + # Fallback: nearest by combined distance (should rarely be needed). + if not sures: + return None + return min(sures, key=lambda s: abs(s["_center"][1] - oy) * 3 + + abs(s["_center"][0] - ox)) + + +# ── navigation helpers. The and_enter*/and_reach* NAME is what backs a declared +# depth>=1; each leaves the destination surface open and returns True on success. +def and_enter_menu(nodes, ascii_token, title): + """Main -> a top menu (Hiragana/Katakana/Kanji/Vocabulary/Progress/Settings). + Taps the main-menu button and counts one surface. Callers confirm the + destination string appeared.""" + b = menu_button(nodes, ascii_token) + if not b: + return False + if not tap_node(b): + return False + and_enter(title) + return True + + +def and_reach_quiz(kind_token): + """Main -> Hiragana -> a grid quiz (depth 2). Leaves TestActivity open with the + 'Session score' line rendered. Returns the tree, or None.""" + n = fresh_main() + if n is None or not and_enter_menu(n, "HIRAGANA", "Hiragana"): + return None + settle("tap") + n = ui() + q = sub_button(n, kind_token) + if not q or not tap_node(q): + return None + and_enter("quiz") + settle("tap") + return ui() + + +def show_answers(nodes): + """Tap the SHOW ANSWERS gate; return the fresh answers tree (or the input).""" + btn = find_node_ci(nodes, "SHOW ANSWERS") or sub_button(nodes, "SHOW ANSWERS") + if btn: + tap_node(btn) + settle("tap") + return ui() + + +def and_reach_settings(): + """Main -> Settings (depth 1). Leaves the preference list open; returns the + tree, or None. The whole preference list renders in the dump at once (no + scroll needed for any label/summary).""" + n = fresh_main() + if n is None or not and_enter_menu(n, "SETTINGS", "Settings"): + return None + settle("tap") + return ui() + + +def and_reach_kanji_selection(): + """Main -> Kanji -> KANJI SELECTION (ClassSelectionActivity, depth 2). Leaves + the class list open; returns the tree or None.""" + n = fresh_main() + if n is None or not and_enter_menu(n, "KANJI", "Kanji"): + return None + settle("tap") + n = ui() + sel = find_node(n, text="KANJI SELECTION") or find_node_ci(n, "KANJI SELECTION") + if not sel or not tap_node(sel): + return None + and_enter("Kanji selection") + settle("tap") + return ui() + + +def and_reach_kanji_display(): + """Main -> Kanji -> KANJI SELECTION -> JLPT level 5 -> kanji row -> KanjiDisplay + (depth 4). Leaves the detail surface open; returns the tree or None.""" + n = and_reach_kanji_selection() + if n is None: + return None + lvl = find_node(n, text="JLPT level 5") + if not lvl or not tap_node(lvl): + return None + and_enter("JLPT level 5") + settle("tap") + n = ui() + # Tap the first kanji glyph body; its center is far from the left checkbox, so + # it falls through to the clickable full-width row View -> KanjiDisplay. + glyph = find_node(n, text="一") or next( + (x for x in n if len(x.get("text", "").strip()) == 1 + and x.get("text", "").strip() >= " "), None) + if not glyph or not tap_node(glyph): + return None + and_enter("kanji detail") + settle("tap") + return ui() + + +# ══════════════════════════════════════════════════════════════════════════════ +# T1 — the produced quiz score STRING +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_score_label_start",)) +def test_score_label_start(): + n = fresh_main() + absent = n is not None and not has_text(n, "Session score: 0/0") + tree = and_reach_quiz("TO ROMAJI QUIZ") + if tree is None: + record("text_score_label_start", False, + "setup_failed: could not start a hiragana grid quiz", + depth=2, jump_kind="value", expect="Session score: 0/0") + return + present = has_text(tree, "Session score: 0/0") + ok = bool(absent and present) + record("text_score_label_start", ok, + "" if ok else "behavior_wrong: quiz did not render the exact " + "'Session score: 0/0' status line", + depth=2, jump_kind="value", expect="Session score: 0/0") + + +@and_test(expects=("text_score_after_correct",)) +def test_score_after_correct(): + """Answer the option whose romaji matches the question kana; the produced + status STRING must flip 0/0 -> 1/1.""" + tree = and_reach_quiz("TO ROMAJI QUIZ") + if tree is None: + record("text_score_after_correct", False, + "setup_failed: could not start a hiragana grid quiz", + depth=2, jump_kind="value", expect="Session score: 1/1") + return + before = has_text(tree, "Session score: 0/0") + kana = question_kana(tree) + romaji = KANA2ROMAJI.get(kana or "") + if not romaji: + record("text_score_after_correct", False, + "setup_failed: could not read the question kana to derive its romaji", + depth=2, jump_kind="value", expect="Session score: 1/1") + return + n = show_answers(tree) + target = sure_for_option(n, romaji) + if not target or not tap_node(target): + record("text_score_after_correct", False, + f"setup_failed: could not tap the SURE for the correct option " + f"'{romaji}' (kana '{kana}')", + depth=2, jump_kind="value", expect="Session score: 1/1") + return + settle("tap") + after = has_text(ui(), "Session score: 1/1") + ok = bool(before and after) + record("text_score_after_correct", ok, + "" if ok else "behavior_wrong: correct answer did not produce " + "'Session score: 1/1'", + depth=2, jump_kind="value", expect="Session score: 1/1") + + +# ══════════════════════════════════════════════════════════════════════════════ +# T2 — screen titles produced by navigating (each a distinct produced string) +# ══════════════════════════════════════════════════════════════════════════════ +def _title_test(record_name, ascii_token, title): + n = fresh_main() + if n is None: + record(record_name, False, "setup_failed: main menu never appeared", + depth=1, jump_kind="value", expect=title) + return + absent = not has_text(n, title) + if not and_enter_menu(n, ascii_token, title): + record(record_name, False, + f"setup_failed: main-menu button '{ascii_token}' not found", + depth=1, jump_kind="value", expect=title) + return + settle("tap") + present = has_text(ui(), title) + ok = bool(absent and present) + record(record_name, ok, + "" if ok else f"behavior_wrong: '{title}' title not produced after " + f"opening the {ascii_token} menu", + depth=1, jump_kind="value", expect=title) + + +@and_test(expects=("text_title_hiragana",)) +def test_title_hiragana(): + _title_test("text_title_hiragana", "HIRAGANA", "Hiragana") + + +@and_test(expects=("text_title_katakana",)) +def test_title_katakana(): + _title_test("text_title_katakana", "KATAKANA", "Katakana") + + +@and_test(expects=("text_title_kanji",)) +def test_title_kanji(): + _title_test("text_title_kanji", "KANJI", "Kanji") + + +@and_test(expects=("text_title_vocabulary",)) +def test_title_vocabulary(): + _title_test("text_title_vocabulary", "VOCABULARY", "Vocabulary") + + +@and_test(expects=("text_title_progress",)) +def test_title_progress(): + _title_test("text_title_progress", "PROGRESS", "Progress") + + +@and_test(expects=("text_title_settings",)) +def test_title_settings(): + _title_test("text_title_settings", "SETTINGS", "Settings") + + +@and_test(expects=("text_title_kanji_selection",)) +def test_title_kanji_selection(): + """Main -> Kanji -> KANJI SELECTION produces the title 'Kanji selection' + (depth 2). Absent on the kanji menu, present on ClassSelectionActivity.""" + n = fresh_main() + if n is None or not and_enter_menu(n, "KANJI", "Kanji"): + record("text_title_kanji_selection", False, + "setup_failed: could not open the Kanji menu", + depth=2, jump_kind="value", expect="Kanji selection") + return + settle("tap") + menu = ui() + absent = not has_text(menu, "Kanji selection") + sel = find_node(menu, text="KANJI SELECTION") or find_node_ci(menu, "KANJI SELECTION") + if not sel or not tap_node(sel): + record("text_title_kanji_selection", False, + "setup_failed: 'KANJI SELECTION' button not found on the Kanji menu", + depth=2, jump_kind="value", expect="Kanji selection") + return + and_enter("Kanji selection") + settle("tap") + present = has_text(ui(), "Kanji selection") + ok = bool(absent and present) + record("text_title_kanji_selection", ok, + "" if ok else "behavior_wrong: 'Kanji selection' title not produced", + depth=2, jump_kind="value", expect="Kanji selection") + + +# ══════════════════════════════════════════════════════════════════════════════ +# T3 — quiz answer-button labels the interaction produces +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_show_answers_label",)) +def test_show_answers_label(): + """A grid quiz starts gated behind the produced 'SHOW ANSWERS' label.""" + tree = and_reach_quiz("TO ROMAJI QUIZ") + if tree is None: + record("text_show_answers_label", False, + "setup_failed: could not start a hiragana grid quiz", + depth=2, jump_kind="value", expect="SHOW ANSWERS") + return + present = has_text_ci(tree, "SHOW ANSWERS") + record("text_show_answers_label", bool(present), + "" if present else "behavior_wrong: quiz did not render a " + "'SHOW ANSWERS' button", + depth=2, jump_kind="value", expect="SHOW ANSWERS") + + +@and_test(expects=("text_answer_buttons_labels",)) +def test_answer_buttons_labels(): + """Tapping SHOW ANSWERS produces the answer-cell labels SURE / MAYBE and the + DON'T KNOW button. All three absent before the tap, present after.""" + tree = and_reach_quiz("TO ROMAJI QUIZ") + if tree is None: + record("text_answer_buttons_labels", False, + "setup_failed: could not start a hiragana grid quiz", + depth=2, jump_kind="value", expect="SURE / MAYBE / DON'T KNOW") + return + absent = not (has_text_ci(tree, "SURE") or has_text_ci(tree, "DON'T KNOW")) + n = show_answers(tree) + present = (has_text_ci(n, "SURE") and has_text_ci(n, "MAYBE") + and has_text_ci(n, "DON'T KNOW")) + ok = bool(absent and present) + record("text_answer_buttons_labels", ok, + "" if ok else "behavior_wrong: SHOW ANSWERS did not produce the " + "SURE / MAYBE / DON'T KNOW labels", + depth=2, jump_kind="value", expect="SURE / MAYBE / DON'T KNOW") + + +@and_test(expects=("text_next_after_wrong",)) +def test_next_after_wrong(): + """DON'T KNOW (counts as wrong) flips the bottom button label to 'NEXT': + absent before, present after.""" + tree = and_reach_quiz("TO ROMAJI QUIZ") + if tree is None: + record("text_next_after_wrong", False, + "setup_failed: could not start a hiragana grid quiz", + depth=2, jump_kind="value", expect="NEXT") + return + n = show_answers(tree) + absent = not has_text_ci(n, "NEXT") + dk = find_node_ci(n, "DON'T KNOW") + if not dk or not tap_node(dk): + record("text_next_after_wrong", False, + "setup_failed: DON'T KNOW button not found after SHOW ANSWERS", + depth=2, jump_kind="value", expect="NEXT") + return + settle("tap") + present = has_text_ci(ui(), "NEXT") + ok = bool(absent and present) + record("text_next_after_wrong", ok, + "" if ok else "behavior_wrong: answering wrong did not produce a " + "'NEXT' button", + depth=2, jump_kind="value", expect="NEXT") + + +# ══════════════════════════════════════════════════════════════════════════════ +# T4 — the Terminate-session dialog text (produced by BACK inside a quiz) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_terminate_dialog",)) +def test_terminate_dialog(): + tree = and_reach_quiz("TO ROMAJI QUIZ") + if tree is None: + record("text_terminate_dialog", False, + "setup_failed: could not start a hiragana grid quiz", + depth=3, jump_kind="value", + expect="Terminate session / Are you sure you want to end this quiz session?") + return + absent = not has_text(tree, "Terminate session") + back() # opens the AlertDialog (a new surface) + and_enter("Terminate dialog") + settle("tap") + n = ui() + title_ok = has_text(n, "Terminate session") + msg_ok = has_text(n, "Are you sure you want to end this quiz session?") + ok = bool(absent and title_ok and msg_ok) + record("text_terminate_dialog", ok, + "" if ok else "behavior_wrong: BACK did not produce the exact " + "'Terminate session' dialog text", + depth=3, jump_kind="value", + expect="Terminate session / Are you sure you want to end this quiz session?") + + +# ══════════════════════════════════════════════════════════════════════════════ +# T5 — Settings preference labels + summaries. Each string is absent on the main +# menu (the "before" surface) and present the moment Settings opens. +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_settings_dark_theme",)) +def test_settings_dark_theme(): + """'Enable dark theme' + its exact summary 'Will update when leaving the + settings screen'.""" + n = fresh_main() + if n is None: + record("text_settings_dark_theme", False, + "setup_failed: main menu never appeared", + depth=1, jump_kind="value", + expect="Enable dark theme / Will update when leaving the settings screen") + return + absent = not has_text(n, "Enable dark theme") + if not and_enter_menu(n, "SETTINGS", "Settings"): + record("text_settings_dark_theme", False, + "setup_failed: could not open Settings", + depth=1, jump_kind="value", + expect="Enable dark theme / Will update when leaving the settings screen") + return + settle("tap") + s = ui() + label_ok = has_text(s, "Enable dark theme") + summ_ok = has_text(s, "Will update when leaving the settings screen") + ok = bool(absent and label_ok and summ_ok) + record("text_settings_dark_theme", ok, + "" if ok else "behavior_wrong: Settings did not produce 'Enable dark " + "theme' + its exact summary", + depth=1, jump_kind="value", + expect="Enable dark theme / Will update when leaving the settings screen") + + +@and_test(expects=("text_settings_hide_answers",)) +def test_settings_hide_answers(): + """'Hide answers' + its exact summary. Absent on main, present in Settings.""" + n = fresh_main() + if n is None: + record("text_settings_hide_answers", False, + "setup_failed: main menu never appeared", + depth=1, jump_kind="value", + expect="Hide answers / You will need to click on a button to show answers") + return + absent = not has_text(n, "Hide answers") + if not and_enter_menu(n, "SETTINGS", "Settings"): + record("text_settings_hide_answers", False, + "setup_failed: could not open Settings", + depth=1, jump_kind="value", + expect="Hide answers / You will need to click on a button to show answers") + return + settle("tap") + s = ui() + label = find_node(s, text="Hide answers") or scroll_into_view("Hide answers", 4) + summ = (find_node(ui(), text="You will need to click on a button to show answers")) + ok = bool(absent and label is not None and summ is not None) + record("text_settings_hide_answers", ok, + "" if ok else "behavior_wrong: Settings did not produce 'Hide answers' " + "+ its exact summary", + depth=1, jump_kind="value", + expect="Hide answers / You will need to click on a button to show answers") + + +@and_test(expects=("text_settings_single_button",)) +def test_settings_single_button(): + """'Single button mode' preference label. Absent on main, present in Settings.""" + n = fresh_main() + if n is None: + record("text_settings_single_button", False, + "setup_failed: main menu never appeared", + depth=1, jump_kind="value", expect="Single button mode") + return + absent = not has_text(n, "Single button mode") + if not and_enter_menu(n, "SETTINGS", "Settings"): + record("text_settings_single_button", False, + "setup_failed: could not open Settings", + depth=1, jump_kind="value", expect="Single button mode") + return + settle("tap") + s = ui() + label = find_node(s, text="Single button mode") or scroll_into_view("Single button mode", 4) + ok = bool(absent and label is not None) + record("text_settings_single_button", ok, + "" if ok else "behavior_wrong: Settings did not produce the 'Single " + "button mode' preference", + depth=1, jump_kind="value", expect="Single button mode") + + +@and_test(expects=("text_settings_keep_screen_on",)) +def test_settings_keep_screen_on(): + """'Keep screen on' + its exact summary 'Keep screen lit during tests'.""" + n = fresh_main() + if n is None: + record("text_settings_keep_screen_on", False, + "setup_failed: main menu never appeared", + depth=1, jump_kind="value", + expect="Keep screen on / Keep screen lit during tests") + return + absent = not has_text(n, "Keep screen on") + if not and_enter_menu(n, "SETTINGS", "Settings"): + record("text_settings_keep_screen_on", False, + "setup_failed: could not open Settings", + depth=1, jump_kind="value", + expect="Keep screen on / Keep screen lit during tests") + return + settle("tap") + s = ui() + label = find_node(s, text="Keep screen on") or scroll_into_view("Keep screen on", 4) + summ = find_node(ui(), text="Keep screen lit during tests") + ok = bool(absent and label is not None and summ is not None) + record("text_settings_keep_screen_on", ok, + "" if ok else "behavior_wrong: Settings did not produce 'Keep screen " + "on' + its exact summary", + depth=1, jump_kind="value", + expect="Keep screen on / Keep screen lit during tests") + + +# ══════════════════════════════════════════════════════════════════════════════ +# T6 — KanjiDisplay content labels (depth 4) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_kanji_display_readings",)) +def test_kanji_display_readings(): + """The reading section labels 'On'yomi:' / 'Kun'yomi:' / 'Definitions:' + produced on KanjiDisplay after drilling in four surfaces.""" + n = and_reach_kanji_display() + if n is None: + record("text_kanji_display_readings", False, + "setup_failed: could not reach KanjiDisplay", + depth=4, jump_kind="value", + expect="On'yomi: / Kun'yomi: / Definitions:") + return + ok = (has_text(n, "On'yomi:") and has_text(n, "Kun'yomi:") + and has_text(n, "Definitions:")) + record("text_kanji_display_readings", bool(ok), + "" if ok else "behavior_wrong: KanjiDisplay did not produce the " + "On'yomi: / Kun'yomi: / Definitions: labels", + depth=4, jump_kind="value", + expect="On'yomi: / Kun'yomi: / Definitions:") + + +@and_test(expects=("text_kanji_display_status",)) +def test_kanji_display_status(): + """The learning-status section: 'Learning status:' + the per-aspect labels + 'Reading:' / 'Meaning:' / 'Strokes:' + the status chip 'Not known' + the + 'Skip next review' action — all produced on KanjiDisplay.""" + n = and_reach_kanji_display() + if n is None: + record("text_kanji_display_status", False, + "setup_failed: could not reach KanjiDisplay", + depth=4, jump_kind="value", + expect="Learning status: / Reading: / Meaning: / Strokes: / Not known / Skip next review") + return + ok = (has_text(n, "Learning status:") and has_text(n, "Reading:") + and has_text(n, "Meaning:") and has_text(n, "Strokes:") + and has_text(n, "Not known") and has_text(n, "Skip next review")) + record("text_kanji_display_status", bool(ok), + "" if ok else "behavior_wrong: KanjiDisplay did not produce the " + "learning-status labels / 'Not known' / 'Skip next review'", + depth=4, jump_kind="value", + expect="Learning status: / Reading: / Meaning: / Strokes: / Not known / Skip next review") + + +@and_test(expects=("text_kanji_display_open_dict_desc",)) +def test_kanji_display_open_dict_desc(): + """The icon-only toolbar action carries content-desc 'Open in external + dictionary' — a produced, app-unique string that a recreation must get right.""" + n = and_reach_kanji_display() + if n is None: + record("text_kanji_display_open_dict_desc", False, + "setup_failed: could not reach KanjiDisplay", + depth=4, jump_kind="value", expect="Open in external dictionary") + return + present = find_node(n, content_desc="Open in external dictionary") is not None + record("text_kanji_display_open_dict_desc", bool(present), + "" if present else "behavior_wrong: no 'Open in external dictionary' " + "content-desc on KanjiDisplay", + depth=4, jump_kind="value", expect="Open in external dictionary") + + +# ══════════════════════════════════════════════════════════════════════════════ +# T7 — Stats heading (rule) + chart legend (the one VLM: canvas-only) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_stats_heading",)) +def test_stats_heading(): + """Opening Progress produces the dump-readable chart heading 'Questions + answered'. Absent on main, present on StatsActivity.""" + n = fresh_main() + if n is None: + record("text_stats_heading", False, + "setup_failed: main menu never appeared", + depth=1, jump_kind="value", expect="Questions answered") + return + absent = not has_text(n, "Questions answered") + if not and_enter_menu(n, "PROGRESS", "Progress"): + record("text_stats_heading", False, + "setup_failed: could not open Progress", + depth=1, jump_kind="value", expect="Questions answered") + return + settle("tap") + present = has_text(ui(), "Questions answered") + ok = bool(absent and present) + record("text_stats_heading", ok, + "" if ok else "behavior_wrong: Progress did not produce the " + "'Questions answered' heading", + depth=1, jump_kind="value", expect="Questions answered") + + +@and_test(expects=("text_stats_chart_legend_vlm",)) +def test_stats_chart_legend_vlm(): + """The chart LEGEND ('Correct answers' green swatch, 'Wrong answers' pink + swatch) is drawn on the MPAndroidChart canvas and never reaches the view tree + (confirmed: the Progress dump holds only 'Questions answered' + 'Progress'). + This is the one opaque text core in the lane. First answer a quiz question so + the chart is guaranteed non-empty, then read the rendered legend visually. + + tag='color': the question tests an exact rendered property — a GREEN legend + swatch beside the 'Correct answers' label — which a blank screen or a dump + read cannot satisfy.""" + # Produce at least one answered question so the stacked bar + legend render. + tree = and_reach_quiz("TO ROMAJI QUIZ") + if tree is not None: + n = show_answers(tree) + dk = find_node_ci(n, "DON'T KNOW") + if dk: + tap_node(dk) + settle("tap") + # Now open Progress from a clean main menu. + m = fresh_main() + if m is None or not and_enter_menu(m, "PROGRESS", "Progress"): + record("text_stats_chart_legend_vlm", False, + "setup_failed: could not open Progress for the chart legend", + depth=1, jump_kind="none", tag="color") + return + settle("tap") + vlm_assert("text_stats_chart_legend", + "In the chart legend near the bottom, is there a small GREEN " + "colored square immediately to the LEFT of the text " + "'Correct answers'?", + RESULTS_DIR, depth=1, jump_kind="none", tag="color") + + +# ══════════════════════════════════════════════════════════════════════════════ +# T8 — text-typing test: the correct-romaji string a wrong answer reveals +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_writing_correct_reveal",)) +def test_writing_correct_reveal(): + """In the Hiragana WRITING test, type a wrong romaji ('zzz') + SURE. The app + reveals the correct romaji for the shown kana as a produced string (in the + green box). We derive the exact romaji from the question kana and assert it + appears — a string the field never held (we typed 'zzz').""" + n = fresh_main() + if n is None or not and_enter_menu(n, "HIRAGANA", "Hiragana"): + record("text_writing_correct_reveal", False, + "setup_failed: could not open the Hiragana menu", + depth=2, jump_kind="value", expect="correct romaji for the shown kana") + return + settle("tap") + n = ui() + w = sub_button(n, "WRITING") + if not w or not tap_node(w): + record("text_writing_correct_reveal", False, + "setup_failed: 'HIRAGANA TO ROMAJI WRITING' button not found", + depth=2, jump_kind="value", expect="correct romaji for the shown kana") + return + and_enter("writing test") + settle("tap") + n = ui() + kana = question_kana(n) + romaji = KANA2ROMAJI.get(kana or "") + fields = find_by_class(n, "EditText") + if not romaji or not fields: + record("text_writing_correct_reveal", False, + "setup_failed: no editable field or unrecognised question kana", + depth=2, jump_kind="value", expect="correct romaji for the shown kana") + return + # 'zzz' is not a valid romaji, so the correct romaji is not on screen yet. + absent = not has_text(n, romaji) + type_text(fields[0], "zzz") + hide_keyboard() + n = ui() + sure = find_node_ci(n, "SURE") + if not sure or not tap_node(sure): + record("text_writing_correct_reveal", False, + "setup_failed: SURE button not found in the writing test", + depth=2, jump_kind="value", expect=f"correct romaji '{romaji}'") + return + settle("tap") + present = has_text(ui(), romaji) + ok = bool(absent and present) + record("text_writing_correct_reveal", ok, + "" if ok else f"behavior_wrong: wrong answer did not reveal the correct " + f"romaji '{romaji}' for kana '{kana}'", + depth=2, jump_kind="value", expect=f"correct romaji '{romaji}'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# T9 — class-selection level names + toolbar content-descs +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_class_level_names",)) +def test_class_level_names(): + """ClassSelectionActivity produces the class-level names 'JLPT level 5' and + 'Additional kanji'. Absent on the kanji menu, present on the class list.""" + n = fresh_main() + if n is None or not and_enter_menu(n, "KANJI", "Kanji"): + record("text_class_level_names", False, + "setup_failed: could not open the Kanji menu", + depth=2, jump_kind="value", expect="JLPT level 5 / Additional kanji") + return + settle("tap") + menu = ui() + absent = not has_text(menu, "JLPT level 5") + sel = find_node(menu, text="KANJI SELECTION") or find_node_ci(menu, "KANJI SELECTION") + if not sel or not tap_node(sel): + record("text_class_level_names", False, + "setup_failed: 'KANJI SELECTION' button not found", + depth=2, jump_kind="value", expect="JLPT level 5 / Additional kanji") + return + and_enter("Kanji selection") + settle("tap") + s = ui() + present = has_text(s, "JLPT level 5") and has_text(s, "Additional kanji") + ok = bool(absent and present) + record("text_class_level_names", ok, + "" if ok else "behavior_wrong: class selection did not produce the " + "'JLPT level 5' / 'Additional kanji' level names", + depth=2, jump_kind="value", expect="JLPT level 5 / Additional kanji") + + +@and_test(expects=("text_class_selection_toolbar_descs",)) +def test_class_selection_toolbar_descs(): + """The class-selection toolbar carries the icon-only content-descs 'Search' + and 'More options' — produced app-unique strings a recreation must match.""" + n = and_reach_kanji_selection() + if n is None: + record("text_class_selection_toolbar_descs", False, + "setup_failed: could not reach Kanji selection", + depth=2, jump_kind="value", expect="Search / More options") + return + present = (find_node(n, content_desc="Search") is not None + and find_node(n, content_desc="More options") is not None) + record("text_class_selection_toolbar_descs", bool(present), + "" if present else "behavior_wrong: class-selection toolbar missing the " + "'Search' / 'More options' content-descs", + depth=2, jump_kind="value", expect="Search / More options") + + +TESTS = [ + test_score_label_start, + test_score_after_correct, + test_title_hiragana, + test_title_katakana, + test_title_kanji, + test_title_vocabulary, + test_title_progress, + test_title_settings, + test_title_kanji_selection, + test_show_answers_label, + test_answer_buttons_labels, + test_next_after_wrong, + test_terminate_dialog, + test_settings_dark_theme, + test_settings_hide_answers, + test_settings_single_button, + test_settings_keep_screen_on, + test_kanji_display_readings, + test_kanji_display_status, + test_kanji_display_open_dict_desc, + test_stats_heading, + test_stats_chart_legend_vlm, + test_writing_correct_reveal, + test_class_level_names, + test_class_selection_toolbar_descs, +] + +if __name__ == "__main__": + run_suite(TESTS, "text") diff --git a/android/blastrock-kakugo/tests/test_manifest.json b/android/blastrock-kakugo/tests/test_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..fffd58875694ae569db0167c5d84e8c5bb6f1307 --- /dev/null +++ b/android/blastrock-kakugo/tests/test_manifest.json @@ -0,0 +1,697 @@ +{ + "manifest_version": 1, + "kit_api_version": 1, + "task_id": "kakugo", + "baseline_model": "claude-opus-4-8", + "baseline_package": "", + "total": 119, + "manifest_sha": "a398153427aa", + "tests": [ + { + "name": "computation::computation_hira_grid_correct_maybe_11", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_hira_grid_correct_sure_11", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_hira_grid_correct_then_wrong_12", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_hira_grid_dontknow_01", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_hira_grid_dontknow_then_correct_12", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_hira_grid_start_score_00", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_hira_grid_two_correct_22", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_hira_grid_wrong_01", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_kata_grid_correct_11", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_kata_grid_dontknow_01", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_kata_grid_two_correct_22", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_kata_writing_correct_11", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_writing_correct_11", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_writing_dontknow_01", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_writing_start_score_00", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_writing_two_correct_22", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_writing_wrong_01", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_custom_test_launch", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_dontknow_counts_wrong", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_item_persist_process_death", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_item_persist_reopen", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_item_toggle_statsbar", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_katakana_score_correct", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_lastitemrow_updates", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_multi_record_integrity", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_multi_record_integrity_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_next_advances_question", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_quiz_history_sheet", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_quiz_history_sheet_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_quiz_mixed_tally", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_quiz_multistep_tally", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_quiz_score_correct", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_quiz_score_wrong", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_quiz_score_wrong_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_singlebutton_longpress", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_wrong_lastitem_circles_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_deep_unwind", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_detail_to_itemsel", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_quiz_cancel_stays", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_submenu_to_main", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_hiragana", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_hiragana_selection", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_item_selection", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_kanji_detail", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_kanji_detail_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_kanji_menu", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_kanji_selection", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_katakana", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_progress", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_quiz", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_quiz_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_settings", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_terminate_dialog", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_vocabulary", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "states::states_checkbox_checked_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_checkbox_persist", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_checkbox_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_custom_font_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_theme_applied_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_theme_persist_processdeath", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_theme_persist_reopen", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_theme_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_hide_answers_off_consequence", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_hide_answers_on_consequence", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_hide_answers_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_keep_screen_on_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_quiz_wrong_highlight_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_show_answers_flip", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_single_button_consequence", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_single_button_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_tab_content_changes", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_tab_kanji_selected_default", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_tab_kanji_selected_default_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_tab_words_select", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_tab_words_select_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_writing_field_focused", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_wrong_answer_cells_disabled", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_wrong_answer_next_flip", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "structure::structure_classsel_overflow_delta", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_custom_test_dialog_delta", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_drawing_canvas_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_drawing_canvas_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_launch", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_hiragana_menu_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_kanji_menu_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_main_layout_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_main_six_buttons", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_quiz_grid_two_columns", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_quiz_grid_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_quiz_show_answers_delta", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_quiz_statsbar_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_pref_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_stats_chart_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_stats_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "text::text_answer_buttons_labels", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_class_level_names", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_class_selection_toolbar_descs", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_kanji_display_open_dict_desc", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_kanji_display_readings", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_kanji_display_status", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_next_after_wrong", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_score_after_correct", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_score_label_start", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_dark_theme", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_hide_answers", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_keep_screen_on", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_single_button", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_show_answers_label", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_stats_chart_legend_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_stats_heading", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_terminate_dialog", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_title_hiragana", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_title_kanji", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_title_kanji_selection", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_title_katakana", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_title_progress", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_title_settings", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_title_vocabulary", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_writing_correct_reveal", + "module": "text", + "baseline_status": "passed" + } + ], + "ignored": [], + "vlm_assertions": [ + { + "name": "interaction::interaction_multi_record_integrity_vlm", + "module": "interaction", + "tag": "color" + }, + { + "name": "interaction::interaction_quiz_score_wrong_vlm", + "module": "interaction", + "tag": "color" + }, + { + "name": "interaction::interaction_quiz_history_sheet_vlm", + "module": "interaction", + "tag": "color" + }, + { + "name": "interaction::interaction_wrong_lastitem_circles_vlm", + "module": "interaction", + "tag": "color" + }, + { + "name": "navigation::nav_reach_quiz_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_reach_kanji_detail_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "states::states_dark_theme_applied_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_quiz_wrong_highlight_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_tab_kanji_selected_default_vlm", + "module": "states", + "tag": "position" + }, + { + "name": "states::states_tab_words_select_vlm", + "module": "states", + "tag": "position" + }, + { + "name": "states::states_checkbox_checked_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "structure::structure_main_layout_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_quiz_grid_vlm", + "module": "structure", + "tag": "shape" + }, + { + "name": "structure::structure_stats_chart_vlm", + "module": "structure", + "tag": "color" + }, + { + "name": "structure::structure_drawing_canvas_vlm", + "module": "structure", + "tag": "shape" + }, + { + "name": "structure::structure_quiz_statsbar_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "text::text_stats_chart_legend_vlm", + "module": "text", + "tag": "color" + } + ], + "vlm_total": 17, + "n_vlm_unverified": 0, + "vlm_log_found": true +} \ No newline at end of file diff --git a/android/blastrock-kakugo/vlm_assertions.json b/android/blastrock-kakugo/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..fe7e717eb1b14d30485cb32f332b7f6a719c31a2 --- /dev/null +++ b/android/blastrock-kakugo/vlm_assertions.json @@ -0,0 +1,454 @@ +{ + "schema_version": 2, + "instance_id": "android/blastrock-kakugo", + "grading": { + "mode": "inline", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 22, + "with_verdict": 20, + "calibrated": 0, + "usable": null, + "scored_records": 20, + "unbacked_records": 3, + "unbacked_sample": [ + "smoke_a_vlm", + "smoke_b_vlm", + "smoke_c_vlm" + ] + }, + "assertions": [ + { + "id": "structure_main_layout_vlm", + "screenshot": "structure_main_layout_vlm.png", + "assertion": "Is there a vertical stack of six full-width rectangular buttons that fill the width of the screen, one below another, with a title/logo area above them?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "structure_main_layout", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_quiz_grid_vlm", + "screenshot": "structure_quiz_grid_vlm.png", + "assertion": "Are the answer options arranged as a grid of two side-by-side columns, where each option shows a 'SURE' button and a 'MAYBE' button?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "structure_quiz_grid", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_stats_chart_vlm", + "screenshot": "structure_stats_chart_vlm.png", + "assertion": "Below the 'Questions answered' heading, is a bar chart rendered with one or more coloured vertical bars (not an empty area and not only text)?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "structure_stats_chart", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_drawing_canvas_vlm", + "screenshot": "structure_drawing_canvas_vlm.png", + "assertion": "Is there a large empty white square drawing area filling most of the middle of the screen, positioned above a row containing a 'HINT' button and a \"DON'T KNOW\" button?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "structure_drawing_canvas", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_quiz_statsbar_vlm", + "screenshot": "structure_quiz_statsbar_vlm.png", + "assertion": "Near the very top of the screen, is there a thin coloured horizontal status bar, with the text 'Session score' shown directly below it?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_quiz_statsbar", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_quiz_vlm", + "screenshot": "nav_reach_quiz_vlm.png", + "assertion": "Is there a left-pointing back arrow icon at the very top-left corner of this screen, to the left of the title text?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_reach_quiz", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_kanji_detail_vlm", + "screenshot": "nav_reach_kanji_detail_vlm.png", + "assertion": "Near the top of this screen, are there two side-by-side tab labels reading 'Kanji' (left) and 'Words' (right)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_reach_kanji_detail", + "rigor": { + "jump_kind": "none", + "depth": 4 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_multi_record_integrity_vlm", + "screenshot": "interaction_multi_record_integrity_vlm.png", + "assertion": "Look at the thin horizontal status bar directly under the blue toolbar. Is it split into TWO differently coloured segments (a wide coloured segment and a separate smaller segment of a different colour), rather than being one single solid colour?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "interaction_multi_record_integrity", + "rigor": { + "jump_kind": "transition", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_quiz_score_wrong_vlm", + "screenshot": "interaction_quiz_score_wrong_vlm.png", + "assertion": "In the answer grid, exactly one answer cell has a PINK/RED background and exactly one other answer cell has a GREEN background (the rest are white). Is that the case?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "interaction_quiz_score_wrong", + "rigor": { + "jump_kind": "value", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_quiz_history_sheet_vlm", + "screenshot": "interaction_quiz_history_sheet_vlm.png", + "assertion": "A history panel is shown listing answered items. Is each answered item shown as a small ROUND coloured circle (green and/or pink/red) next to its romaji text?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "interaction_quiz_history_sheet", + "rigor": { + "jump_kind": "transition", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_drawing_ink_vlm", + "screenshot": "interaction_drawing_ink_vlm.png", + "assertion": "Look at the large white drawing box between the big grey letters at the top and the HINT / DON'T KNOW buttons at the bottom. Does it contain visible DARK ink strokes/marks (i.e. it is no longer a completely blank white box)?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "interaction_drawing_ink", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "interaction_wrong_lastitem_circles_vlm", + "screenshot": "interaction_wrong_lastitem_circles_vlm.png", + "assertion": "Look ONLY at the thin strip along the very BOTTOM of the screen (below the answer grid and the NEXT button). Does it show two small ROUND coloured circles side by side — one PINK/RED and one GREEN — each containing a Japanese character?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "interaction_wrong_lastitem_circles", + "rigor": { + "jump_kind": "value", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_dark_theme_applied_vlm", + "screenshot": "states_dark_theme_applied_vlm.png", + "assertion": "Is the background of this screen dark (near-black or very dark) with light-colored (white) text and dark button cards?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_dark_theme_applied", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_quiz_wrong_highlight_vlm", + "screenshot": "states_quiz_wrong_highlight_vlm.png", + "assertion": "In the answer grid, is exactly one answer cell highlighted with a green background and a different cell highlighted with a red or pink background?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_quiz_wrong_highlight", + "rigor": { + "jump_kind": "value", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_tab_kanji_selected_default_vlm", + "screenshot": "states_tab_kanji_selected_default_vlm.png", + "assertion": "Near the top there are two tabs, 'Kanji' on the LEFT and 'Words' on the RIGHT. Is the LEFT 'Kanji' tab the selected one (highlighted or underlined) rather than 'Words'?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "states_tab_kanji_selected_default", + "rigor": { + "jump_kind": "value", + "depth": 4 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_tab_words_select_vlm", + "screenshot": "states_tab_words_select_vlm.png", + "assertion": "Near the top there are two tabs, 'Kanji' on the LEFT and 'Words' on the RIGHT. Is the RIGHT 'Words' tab now the selected one (the highlight/underline indicator is under 'Words')?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "states_tab_words_select", + "rigor": { + "jump_kind": "transition", + "depth": 4 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_checkbox_toggle_vlm", + "screenshot": "states_checkbox_toggle_vlm.png", + "assertion": "On the left of each list row there are checkboxes. Are they filled / checked (a filled box with a checkmark) rather than empty outlines?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_checkbox_toggle", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_checkbox_checked_vlm", + "screenshot": "states_checkbox_checked_vlm.png", + "assertion": "On the left of each list row there are checkboxes. Are they filled / checked (a filled box with a checkmark) rather than empty outlines?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_checkbox_checked", + "rigor": { + "jump_kind": "transition", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_stats_chart_legend_vlm", + "screenshot": "text_stats_chart_legend_vlm.png", + "assertion": "In the chart legend near the bottom, is there a small GREEN colored square immediately to the LEFT of the text 'Correct answers'?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "text_stats_chart_legend", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "smoke_a_vlm", + "screenshot": "smoke_a_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "smoke_a", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "smoke_b_vlm", + "screenshot": "smoke_b_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "smoke_b", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": false, + "passed": false, + "raw": null + }, + "calibration": null + }, + { + "id": "smoke_c_vlm", + "screenshot": "smoke_c_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "smoke_c", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": false, + "passed": false, + "raw": null + }, + "calibration": null + } + ], + "merged_from_files": 1, + "source_shapes": { + "list": 1 + } +} \ No newline at end of file diff --git a/android/brodeurlv-fastnfitness/LICENSE b/android/brodeurlv-fastnfitness/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..fa2464c70d29030f54d7d925e4090c090a617a50 --- /dev/null +++ b/android/brodeurlv-fastnfitness/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2019-2020, Charles Combes +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/android/brodeurlv-fastnfitness/instance.json b/android/brodeurlv-fastnfitness/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..cf7eaf7965c15e6011bdde8db4e3a53d990f1d25 --- /dev/null +++ b/android/brodeurlv-fastnfitness/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "android/brodeurlv-fastnfitness", + "platform": "android", + "repo": "https://github.com/brodeurlv/fastnfitness", + "commit": "27935ec232f1a46577e9099511bab634c1aaf719", + "patches": [], + "package": "com.easyfitness.debug", + "license": null +} diff --git a/android/brodeurlv-fastnfitness/reference/launch.sh b/android/brodeurlv-fastnfitness/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8 --- /dev/null +++ b/android/brodeurlv-fastnfitness/reference/launch.sh @@ -0,0 +1,9 @@ +#!/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 1 diff --git a/android/brodeurlv-fastnfitness/tests/android_computation_eval.json b/android/brodeurlv-fastnfitness/tests/android_computation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..213b44ea79af9ec8210819fe43559bc8e08d105f --- /dev/null +++ b/android/brodeurlv-fastnfitness/tests/android_computation_eval.json @@ -0,0 +1,131 @@ +{ + "module": "computation", + "total": 11, + "passed": 11, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 11, + "passed": 11, + "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": 11, + "depth_ge1": 1, + "depth_ge2": 0, + "value": 11, + "vlm_fine": 0 + }, + "results": [ + { + "test": "computation_add_reps_3", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "top REPETITION_CELL == 3" + }, + { + "test": "computation_add_reps_7", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "top REPETITION_CELL == 7" + }, + { + "test": "computation_add_reps_12", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "top REPETITION_CELL == 12" + }, + { + "test": "computation_add_reps_15", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "top REPETITION_CELL == 15" + }, + { + "test": "computation_add_sets_2", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "top SERIE_CELL == 2" + }, + { + "test": "computation_add_sets_4", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "top SERIE_CELL == 4" + }, + { + "test": "computation_add_sets_5", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "top SERIE_CELL == 5" + }, + { + "test": "computation_add_weight_80", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "top POIDS_CELL == 80lb" + }, + { + "test": "computation_add_weight_88", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "top POIDS_CELL == 88lb" + }, + { + "test": "computation_add_weight_125", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "top POIDS_CELL == 125lb" + }, + { + "test": "computation_editor_reps_9", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "top REPETITION_CELL 3->9" + } + ] +} \ No newline at end of file diff --git a/android/brodeurlv-fastnfitness/tests/android_interaction_eval.json b/android/brodeurlv-fastnfitness/tests/android_interaction_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..360e5ecc8ecf0ab5f4354f944cb3c8065121832a --- /dev/null +++ b/android/brodeurlv-fastnfitness/tests/android_interaction_eval.json @@ -0,0 +1,236 @@ +{ + "module": "interaction", + "total": 22, + "passed": 22, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 16, + "passed": 16, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 6, + "passed": 6, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.375, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 22, + "depth_ge1": 12, + "depth_ge2": 0, + "value": 19, + "vlm_fine": 4 + }, + "results": [ + { + "test": "interaction_create_reps", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "top REPETITION_CELL=731, count 0->1" + }, + { + "test": "interaction_create_reps_vlm", + "passed": true, + "message": "VLM: Q='In the list of workout records under the date header, is the very first (top) record row showing the repetitions value 731?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In the list of workout records under the date header, is the very first (top) record row showing the repetitions value 731?", + "tag": "position" + }, + { + "test": "interaction_create_sets", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "top SERIE_CELL=6" + }, + { + "test": "interaction_create_count_grows", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "REPETITION_CELL 732 count 0->1" + }, + { + "test": "interaction_update_reps_vlm", + "passed": true, + "message": "VLM: Q='Is a modal editor dialog (a card titled 'Record Editor' with input fields and UPDATE / CANCEL buttons) shown centered on top of the screen, overlaying the record list behind it?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Is a modal editor dialog (a card titled 'Record Editor' with input fields and UPDATE / CANCEL buttons) shown centered on top of the screen, overlaying the record list behind it?", + "tag": "shape" + }, + { + "test": "interaction_update_reps", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "top REPETITION_CELL 751->752" + }, + { + "test": "interaction_update_weight", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "top POIDS_CELL starts with '75'" + }, + { + "test": "interaction_update_cancel_unchanged", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "REPETITION_CELL stays 761 after CANCEL" + }, + { + "test": "interaction_multi_two_records", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "both 941 and 942 counts +1" + }, + { + "test": "interaction_multi_stack_vlm", + "passed": true, + "message": "VLM: Q='In the workout record list, are there at least three record rows stacked vertically one below another, each showing a sets / reps / weight value block on its right side?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In the workout record list, are there at least three record rows stacked vertically one below another, each showing a sets / reps / weight value block on its right side?", + "tag": "layout" + }, + { + "test": "interaction_multi_edit_middle_keeps_others", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "top3 == [943, 944, 941]" + }, + { + "test": "interaction_seq_machine_then_reps", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "top MACHINE_CELL='Example 1' & REPETITION_CELL=733" + }, + { + "test": "interaction_create_then_edit_sequence", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "top REPETITION_CELL 781->782" + }, + { + "test": "interaction_two_identical_adds", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "REPETITION_CELL 791 count 0->2" + }, + { + "test": "interaction_persist_across_kill", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "REPETITION_CELL 734 count 0->1 and survives relaunch" + }, + { + "test": "interaction_persist_second_record", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "top row reps=735/sets=5 after relaunch" + }, + { + "test": "interaction_record_in_history", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "HISTORY REPETITION_CELL contains 771" + }, + { + "test": "interaction_record_in_history_vlm", + "passed": true, + "message": "VLM: Q='Is the HISTORY tab currently selected and showing a vertical list of workout record cards (each with an exercise name and sets/reps/weight values)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Is the HISTORY tab currently selected and showing a vertical list of workout record cards (each with an exercise name and sets/reps/weight values)?", + "tag": "position" + }, + { + "test": "interaction_history_filter_machine", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "HISTORY list -> all 'Example 1', none 'Example 2'" + }, + { + "test": "interaction_history_filter_vlm", + "passed": true, + "message": "VLM: Q='In this filtered history list, does every visible record row show the SAME exercise name ('Example 1'), with no other exercise names present?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In this filtered history list, does every visible record row show the SAME exercise name ('Example 1'), with no other exercise names present?", + "tag": "content" + }, + { + "test": "interaction_exercise_search_filter", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "listMachine shows only 'Example 1' after search" + }, + { + "test": "interaction_card_action_icons_vlm", + "passed": true, + "message": "VLM: Q='Does each workout record row show a row of small action icons (copy, edit and delete) on its right-hand side?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Does each workout record row show a row of small action icons (copy, edit and delete) on its right-hand side?", + "tag": "position" + } + ] +} \ No newline at end of file diff --git a/android/brodeurlv-fastnfitness/tests/android_navigation_eval.json b/android/brodeurlv-fastnfitness/tests/android_navigation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..948c2aac2a2e977ace704f858835b00f6de249f2 --- /dev/null +++ b/android/brodeurlv-fastnfitness/tests/android_navigation_eval.json @@ -0,0 +1,289 @@ +{ + "module": "navigation", + "total": 28, + "passed": 28, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 23, + "passed": 23, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 5, + "passed": 5, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.2174, + "audit": { + "kit_api_version": 1, + "existence": 5, + "liveness": 0, + "interactive": 23, + "depth_ge1": 23, + "depth_ge2": 10, + "value": 0, + "vlm_fine": 4 + }, + "results": [ + { + "test": "nav_reach_exercises", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "'ADD NEW EXERCISE' button appeared; Workout WorkoutValuesInput gone; title 'Exercises'" + }, + { + "test": "nav_reach_program_list", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "listWorkout list + 'NEW PROGRAM' appeared; Workout WorkoutValuesInput gone; title 'Program List'" + }, + { + "test": "nav_reach_weight_track", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "activityLevelSpinner + weightDetailsButton (DETAILS) appeared; Workout WorkoutValuesInput gone" + }, + { + "test": "nav_reach_weight_widgets_vlm", + "passed": true, + "message": "VLM: Q='Are there four cards arranged in a two-by-two grid, labelled 'Weight', 'Fat', 'Muscles' and 'Water', each with a 'DETAILS' button at its bottom?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Are there four cards arranged in a two-by-two grid, labelled 'Weight', 'Fat', 'Muscles' and 'Water', each with a 'DETAILS' button at its bottom?", + "tag": "position" + }, + { + "test": "nav_reach_body_track", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "listBodyMeasures list + title 'Body Track' appeared; Workout WorkoutValuesInput gone" + }, + { + "test": "nav_reach_progress_images", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "currentProgressImage + progressImageIndex ('1 / 0') + NEWER/OLDER appeared; Workout WorkoutValuesInput gone" + }, + { + "test": "nav_reach_settings", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "'Unit System' section + Settings recycler_view appeared; Workout WorkoutValuesInput gone" + }, + { + "test": "nav_reach_about_drawer", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "'Libraries used in this app:' + library rows appeared; Workout WorkoutValuesInput gone" + }, + { + "test": "nav_reach_about_credits_vlm", + "passed": true, + "message": "VLM: Q='Does this screen show a scrollable list of library/credit rows, each a library name followed by its licence in parentheses (e.g. 'Apache 2.0')?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does this screen show a scrollable list of library/credit rows, each a library name followed by its licence in parentheses (e.g. 'Apache 2.0')?", + "tag": "layout" + }, + { + "test": "nav_reach_workout_from_drawer", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "From Program List: WorkoutValuesInput reappeared and listWorkout disappeared after tapping drawer 'Workout'" + }, + { + "test": "nav_tab_program", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "'START PROGRAM' button + 'Program preview:' appeared; FREE WORKOUT's WorkoutValuesInput gone" + }, + { + "test": "nav_tab_program_vlm", + "passed": true, + "message": "VLM: Q='Is a wide 'START PROGRAM' button shown in the content area below a row of tabs, with the 'PROGRAM' tab highlighted?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a wide 'START PROGRAM' button shown in the content area below a row of tabs, with the 'PROGRAM' tab highlighted?", + "tag": "position" + }, + { + "test": "nav_tab_graphs", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "graphLineChart + zoom buttons (ALL/LAST YEAR) appeared; FREE WORKOUT's WorkoutValuesInput gone" + }, + { + "test": "nav_tab_graphs_chart_vlm", + "passed": true, + "message": "VLM: Q='Is a line chart with plotted data points/lines rendered in the content area of this screen?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a line chart with plotted data points/lines rendered in the content area of this screen?", + "tag": "shape" + }, + { + "test": "nav_tab_history", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "listFilterRecord + filterMachine appeared; FREE WORKOUT's WorkoutValuesInput gone" + }, + { + "test": "nav_tab_back_to_free_workout", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "From PROGRAM: WorkoutValuesInput reappeared and START PROGRAM disappeared on FREE WORKOUT" + }, + { + "test": "nav_exercise_detail", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Exercise Detail: machine_photo + EXERCISE/HISTORY tab host + favButton appeared; 'ADD NEW EXERCISE' gone" + }, + { + "test": "nav_exercise_detail_affordance_vlm", + "passed": true, + "message": "VLM: Q='Does the top toolbar of this screen show a star (favourite) icon and a trash/delete (bin) icon?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does the top toolbar of this screen show a star (favourite) icon and a trash/delete (bin) icon?", + "tag": "shape" + }, + { + "test": "nav_exercise_detail_back", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "After one BACK: Exercises addExercise restored, detail favButton gone" + }, + { + "test": "nav_exercise_history_subtab", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "listFilterRecord appeared; EXERCISE-tab machine_description gone" + }, + { + "test": "nav_weight_metric_detail", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Metric detail: bodymeasureChart + 'Measurement history:' appeared; Weight-Track activityLevelSpinner gone" + }, + { + "test": "nav_weight_metric_back", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "After one BACK: weightDetailsButton restored, bodymeasureChart gone" + }, + { + "test": "nav_bodypart_detail", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Body-part detail: bodymeasureChart + 'Measurement history:' appeared; Body-Track listBodyMeasures gone" + }, + { + "test": "nav_bodypart_back", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "After one BACK: addBodyPart restored, bodymeasureChart gone" + }, + { + "test": "nav_profile_page", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Popup 'Profile page' item appeared; then editor gender/birthday/size appeared, popup 'Change profile' gone" + }, + { + "test": "nav_reach_about_overflow", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "From overflow: 'Libraries used in this app:' appeared; menu 'Reset app' item gone" + }, + { + "test": "nav_program_editor", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Editor: program_pagertab (EDITOR/INFO) + workout_name appeared; START PROGRAM gone" + }, + { + "test": "nav_program_editor_back", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "After one BACK: startStopProgram restored, program_pagertab (editor) gone" + } + ] +} \ No newline at end of file diff --git a/android/brodeurlv-fastnfitness/tests/android_states_eval.json b/android/brodeurlv-fastnfitness/tests/android_states_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1dc90d34758152cdbc0e5b8ef5f1d9c17a3153 --- /dev/null +++ b/android/brodeurlv-fastnfitness/tests/android_states_eval.json @@ -0,0 +1,285 @@ +{ + "module": "states", + "total": 27, + "passed": 27, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 17, + "passed": 17, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 10, + "passed": 10, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.5882, + "audit": { + "kit_api_version": 1, + "existence": 10, + "liveness": 0, + "interactive": 17, + "depth_ge1": 8, + "depth_ge2": 0, + "value": 2, + "vlm_fine": 9 + }, + "results": [ + { + "test": "states_resttime_checkbox_dialog", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "restTimeCheckBox checked=true; ADD opens Rest-time dialog (chronoValue present)" + }, + { + "test": "states_resttime_checkbox_dialog_vlm", + "passed": true, + "message": "VLM: Q='Is a large circular progress ring (a grey circle with a coloured arc segment) drawn around a mm:ss countdown time in the centre of the screen?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a large circular progress ring (a grey circle with a coloured arc segment) drawn around a mm:ss countdown time in the centre of the screen?", + "tag": "shape" + }, + { + "test": "states_resttime_unchecked_no_dialog", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "restTimeCheckBox checked=false; ADD adds inline, no countdown dialog, still on Workout home" + }, + { + "test": "states_countdown_decreases", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "chronoValue counts down (observed 54s -> lower after ~3s)" + }, + { + "test": "states_countdown_decreases_vlm", + "passed": true, + "message": "VLM: Q='Is the coloured progress arc a BLUE segment sitting on a grey circular ring near the top of the donut?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is the coloured progress arc a BLUE segment sitting on a grey circular ring near the top of the donut?", + "tag": "color" + }, + { + "test": "states_settings_audio_persists", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Show Audio Player checked false->true and still that after restart" + }, + { + "test": "states_settings_beep_toggle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Beep checked true->false" + }, + { + "test": "states_settings_beep_toggle_vlm", + "passed": true, + "message": "VLM: Q='In this Settings list, is the 'Beep' row's control a small square checkbox (checked ones show a filled square with a white tick)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In this Settings list, is the 'Beep' row's control a small square checkbox (checked ones show a filled square with a white tick)?", + "tag": "shape" + }, + { + "test": "states_weight_unit_persists_vlm", + "passed": true, + "message": "VLM: Q='In this pop-up unit chooser (options kg, lb, st), is exactly ONE option marked with a filled/solid coloured radio button while the others show empty circular outlines?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In this pop-up unit chooser (options kg, lb, st), is exactly ONE option marked with a filled/solid coloured radio button while the others show empty circular outlines?", + "tag": "shape" + }, + { + "test": "states_weight_unit_persists", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Weight summary contains 'lb' after pick and after restart" + }, + { + "test": "states_activity_level_persists", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "activityLevelSpinner shows 'active' after pick and after restart" + }, + { + "test": "states_graph_function_spinner", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "filterGraphFunction label 'Reps Sum' -> 'Weight Sum'" + }, + { + "test": "states_graph_function_spinner_vlm", + "passed": true, + "message": "VLM: Q='Is a line/point chart with visible axes rendered in the main area of this GRAPHS screen, positioned below the two dropdown filters?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a line/point chart with visible axes rendered in the main area of this GRAPHS screen, positioned below the two dropdown filters?", + "tag": "position" + }, + { + "test": "states_history_filter_spinner", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "filterMachine label 'All' -> 'Example 1'" + }, + { + "test": "states_unit_spinner_label", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "unit spinner label 'lb' -> 'kg'" + }, + { + "test": "states_tab_selected", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "GRAPHS selected false->true; FREE WORKOUT true->false" + }, + { + "test": "states_tab_selected_vlm", + "passed": true, + "message": "VLM: Q='In the tab strip (FREE WORKOUT / PROGRAM / GRAPHS / HISTORY), is a coloured underline indicator positioned directly beneath the GRAPHS tab (and not under FREE WORKOUT)?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the tab strip (FREE WORKOUT / PROGRAM / GRAPHS / HISTORY), is a coloured underline indicator positioned directly beneath the GRAPHS tab (and not under FREE WORKOUT)?", + "tag": "position" + }, + { + "test": "states_tab_history_selected", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "HISTORY selected false->true; FREE WORKOUT no longer selected" + }, + { + "test": "states_tab_history_selected_vlm", + "passed": true, + "message": "VLM: Q='Is the coloured underline indicator in the tab strip positioned beneath the HISTORY tab?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is the coloured underline indicator in the tab strip positioned beneath the HISTORY tab?", + "tag": "position" + }, + { + "test": "states_focus_reps_field", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Reps EditText focused false->true; Sets & Weight stay false" + }, + { + "test": "states_favorite_toggle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "favorite star tapped; icon box changes (fills to a solid star)" + }, + { + "test": "states_checkbox_checked_visual", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "restTimeCheckBox checked=true" + }, + { + "test": "states_checkbox_checked_visual_vlm", + "passed": true, + "message": "VLM: Q='Next to the 'Activate rest countdown' label, is the checkbox a filled coloured (teal/green) square containing a white check-mark?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Next to the 'Activate rest countdown' label, is the checkbox a filled coloured (teal/green) square containing a white check-mark?", + "tag": "color" + }, + { + "test": "states_settings_vibration_toggle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Vibration checked true->false" + }, + { + "test": "states_settings_vibration_toggle_vlm", + "passed": true, + "message": "VLM: Q='In this Settings list, does the 'Rest Timer Settings' section show small square checkbox controls on the right of the Beep and Vibration rows?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In this Settings list, does the 'Rest Timer Settings' section show small square checkbox controls on the right of the Beep and Vibration rows?", + "tag": "shape" + }, + { + "test": "states_activity_spinner_change_vlm", + "passed": true, + "message": "VLM: Q='Is an open dropdown/list of selectable text options (such as sedentary, moderate, active) currently displayed on top of the screen?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is an open dropdown/list of selectable text options (such as sedentary, moderate, active) currently displayed on top of the screen?", + "tag": "layout" + }, + { + "test": "states_activity_spinner_change", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "activityLevelSpinner label 'sedentary' -> 'active'" + } + ] +} \ No newline at end of file diff --git a/android/brodeurlv-fastnfitness/tests/android_structure_eval.json b/android/brodeurlv-fastnfitness/tests/android_structure_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..fb60b8723119ff19235cc3babc48454ee4bc4be0 --- /dev/null +++ b/android/brodeurlv-fastnfitness/tests/android_structure_eval.json @@ -0,0 +1,238 @@ +{ + "module": "structure", + "total": 22, + "passed": 22, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 14, + "passed": 14, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 8, + "passed": 8, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.5714, + "audit": { + "kit_api_version": 1, + "existence": 2, + "liveness": 0, + "interactive": 20, + "depth_ge1": 14, + "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_tabstrip_vlm", + "passed": true, + "message": "VLM: Q='Near the top of the screen, are the four tab labels FREE WORKOUT, PROGRAM, GRAPHS and HISTORY arranged side by side in a single horizontal row (not stacked vertically)?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Near the top of the screen, are the four tab labels FREE WORKOUT, PROGRAM, GRAPHS and HISTORY arranged side by side in a single horizontal row (not stacked vertically)?", + "tag": "position" + }, + { + "test": "structure_tab_free_to_program", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "EditText 4->0 on PROGRAM, restored to 4 on FREE WORKOUT" + }, + { + "test": "structure_tab_free_to_graphs", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "EditText 4->0 and graphLineChart appears on GRAPHS" + }, + { + "test": "structure_graphs_chart_vlm", + "passed": true, + "message": "VLM: Q='Does the main area of this screen show a line/point chart plotted on X and Y axes (a graph), rather than a form with text input fields?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Does the main area of this screen show a line/point chart plotted on X and Y axes (a graph), rather than a form with text input fields?", + "tag": "shape" + }, + { + "test": "structure_tab_free_to_history", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Spinner 1->2 (2 filters) and listFilterRecord on HISTORY" + }, + { + "test": "structure_tab_program_to_graphs", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "PROGRAM->GRAPHS: startStopProgram gone, graphLineChart present" + }, + { + "test": "structure_expand_arrow_toggles", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "details card toggle flips CheckBox count by 1 and restores" + }, + { + "test": "structure_drawer_opens", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "left_drawer ListView + >=6 item labels appear (absent on fresh launch)" + }, + { + "test": "structure_drawer_position_vlm", + "passed": true, + "message": "VLM: Q='Is a navigation menu panel overlaying the LEFT side of the screen (a vertical list of menu items anchored to the left edge, with the right side dimmed)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is a navigation menu panel overlaying the LEFT side of the screen (a vertical list of menu items anchored to the left edge, with the right side dimmed)?", + "tag": "position" + }, + { + "test": "structure_add_opens_dialog", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "rest-time modal adds chronoValue+donut_progress, gone on BACK" + }, + { + "test": "structure_rest_donut_vlm", + "passed": true, + "message": "VLM: Q='Is there a dialog showing a large circular progress ring (a donut/circle shape) with a countdown time in its center?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is there a dialog showing a large circular progress ring (a donut/circle shape) with a countdown time in its center?", + "tag": "shape" + }, + { + "test": "structure_editbutton_opens_editor", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Record Editor modal adds btn_update, removed on BACK" + }, + { + "test": "structure_editor_dialog_vlm", + "passed": true, + "message": "VLM: Q='Is a dialog box open in the CENTER of the screen showing numeric input fields, with CANCEL and UPDATE buttons in a row at the BOTTOM of the dialog?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is a dialog box open in the CENTER of the screen showing numeric input fields, with CANCEL and UPDATE buttons in a row at the BOTTOM of the dialog?", + "tag": "position" + }, + { + "test": "structure_machine_picker_dialog", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "exercise-picker modal adds listMachine list, gone on BACK" + }, + { + "test": "structure_drawer_exercises_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "content becomes listMachine + addExercise; workout ADD gone" + }, + { + "test": "structure_exercises_rows_vlm", + "passed": true, + "message": "VLM: Q='In this list, does each row place a small image/thumbnail on the LEFT edge and a star icon on the RIGHT edge, with the exercise name between them?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In this list, does each row place a small image/thumbnail on the LEFT edge and a star icon on the RIGHT edge, with the exercise name between them?", + "tag": "position" + }, + { + "test": "structure_drawer_weight_track_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "content shows 5 metric inputs + BMI index block; ADD FAB" + }, + { + "test": "structure_weight_cards_vlm", + "passed": true, + "message": "VLM: Q='Does this screen present multiple separate rectangular metric cards (for example Weight, Fat, Muscles, Water) stacked as panels?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Does this screen present multiple separate rectangular metric cards (for example Weight, Fat, Muscles, Water) stacked as panels?", + "tag": "layout" + }, + { + "test": "structure_drawer_settings_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "content becomes a preference recycler_view; workout ADD gone" + }, + { + "test": "structure_settings_list_vlm", + "passed": true, + "message": "VLM: Q='Is this screen a vertically scrolling list of settings/preference rows, each with a title and a smaller summary line beneath it?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is this screen a vertically scrolling list of settings/preference rows, each with a title and a smaller summary line beneath it?", + "tag": "layout" + }, + { + "test": "structure_drawer_body_track_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "content becomes listBodyMeasures + ADD; workout ADD gone" + } + ] +} \ No newline at end of file diff --git a/android/brodeurlv-fastnfitness/tests/android_testgen_kit.py b/android/brodeurlv-fastnfitness/tests/android_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6 --- /dev/null +++ b/android/brodeurlv-fastnfitness/tests/android_testgen_kit.py @@ -0,0 +1,1910 @@ +#!/usr/bin/env python3 +"""Android TestGen Kit — the single source of every test helper, so a test's +NAVIGATION 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 package +name differs): always use the module-level PACKAGE (argv[1]). Never write a package +name, an .apk path, a /data/data path, or a pixel coordinate as a literal. + python3 android_testgen_kit.py lint_sources # flags all of those + +SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery): + python3 android_testgen_kit.py audit + python3 android_testgen_kit.py lint + python3 android_testgen_kit.py lint_sources + python3 android_testgen_kit.py audit_depth [results_dir] +""" +from __future__ import annotations + +import ast +import base64 +import functools +import glob +import hashlib +import json +import math +import os +import re +import shlex +import subprocess +import sys +import time +import urllib.error +import 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.0 +SETTLE = { + "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 /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 " list[dict]: + """XML -> list of attribute dicts, each with _bounds and _center.""" + nodes = [] + for m in re.finditer(r"]+?)/?>", 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} \n" + " android_testgen_kit.py audit_depth [results_dir]\n" + " android_testgen_kit.py score [manifest_dir]") diff --git a/android/brodeurlv-fastnfitness/tests/android_text_eval.json b/android/brodeurlv-fastnfitness/tests/android_text_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..312de220aed59e19e8433503438a3324f195f36a --- /dev/null +++ b/android/brodeurlv-fastnfitness/tests/android_text_eval.json @@ -0,0 +1,223 @@ +{ + "module": "text", + "total": 21, + "passed": 21, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 19, + "passed": 19, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 2, + "passed": 2, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.1053, + "audit": { + "kit_api_version": 1, + "existence": 5, + "liveness": 0, + "interactive": 16, + "depth_ge1": 13, + "depth_ge2": 0, + "value": 0, + "vlm_fine": 1 + }, + "results": [ + { + "test": "text_title_workout", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "toolbar title 'Fast N Fitness Debug'" + }, + { + "test": "text_title_exercises", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "toolbar title 'Exercises'" + }, + { + "test": "text_title_weight_track", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "toolbar title 'Weight Track'" + }, + { + "test": "text_title_body_track", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "toolbar title 'Body Track'" + }, + { + "test": "text_title_settings", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "toolbar title 'Settings'" + }, + { + "test": "text_title_about", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "toolbar title 'About'" + }, + { + "test": "text_program_empty", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "listProgramEmpty 'This program is empty'" + }, + { + "test": "text_program_preview_title", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "programListTitle 'Program preview:'" + }, + { + "test": "text_settings_unit_summaries", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "summaries 'Preferred unit: kg/km/cm'" + }, + { + "test": "text_settings_section_header", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "section headers 'Unit System' + 'UI Settings'" + }, + { + "test": "text_workout_comment_range", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "comment reads 'Min:lb - Max:lb'" + }, + { + "test": "text_weight_no_data", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "imcViewText 'no weight available'" + }, + { + "test": "text_about_library_rows", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "rows 'MPAndroidChart' + 'SmartTabLayout' + 'SweetAlertDialog'" + }, + { + "test": "text_about_db_label", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "labels 'Database version:' + 'Libraries used in this app:'" + }, + { + "test": "text_about_heading", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "About heading 'Fast N Fitness Debug'" + }, + { + "test": "text_added_record_name", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "new record MACHINE_CELL reads 'Example 2'" + }, + { + "test": "text_exercises_hint", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "searchField hint 'Filter by exercise name'" + }, + { + "test": "text_exercises_filter_result", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "filtered LIST_MACHINE_NAME == ['Example 1']" + }, + { + "test": "text_tab_labels", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "tabs 'FREE WORKOUT' 'PROGRAM' 'GRAPHS' 'HISTORY'" + }, + { + "test": "text_chart_axis_label_vlm", + "passed": true, + "message": "VLM: Q='In the line-chart area, is the label text 'Example 2/Weight Sum(kg)' drawn near the bottom-right corner of the chart, just above the axis?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the line-chart area, is the label text 'Example 2/Weight Sum(kg)' drawn near the bottom-right corner of the chart, just above the axis?", + "tag": "content" + }, + { + "test": "text_chart_date_ticks_vlm", + "passed": true, + "message": "VLM: Q='Along the horizontal axis at the BOTTOM of the line chart, are abbreviated calendar date labels shown (for example '18-May', '22-Jun', '27-Jul')?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Along the horizontal axis at the BOTTOM of the line chart, are abbreviated calendar date labels shown (for example '18-May', '22-Jun', '27-Jul')?", + "tag": "position" + } + ] +} \ No newline at end of file diff --git a/android/brodeurlv-fastnfitness/tests/conftest.py b/android/brodeurlv-fastnfitness/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27 --- /dev/null +++ b/android/brodeurlv-fastnfitness/tests/conftest.py @@ -0,0 +1 @@ +pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"] diff --git a/android/brodeurlv-fastnfitness/tests/requirements.txt b/android/brodeurlv-fastnfitness/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c --- /dev/null +++ b/android/brodeurlv-fastnfitness/tests/requirements.txt @@ -0,0 +1,2 @@ +pytest +pillow diff --git a/android/brodeurlv-fastnfitness/tests/test_android_computation.py b/android/brodeurlv-fastnfitness/tests/test_android_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..98baa8b4ec72fae02db5759e3685d283fad5fe2d --- /dev/null +++ b/android/brodeurlv-fastnfitness/tests/test_android_computation.py @@ -0,0 +1,680 @@ +#!/usr/bin/env python3 +"""COMPUTATION lane — FastNFitness (com.easyfitness.debug). + +Owns jump_kind="value": every test feeds an INPUT through the user path and +asserts the SPECIFIC OUTPUT the running app produced. + +The app's real input->output surfaces (all confirmed live on this build): + + * FREE WORKOUT "ADD" flow — type Sets/Reps/Weight, tap ADD -> a NEW record + card appears at the TOP of `listRecord` under today's SEPARATOR whose cells + echo the inputs exactly: SERIE_CELL=Sets, REPETITION_CELL=Reps, + POIDS_CELL=Weight+unit, MACHINE_CELL=exercise. (Verified: Reps 7 -> new + card REPETITION_CELL "7"; Sets 4 / Reps 15 / Weight 88 -> "4"/"15"/"88lb".) + * Record Editor (a card's editButton) — prefilled Sets/Reps/Weight; change a + field, UPDATE -> that card's cell shows the new value. depth 1. (Verified: + Reps 7->12 -> top REPETITION_CELL "12".) NOTE: typing raises the soft + keyboard which SHIFTS the modal; dismiss the IME and re-ui() before tapping + btn_update, or the tap lands below the moved button. + * singlevalueinput_comment = "Min: - Max:" — the SELECTED + exercise's recorded weight RANGE, a derived output. Example 1 -> a kg range + ("Min:40kg - Max:75kg" observed); Example 2 -> an lb range + ("Min:60lb - Max:60lb" observed). The unit tracks the exercise; the numbers + are computed from stored records (so they drift as records are added — we + assert the DERIVED unit + Min/Max shape, and that switching exercises + CHANGES the comment, which is the stable ground truth). + +The unit LABEL follows the exercise (Example 1 = kg, Example 2 = lb). The unit +spinner does NOT live-convert the number — so there is no "switch unit -> number +changes" test (that is not this app's behavior). + +Single VLM assertion: the GRAPHS line chart is an MPAndroidChart canvas whose +plotted line/point never reaches the view tree — asked visually (tag="shape"). +""" +import os +import re +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 + + +# ══════════════════════════════════════════════════════════════════════════════ +# Helpers (self-contained — this module never imports a sibling test file) +# ══════════════════════════════════════════════════════════════════════════════ + +# x-order thresholds for the three singlevalueinput_value EditTexts. +# Main Free-Workout form: Sets~134, Reps~404, Weight~739. +# Record Editor modal: Sets~283, Reps~453, Weight~639. +# Bands separate all six: Sets < 350, 350 <= Reps < 560, Weight >= 560. +def value_field(nodes, which): + """The Sets/Reps/Weight EditText of the current input surface, disambiguated + by x-center. `which` in {"sets","reps","weight"}.""" + fields = [n for n in nodes + if n.get("resource-id", "").rsplit("/", 1)[-1] == "singlevalueinput_value" + and "_center" in n] + for f in fields: + x = f["_center"][0] + if which == "sets" and x < 350: + return f + if which == "reps" and 350 <= x < 560: + return f + if which == "weight" and x >= 560: + return f + return None + + +def clear_and_type(field_node, text): + """Tap the field to focus it, move to end, backspace it empty, then type + WITHOUT re-dumping (an extra ui() between tap and type drops edit focus on + this build). Spaces are %s-escaped exactly as the kit's type_text does.""" + if not field_node or not tap_node(field_node): + return False + settle("keyboard") + press_key("KEYCODE_MOVE_END") + for _ in range(10): + press_key("KEYCODE_DEL") + adb_shell("input", "text", str(text).replace(" ", "%s")) + settle("text") + return True + + +def dismiss_kb(): + """Dismiss the soft keyboard with a SINGLE KEYCODE_BACK. The kit's + hide_keyboard() first taps a toolbar control whose desc contains 'back', + which on THIS app navigates the fragment away and empties the list. A lone + BACK reliably closes only the IME here (verified: it leaves the Free-Workout + ADD surface and the Record Editor modal intact). No-op when the IME is down.""" + if keyboard_visible(): + press_key("KEYCODE_BACK") + settle("keyboard") + + +def uncheck_rest_timer(): + """Uncheck `restTimeCheckBox` if checked, so ADD saves directly with no + intercepting rest-countdown dialog. Idempotent.""" + cb = node_by_id(ui(), "restTimeCheckBox") + if cb is not None and cb.get("checked") == "true": + tap_node(cb) + settle("tap") + + +def _cell_nodes(nodes, cell_id): + c = [n for n in nodes + if n.get("resource-id", "").rsplit("/", 1)[-1] == cell_id and "_center" in n] + c.sort(key=lambda n: n["_center"][1]) + return c + + +def top_card_cell(nodes, cell_id): + """Text of the top-most (smallest y) record-card cell whose id suffix is + `cell_id` (MACHINE_CELL / SERIE_CELL / REPETITION_CELL / POIDS_CELL). The + newest record is always the first card under today's SEPARATOR, i.e. the + smallest y — so this reads the record the ADD/UPDATE just produced.""" + c = _cell_nodes(nodes, cell_id) + return c[0].get("text") if c else None + + +def on_free_workout(nodes=None): + return node_by_id(ui() if nodes is None else nodes, "addperff") is not None + + +def ensure_free_workout(): + """Land on FREE WORKOUT; tap the tab if a relaunch left us elsewhere.""" + if on_free_workout(): + return True + n = find_node_ci(ui(), "FREE WORKOUT") + if n and tap_node(n): + settle("tap") + return on_free_workout() + + +def select_exercise(name): + """Open the exercise picker (buttonListMachine) and pick `name`; confirm + editMachine reflects it. Returns True on success.""" + btn = node_by_id(ui(), "buttonListMachine") + if btn is None or not tap_node(btn): + return False + settle("tap") + opt = find_node_ci(ui(), name) + if opt is None or not tap_node(opt): + return False + settle("tap") + em = node_by_id(ui(), "editMachine") + return em is not None and em.get("text", "").strip() == name + + +def set_fields(sets=None, reps=None, weight=None): + """Set any of Sets/Reps/Weight on the current Free-Workout form. Re-finds the + field before each edit (the tree is re-dumped each time).""" + if sets is not None: + clear_and_type(value_field(ui(), "sets"), sets) + dismiss_kb() + if reps is not None: + clear_and_type(value_field(ui(), "reps"), reps) + dismiss_kb() + if weight is not None: + clear_and_type(value_field(ui(), "weight"), weight) + dismiss_kb() + + +def tap_add(): + """Uncheck the rest timer, tap ADD, settle. Assumes fields already set.""" + uncheck_rest_timer() + add_btn = node_by_id(ui(), "addperff") + if add_btn is None: + return False + ok = tap_node(add_btn) + settle("tap") + return ok + + +def current_unit(nodes=None): + """The weight unit label (child text1 of singlevalueinput_unitSpinner) on the + Free-Workout form.""" + nodes = ui() if nodes is None else nodes + sp = node_by_id(nodes, "singlevalueinput_unitSpinner") + if sp is None or "_bounds" not in sp: + # fall back to any text1 near the weight field + t1 = node_by_id(nodes, "text1") + return t1.get("text", "").strip() if t1 else "" + sx1, sy1, sx2, sy2 = sp["_bounds"] + for n in nodes: + if n.get("resource-id", "").rsplit("/", 1)[-1] == "text1" and "_center" in n: + cx, cy = n["_center"] + if sx1 <= cx <= sx2 and sy1 <= cy <= sy2: + return n.get("text", "").strip() + return "" + + +def comment_text(nodes=None): + """The singlevalueinput_comment (the exercise's Min/Max range) on the + Free-Workout form.""" + n = node_by_id(ui() if nodes is None else nodes, "singlevalueinput_comment") + return (n.get("text", "").strip() if n else "") + + +# ── depth-family helper: opening the Record Editor modal crosses one surface ── +def and_enter_editor(near_y=None): + """Tap a card's `editButton` (the one nearest y=near_y, else the top card), + confirm the Record Editor modal opened ("Record Editor" title present), and + count one surface. Backs a declared depth>=1.""" + ebs = [n for n in ui() + if n.get("resource-id", "").rsplit("/", 1)[-1] == "editButton" + and "_center" in n] + if not ebs: + return False + if near_y is None: + ebs.sort(key=lambda n: n["_center"][1]) + else: + ebs.sort(key=lambda n: abs(n["_center"][1] - near_y)) + if not tap_node(ebs[0]): + return False + settle("tap") + if find_node_ci(ui(), "Record Editor") is None: + return False + and_enter("record_editor") + return True + + +def editor_update(): + """Tap UPDATE in the Record Editor, re-finding it in a FRESH dump first (the + IME shifts the modal; after dismiss_kb the modal returns and a fresh ui() + holds the true button coords). Returns True if UPDATE was tapped.""" + dismiss_kb() + upd = node_by_id(ui(), "btn_update") + if upd is None or not tap_node(upd): + return False + settle("tap") + return True + + +def and_reach_graphs(): + """Tap the GRAPHS pager tab and PROVE the jump: graphLineChart appears and the + Free-Workout ADD button disappears. Counts one surface (depth 1).""" + tab = find_node_ci(ui(), "GRAPHS") + if tab is None: + return False + before = and_showing() + if not tap_node(tab): + return False + settle("tap") + after = and_showing() + ok = and_reach(before, after, "graphLineChart", "addperff") + if ok: + and_enter("graphs") + return ok + + +def _norm(s): + return (s or "").replace(" ", "").strip() + + +# The exercise used for ADD/editor tests. Example 2 keeps its records isolated +# from Example 1, whose kg range we assert separately. +ADD_EXERCISE = "Example 2" +ADD_UNIT = "lb" # Example 2's unit label, observed live + + +def _setup_free_workout_on(exercise): + """restart -> FREE WORKOUT -> select `exercise` -> uncheck rest timer. + Returns (ok, note).""" + restart_app() + if not ensure_free_workout(): + return False, "setup_failed: Free-Workout surface not reachable after restart" + if not select_exercise(exercise): + return False, f"setup_failed: could not select exercise {exercise!r}" + uncheck_rest_timer() + return True, "" + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1. ADD Reps=N -> new top card REPETITION_CELL == N (4 distinct N) +# ══════════════════════════════════════════════════════════════════════════════ + +def _add_reps_case(name, marker): + ok0, note = _setup_free_workout_on(ADD_EXERCISE) + if not ok0: + record(name, False, note, depth=0, jump_kind="value", + expect=f"top REPETITION_CELL == {marker}") + return + set_fields(reps=marker) + if not tap_add(): + record(name, False, "feature_missing: ADD button not present", + depth=0, jump_kind="value", expect=f"top REPETITION_CELL == {marker}") + return + settle("tap") + got = top_card_cell(ui(), "REPETITION_CELL") + ok = got == marker + record(name, ok, + "" if ok else f"behavior_wrong: top REPETITION_CELL {got!r}, expected {marker!r}", + depth=0, jump_kind="value", expect=f"top REPETITION_CELL == {marker}") + + +@and_test(expects=("computation_add_reps_3",)) +def test_add_reps_3(): + _add_reps_case("computation_add_reps_3", "3") + + +@and_test(expects=("computation_add_reps_7",)) +def test_add_reps_7(): + _add_reps_case("computation_add_reps_7", "7") + + +@and_test(expects=("computation_add_reps_12",)) +def test_add_reps_12(): + _add_reps_case("computation_add_reps_12", "12") + + +@and_test(expects=("computation_add_reps_15",)) +def test_add_reps_15(): + _add_reps_case("computation_add_reps_15", "15") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2. ADD Sets=N -> new top card SERIE_CELL == N (3 distinct N) +# ══════════════════════════════════════════════════════════════════════════════ + +def _add_sets_case(name, marker): + ok0, note = _setup_free_workout_on(ADD_EXERCISE) + if not ok0: + record(name, False, note, depth=0, jump_kind="value", + expect=f"top SERIE_CELL == {marker}") + return + set_fields(sets=marker) + if not tap_add(): + record(name, False, "feature_missing: ADD button not present", + depth=0, jump_kind="value", expect=f"top SERIE_CELL == {marker}") + return + settle("tap") + got = top_card_cell(ui(), "SERIE_CELL") + ok = got == marker + record(name, ok, + "" if ok else f"behavior_wrong: top SERIE_CELL {got!r}, expected {marker!r}", + depth=0, jump_kind="value", expect=f"top SERIE_CELL == {marker}") + + +@and_test(expects=("computation_add_sets_2",)) +def test_add_sets_2(): + _add_sets_case("computation_add_sets_2", "2") + + +@and_test(expects=("computation_add_sets_4",)) +def test_add_sets_4(): + _add_sets_case("computation_add_sets_4", "4") + + +@and_test(expects=("computation_add_sets_5",)) +def test_add_sets_5(): + _add_sets_case("computation_add_sets_5", "5") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3. ADD Weight=W -> new top card POIDS_CELL == W + current unit (3 distinct W) +# ══════════════════════════════════════════════════════════════════════════════ + +def _add_weight_case(name, w): + ok0, note = _setup_free_workout_on(ADD_EXERCISE) + if not ok0: + record(name, False, note, depth=0, jump_kind="value", + expect=f"top POIDS_CELL == {w}{ADD_UNIT}") + return + unit = current_unit(ui()) or ADD_UNIT + set_fields(weight=w) + if not tap_add(): + record(name, False, "feature_missing: ADD button not present", + depth=0, jump_kind="value", expect=f"top POIDS_CELL == {w}{unit}") + return + settle("tap") + got = top_card_cell(ui(), "POIDS_CELL") + expected = f"{w}{unit}" + ok = _norm(got) == _norm(expected) + record(name, ok, + "" if ok else f"behavior_wrong: top POIDS_CELL {got!r}, expected {expected!r}", + depth=0, jump_kind="value", expect=f"top POIDS_CELL == {expected}") + + +@and_test(expects=("computation_add_weight_80",)) +def test_add_weight_80(): + _add_weight_case("computation_add_weight_80", "80") + + +@and_test(expects=("computation_add_weight_88",)) +def test_add_weight_88(): + _add_weight_case("computation_add_weight_88", "88") + + +@and_test(expects=("computation_add_weight_125",)) +def test_add_weight_125(): + _add_weight_case("computation_add_weight_125", "125") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4. Record Editor: set Reps=N -> UPDATE -> that card REPETITION_CELL == N (depth1) +# ══════════════════════════════════════════════════════════════════════════════ + +def _editor_reps_case(name, seed, new): + ok0, note = _setup_free_workout_on(ADD_EXERCISE) + if not ok0: + record(name, False, note, depth=1, jump_kind="value", + expect=f"top REPETITION_CELL == {new}") + return + # seed a fresh record so the editor operates on a card whose value we control + set_fields(reps=seed) + if not tap_add(): + record(name, False, "feature_missing: ADD button not present", + depth=1, jump_kind="value", expect=f"top REPETITION_CELL == {new}") + return + settle("tap") + if not and_enter_editor(): + record(name, False, "feature_missing: could not open Record Editor via editButton", + depth=1, jump_kind="value", expect=f"top REPETITION_CELL == {new}") + return + rf = value_field(ui(), "reps") + if rf is None: + record(name, False, "behavior_wrong: no Reps field in the Record Editor", + depth=1, jump_kind="value", expect=f"top REPETITION_CELL == {new}") + return + clear_and_type(rf, new) + if not editor_update(): + record(name, False, "feature_missing: no UPDATE button in the Record Editor", + depth=1, jump_kind="value", expect=f"top REPETITION_CELL == {new}") + return + got = top_card_cell(ui(), "REPETITION_CELL") + ok = got == new + record(name, ok, + "" if ok else f"behavior_wrong: top REPETITION_CELL {got!r} after UPDATE, expected {new!r}", + depth=1, jump_kind="value", expect=f"top REPETITION_CELL {seed}->{new}") + + +@and_test(expects=("computation_editor_reps_9",)) +def test_editor_reps_9(): + _editor_reps_case("computation_editor_reps_9", "3", "9") + + +@and_test(expects=("computation_editor_reps_21",)) +def test_editor_reps_21(): + _editor_reps_case("computation_editor_reps_21", "5", "21") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5. Record Editor: set Weight=W -> UPDATE -> POIDS_CELL == W + unit (depth1) +# ══════════════════════════════════════════════════════════════════════════════ + +def _editor_weight_case(name, seed_w, new_w): + ok0, note = _setup_free_workout_on(ADD_EXERCISE) + if not ok0: + record(name, False, note, depth=1, jump_kind="value", + expect=f"top POIDS_CELL == {new_w}{ADD_UNIT}") + return + unit = current_unit(ui()) or ADD_UNIT + set_fields(weight=seed_w) + if not tap_add(): + record(name, False, "feature_missing: ADD button not present", + depth=1, jump_kind="value", expect=f"top POIDS_CELL == {new_w}{unit}") + return + settle("tap") + if not and_enter_editor(): + record(name, False, "feature_missing: could not open Record Editor via editButton", + depth=1, jump_kind="value", expect=f"top POIDS_CELL == {new_w}{unit}") + return + wf = value_field(ui(), "weight") + if wf is None: + record(name, False, "behavior_wrong: no Weight field in the Record Editor", + depth=1, jump_kind="value", expect=f"top POIDS_CELL == {new_w}{unit}") + return + # unit inside the editor is the same label; the stored value keeps it + edit_unit = "" + for n in ui(): + if n.get("resource-id", "").rsplit("/", 1)[-1] == "text1" and n.get("text", "").strip(): + edit_unit = n.get("text", "").strip() + break + edit_unit = edit_unit or unit + clear_and_type(wf, new_w) + if not editor_update(): + record(name, False, "feature_missing: no UPDATE button in the Record Editor", + depth=1, jump_kind="value", expect=f"top POIDS_CELL == {new_w}{edit_unit}") + return + got = top_card_cell(ui(), "POIDS_CELL") or "" + expected = f"{new_w}{edit_unit}" + ok = _norm(got) == _norm(expected) + record(name, ok, + "" if ok else f"behavior_wrong: top POIDS_CELL {got!r} after UPDATE, expected {expected!r}", + depth=1, jump_kind="value", expect=f"top POIDS_CELL == {expected}") + + +@and_test(expects=("computation_editor_weight_95",)) +def test_editor_weight_95(): + _editor_weight_case("computation_editor_weight_95", "60", "95") + + +@and_test(expects=("computation_editor_weight_140",)) +def test_editor_weight_140(): + _editor_weight_case("computation_editor_weight_140", "70", "140") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 6. singlevalueinput_comment Min/Max reflects the SELECTED exercise (derived) +# Example 1 -> a kg range; Example 2 -> an lb range. The unit is the stable, +# derived ground truth (numbers drift as records are added); we also assert +# the "Min:.. - Max:.." shape and that switching exercises CHANGES the comment. +# ══════════════════════════════════════════════════════════════════════════════ + +def _range_matches(text, unit): + pat = re.compile(rf"^Min:\s*[\d.]+\s*{unit}\s*-\s*Max:\s*[\d.]+\s*{unit}$") + return pat.match(text.strip()) is not None + + +@and_test(expects=("computation_comment_example2_lb",)) +def test_comment_example2_lb(): + """Selecting Example 2 -> comment shows that exercise's weight range in lb, + e.g. the observed 'Min:60lb - Max:60lb'. Assert the derived unit + Min/Max + shape (numbers drift as records are added, the unit does not).""" + ok0, note = _setup_free_workout_on("Example 2") + if not ok0: + record("computation_comment_example2_lb", False, note, + depth=0, jump_kind="value", expect="comment matches 'Min:lb - Max:lb'") + return + txt = comment_text(ui()) + ok = _range_matches(txt, "lb") + record("computation_comment_example2_lb", ok, + "" if ok else f"behavior_wrong: comment {txt!r}, expected a 'Min:lb - Max:lb' range", + depth=0, jump_kind="value", expect="comment matches 'Min:lb - Max:lb'") + + +@and_test(expects=("computation_comment_example1_kg",)) +def test_comment_example1_kg(): + """Selecting Example 1 -> comment shows that exercise's weight range in kg + (observed 'Min:40kg - Max:75kg'). Assert the derived kg unit + Min/Max shape.""" + ok0, note = _setup_free_workout_on("Example 1") + if not ok0: + record("computation_comment_example1_kg", False, note, + depth=0, jump_kind="value", expect="comment matches 'Min:kg - Max:kg'") + return + txt = comment_text(ui()) + ok = _range_matches(txt, "kg") + record("computation_comment_example1_kg", ok, + "" if ok else f"behavior_wrong: comment {txt!r}, expected a 'Min:kg - Max:kg' range", + depth=0, jump_kind="value", expect="comment matches 'Min:kg - Max:kg'") + + +@and_test(expects=("computation_comment_switch_changes",)) +def test_comment_switch_changes(): + """Derived-output TRANSITION: switch the exercise from Example 1 to Example 2 + and the Min/Max comment changes (kg range -> lb range). The exact strings + drift with data, but the switch always re-derives a different comment.""" + ok0, note = _setup_free_workout_on("Example 1") + if not ok0: + record("computation_comment_switch_changes", False, note, + depth=0, jump_kind="value", expect="comment changes Example1->Example2") + return + before = comment_text(ui()) + if not select_exercise("Example 2"): + record("computation_comment_switch_changes", False, + "setup_failed: could not switch to Example 2", + depth=0, jump_kind="value", expect="comment changes Example1->Example2") + return + after = comment_text(ui()) + # both are Min/Max ranges, and the derived unit flips kg -> lb + ok = (before != after and _range_matches(before, "kg") + and _range_matches(after, "lb")) + record("computation_comment_switch_changes", ok, + "" if ok else f"behavior_wrong: comment did not re-derive; before={before!r} after={after!r}", + depth=0, jump_kind="value", expect="comment changes Example1(kg)->Example2(lb)") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 7. Combined input->output: Sets AND Reps AND Weight in one ADD -> card echoes +# all three (checked field-by-field). (2 composite cases) +# ══════════════════════════════════════════════════════════════════════════════ + +def _combined_case(name, s, r, w): + ok0, note = _setup_free_workout_on(ADD_EXERCISE) + exp = f"SERIE={s} REPETITION={r} POIDS={w}{ADD_UNIT}" + if not ok0: + record(name, False, note, depth=0, jump_kind="value", expect=exp) + return + unit = current_unit(ui()) or ADD_UNIT + set_fields(sets=s, reps=r, weight=w) + if not tap_add(): + record(name, False, "feature_missing: ADD button not present", + depth=0, jump_kind="value", expect=exp) + return + settle("tap") + nodes = ui() + got_s = top_card_cell(nodes, "SERIE_CELL") + got_r = top_card_cell(nodes, "REPETITION_CELL") + got_p = top_card_cell(nodes, "POIDS_CELL") + exp_p = f"{w}{unit}" + ok = got_s == s and got_r == r and _norm(got_p) == _norm(exp_p) + record(name, ok, + "" if ok else (f"behavior_wrong: got SERIE={got_s!r} REPETITION={got_r!r} " + f"POIDS={got_p!r}, expected {s!r}/{r!r}/{exp_p!r}"), + depth=0, jump_kind="value", + expect=f"SERIE={s} REPETITION={r} POIDS={exp_p}") + + +@and_test(expects=("computation_combined_2_11_80",)) +def test_combined_2_11_80(): + _combined_case("computation_combined_2_11_80", "2", "11", "80") + + +@and_test(expects=("computation_combined_3_14_110",)) +def test_combined_3_14_110(): + _combined_case("computation_combined_3_14_110", "3", "14", "110") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 8. Edge case: ADD Reps=1 (minimal valid input) -> card echoes "1" +# A positive/negative pair — the value is ABSENT before ADD, PRESENT after. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_add_creates_new_card",)) +def test_add_creates_new_card(): + """Positive/negative: with a distinctive Reps marker ABSENT before ADD, tap + ADD -> a NEW top card carrying exactly that marker appears (the input becomes + the newest record's output).""" + marker = "137" # distinctive value unlikely to pre-exist as the top card + ok0, note = _setup_free_workout_on(ADD_EXERCISE) + if not ok0: + record("computation_add_creates_new_card", False, note, + depth=0, jump_kind="value", expect=f"new top REPETITION_CELL == {marker}") + return + set_fields(reps=marker) + before = top_card_cell(ui(), "REPETITION_CELL") + if not tap_add(): + record("computation_add_creates_new_card", False, "feature_missing: ADD button not present", + depth=0, jump_kind="value", expect=f"new top REPETITION_CELL == {marker}") + return + settle("tap") + after = top_card_cell(ui(), "REPETITION_CELL") + ok = after == marker and before != marker + record("computation_add_creates_new_card", ok, + "" if ok else (f"behavior_wrong: top REPETITION_CELL before={before!r} after={after!r}, " + f"expected ABSENT then {marker!r}"), + depth=0, jump_kind="value", + expect=f"top REPETITION_CELL: not {marker} -> {marker}") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 9. VLM (the ONLY one for this lane) — GRAPHS line chart is a canvas the view +# tree never carries; ask about the rendered plotted line/point (tag="shape"). +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_graph_line_chart_vlm",)) +def test_graph_line_chart_vlm(): + restart_app() + if not ensure_free_workout(): + record("computation_graph_line_chart_vlm", False, + "setup_failed: Free-Workout surface not reachable after restart", + depth=1, jump_kind="reach", tag="shape", + expect="line chart rendered in GRAPHS chart area") + return + if not and_reach_graphs(): + record("computation_graph_line_chart_vlm", False, + "setup_failed: could not reach the GRAPHS chart surface", + depth=1, jump_kind="reach", tag="shape", + expect="line chart rendered in GRAPHS chart area") + return + settle("tap") + vlm_assert("computation_graph_line_chart", + "In the chart area below the ALL/LAST YEAR/LAST MONTH/LAST WEEK " + "buttons, is a line chart rendered showing a plotted line connecting " + "at least one round data point marker (not an empty blank grid)?", + RESULTS_DIR, depth=1, jump_kind="reach", tag="shape") + + +TESTS = [ + test_add_reps_3, test_add_reps_7, test_add_reps_12, test_add_reps_15, + test_add_sets_2, test_add_sets_4, test_add_sets_5, + test_add_weight_80, test_add_weight_88, test_add_weight_125, + test_editor_reps_9, test_editor_reps_21, + test_editor_weight_95, test_editor_weight_140, + test_comment_example2_lb, test_comment_example1_kg, test_comment_switch_changes, + test_combined_2_11_80, test_combined_3_14_110, + test_add_creates_new_card, + test_graph_line_chart_vlm, +] + +if __name__ == "__main__": + run_suite(TESTS, "computation") diff --git a/android/brodeurlv-fastnfitness/tests/test_android_interaction.py b/android/brodeurlv-fastnfitness/tests/test_android_interaction.py new file mode 100644 index 0000000000000000000000000000000000000000..252e57100c76a3309a671469f20eeb7ca9f76744 --- /dev/null +++ b/android/brodeurlv-fastnfitness/tests/test_android_interaction.py @@ -0,0 +1,821 @@ +#!/usr/bin/env python3 +"""INTERACTION lane — FastNFitness (com.easyfitness.debug). + +Owns EFFECT-BY-CONSEQUENCE on user DATA: CRUD lifecycle, 3+ step sequences, +multi-record integrity, and DATA persistence across process death. Sole owner of +long-press / context-menu probes. + +FACTS confirmed on the running original (recon.md + live probing) this file relies on: + + * A clean restart_app() lands on Workout / FREE WORKOUT (the CRUD surface): + tab strip `fontes_pagertab`, the Free-Workout input block `WorkoutValuesInput`, + `addperff` (ADD), and `listRecord`. + * The core CREATE surface is the Free-Workout ADD flow. Three + `singlevalueinput_value` EditTexts, in x-order: Sets (x~134), Reps (x~404), + Weight (x~739). Disambiguated by _center[0]. ADD button id=`addperff`. + * After ADD, a NEW record card appears at the TOP of `listRecord`, under today's + `SEPARATOR_CELL`. Card cells: `MACHINE_CELL` (exercise), `SERIE_CELL` (sets), + `REPETITION_CELL` (reps), `POIDS_CELL` (weight+unit). Confirmed live: Reps 33 + -> top card REPETITION_CELL 33; Sets 4 -> SERIE_CELL 4. + * `editButton` on a card opens the "Record Editor" modal: three prefilled + `singlevalueinput_value` (Sets x~283, Reps x~453, Weight x~639 in this modal), + `btn_update` (UPDATE), `btn_cancel` (CANCEL). Confirmed live: editing Reps -> + UPDATE changed REPETITION_CELL; editing Weight -> POIDS_CELL "75kg"; CANCEL + left the value unchanged. + * `buttonListMachine` opens "Select an existing exercise" (rows Example 1 / + Example 2); picking one sets `editMachine` and the next ADD's MACHINE_CELL. + * A record added on FREE WORKOUT immediately shows in HISTORY; HISTORY + `filterMachine` -> a machine narrows `listFilterRecord` to that machine only. + * Exercises (drawer -> Exercises) `searchField` filters `listMachine` live. + * PERSISTENCE confirmed live: ADD a record, force_stop_and_relaunch, the card is + STILL in `listRecord` (relaunch returns to FREE WORKOUT, no navigation needed). + + IMPLEMENTATION NOTES (learned by probing this build): + * The drawer opens by TAPPING the toolbar hamburger (content-desc "Open + navigation drawer"); the left-edge swipe is unreliable here. + * The kit's hide_keyboard() first taps any 'back'-labelled node, which on this + app is a toolbar control that NAVIGATES the fragment away — so we dismiss the + IME with a single KEYCODE_BACK (`dismiss_kb`), which leaves both the ADD + surface and the Record Editor modal intact (verified live). + * `input text` truncates at a space, so multi-word values are %s-escaped. + * Records PERSIST across restart_app and accumulate, so every data assertion is + COUNT-BASED (a new row => the marker count grew by exactly one AND the new row + is on top) rather than relying on global absence — that stays valid on a fresh + eval emulator and on repeated self-validation runs alike. + * copyButton is a NO-OP on this build and the rest-timer dialog never appears; + neither is asserted (a test that fails on the original buys nothing). Uncheck + the rest checkbox before ADD anyway, per the documented clean path. + * Long-press opens NO context menu on record cards or exercise rows (the exercise + long-press merely navigates); both are recorded honestly as feature_missing. + * NEVER tap: overflow Reset app / Export|Import Records, any deleteButton. +""" +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 + + +# ── x-order thresholds for the three singlevalueinput_value EditTexts ────────── +# Main Free-Workout form: Sets~134, Reps~404, Weight~739. +# Record Editor modal: Sets~283, Reps~453, Weight~639. +# Bands separate all six: Sets < 350, 350 <= Reps < 560, Weight >= 560. +def value_field(nodes, which): + """Return the Sets/Reps/Weight EditText from the current input surface, + disambiguated by x-center. `which` in {"sets","reps","weight"}.""" + fields = [n for n in nodes + if n.get("resource-id", "").rsplit("/", 1)[-1] == "singlevalueinput_value" + and "_center" in n] + for f in fields: + x = f["_center"][0] + if which == "sets" and x < 350: + return f + if which == "reps" and 350 <= x < 560: + return f + if which == "weight" and x >= 560: + return f + return None + + +def clear_and_type(field_node, text): + """Reliable clear-then-type: tap the field to focus it, move to end, backspace + enough chars to empty it, then type WITHOUT re-dumping (an extra ui() between + tap and type drops the edit focus on this build). Spaces are %s-escaped exactly + as the kit's type_text does, so multi-word values ('Example 1') are not + truncated by `input text`.""" + if not tap_node(field_node): + return False + settle("keyboard") + press_key("KEYCODE_MOVE_END") + for _ in range(10): + press_key("KEYCODE_DEL") + adb_shell("input", "text", str(text).replace(" ", "%s")) + settle("text") + return True + + +def dismiss_kb(): + """Dismiss the soft keyboard with a SINGLE KEYCODE_BACK. The kit's + hide_keyboard() first taps any node whose id/desc contains 'back', which on + this app is a toolbar control that NAVIGATES the fragment away — unusable here. + A lone BACK reliably closes only the IME on this build (verified live: it + leaves the Free-Workout ADD surface and the Record Editor modal intact). + No-op when the keyboard is already down.""" + if keyboard_visible(): + press_key("KEYCODE_BACK") + settle("keyboard") + + +def uncheck_rest_timer(): + """Uncheck `restTimeCheckBox` if it is checked, so ADD saves directly with no + intercepting dialog. Idempotent.""" + cb = node_by_id(ui(), "restTimeCheckBox") + if cb is not None and cb.get("checked") == "true": + tap_node(cb) + settle("tap") + + +def _cell_nodes(nodes, cell_id): + c = [n for n in nodes + if n.get("resource-id", "").rsplit("/", 1)[-1] == cell_id and "_center" in n] + c.sort(key=lambda n: n["_center"][1]) + return c + + +def top_card_cell(nodes, cell_id): + """Text of the top-most (smallest y) record card cell with resource-id suffix + `cell_id` (MACHINE_CELL / SERIE_CELL / REPETITION_CELL / POIDS_CELL).""" + c = _cell_nodes(nodes, cell_id) + return c[0].get("text") if c else None + + +def cells(nodes, cell_id): + """All texts for a record cell id, in top-to-bottom order.""" + return [n.get("text") for n in _cell_nodes(nodes, cell_id)] + + +def reps_count(marker, nodes=None): + """How many currently-visible record rows carry REPETITION_CELL == marker.""" + return cells(ui() if nodes is None else nodes, "REPETITION_CELL").count(marker) + + +def on_free_workout(): + return node_by_id(ui(), "addperff") is not None + + +def ensure_free_workout(): + """Land on FREE WORKOUT; tap the tab if a relaunch left us elsewhere.""" + if on_free_workout(): + return True + n = find_node_ci(ui(), "FREE WORKOUT") + if n and tap_node(n): + settle("tap") + return on_free_workout() + + +def add_reps(marker): + """Uncheck the rest timer, set Reps=marker, dismiss the IME, tap ADD, settle. + Returns the top REPETITION_CELL observed afterwards.""" + uncheck_rest_timer() + clear_and_type(value_field(ui(), "reps"), marker) + dismiss_kb() + tap_node(node_by_id(ui(), "addperff")) + settle("tap") + return top_card_cell(ui(), "REPETITION_CELL") + + +# ── depth-family helper: opening the Record Editor modal crosses one surface ── +def and_enter_record_editor(near_y=None): + """Tap a card's `editButton` (the one nearest y=near_y, else the top card), + confirm the Record Editor modal opened, and count one surface.""" + ebs = [n for n in ui() + if n.get("resource-id", "").rsplit("/", 1)[-1] == "editButton" and "_center" in n] + if not ebs: + return False + if near_y is None: + ebs.sort(key=lambda n: n["_center"][1]) + else: + ebs.sort(key=lambda n: abs(n["_center"][1] - near_y)) + if not tap_node(ebs[0]): + return False + settle("tap") + if find_node_ci(ui(), "Record Editor") is None: + return False + and_enter("record_editor") + return True + + +# ── depth-family helper: drawer -> Exercises crosses one surface ────────────── +def and_enter_exercises(): + """Open the drawer via the hamburger, tap Exercises, confirm the Exercises list + surface (searchField present, Workout ADD gone). Counts one surface.""" + ham = find_node(ui(), content_desc="Open navigation drawer") + if ham is None or not tap_node(ham): + return False + settle("tap") + item = find_node_ci(ui(), "Exercises") + if item is None or not tap_node(item): + return False + settle("tap") + nodes = ui() + if node_by_id(nodes, "searchField") is None or node_by_id(nodes, "addperff") is not None: + return False + and_enter("exercises") + return True + + +def and_enter_history(): + """Tap the HISTORY pager tab and confirm the HISTORY surface (filterMachine + present). Counts one surface.""" + tab = find_node_ci(ui(), "HISTORY") + if tab is None or not tap_node(tab): + return False + settle("tap") + if node_by_id(ui(), "filterMachine") is None: + return False + and_enter("history") + return True + + +def pick_history_machine(name): + """On HISTORY, open the filterMachine spinner and pick `name`. Returns True if + the option was tapped.""" + fm = node_by_id(ui(), "filterMachine") + if fm is None or not tap_node(fm): + return False + settle("tap") + opt = find_node_ci(ui(), name) + if opt is None or not tap_node(opt): + return False + settle("tap") + return True + + +# Distinctive reps markers, UNIQUE per test so a re-run's residue cannot make one +# test's read-back alias another's row (records persist across restart_app). +R_CREATE = "731" +R_SETS_REPS = "736" +R_TRANSITION = "732" +R_MACHINE = "733" +R_PERSIST = "734" +R_PERSIST2 = "735" +R_MULTI_A = "941" +R_MULTI_B = "942" +R_MULTI_C = "943" +R_MULTI_EDIT = "944" +R_EDIT_A = "751" +R_EDIT_B = "752" +R_WEIGHT_SEED = "753" +R_CANCEL = "761" +R_HISTORY = "771" +R_SEQ_A = "781" +R_SEQ_B = "782" +R_DUP = "791" +S_CREATE = "6" # distinct Sets value (seeded records are all Sets=1) + + +# ══════════════════════════════════════════════════════════════════════════════ +# CREATE +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_create_reps", "interaction_create_reps_vlm")) +def test_create_record_with_distinct_reps(): + """CREATE: uncheck rest timer, set Reps to a distinct marker, ADD -> a NEW row + with REPETITION_CELL == marker appears at the TOP, and the marker's row-count + grows by exactly one (count-based so it holds whether or not a prior run left + an identical marker behind).""" + restart_app() + if not ensure_free_workout(): + record("interaction_create_reps", False, + "setup_failed: Free-Workout ADD surface not reachable after launch", + depth=0, jump_kind="value", expect=f"top REPETITION_CELL={R_CREATE}, count +1") + return + before = reps_count(R_CREATE) + if value_field(ui(), "reps") is None: + record("interaction_create_reps", False, + "feature_missing: no Reps input field on the ADD surface", + depth=0, jump_kind="value", expect=f"top REPETITION_CELL={R_CREATE}, count +1") + return + top = add_reps(R_CREATE) + after = reps_count(R_CREATE) + ok = top == R_CREATE and after == before + 1 + record("interaction_create_reps", ok, + "" if ok else f"behavior_wrong: top={top!r} count {before}->{after} (want +1, top={R_CREATE})", + depth=0, jump_kind="value", expect=f"top REPETITION_CELL={R_CREATE}, count {before}->{before+1}") + vlm_assert("interaction_create_reps", + "In the list of workout records under the date header, is the very " + f"first (top) record row showing the repetitions value {R_CREATE}?", + expect="YES", depth=0, jump_kind="value", tag="position") + + +@and_test(expects=("interaction_create_sets",)) +def test_create_record_with_distinct_sets(): + """CREATE with a distinct Sets value: set Sets AND a marker Reps, ADD -> the top + card (identified by its marker reps) shows SERIE_CELL == the Sets value.""" + restart_app() + if not ensure_free_workout(): + record("interaction_create_sets", False, + "setup_failed: Free-Workout ADD surface not reachable after launch", + depth=0, jump_kind="value", expect=f"top SERIE_CELL={S_CREATE}") + return + uncheck_rest_timer() + sets_f = value_field(ui(), "sets") + if sets_f is None: + record("interaction_create_sets", False, + "feature_missing: no Sets input field on the ADD surface", + depth=0, jump_kind="value", expect=f"top SERIE_CELL={S_CREATE}") + return + clear_and_type(sets_f, S_CREATE) + dismiss_kb() + clear_and_type(value_field(ui(), "reps"), R_SETS_REPS) + dismiss_kb() + tap_node(node_by_id(ui(), "addperff")) + settle("tap") + nodes = ui() + top_sets = top_card_cell(nodes, "SERIE_CELL") + top_reps = top_card_cell(nodes, "REPETITION_CELL") + ok = top_sets == S_CREATE and top_reps == R_SETS_REPS + record("interaction_create_sets", ok, + "" if ok else f"behavior_wrong: expected top SERIE_CELL={S_CREATE}/reps={R_SETS_REPS}, got {top_sets!r}/{top_reps!r}", + depth=0, jump_kind="value", expect=f"top SERIE_CELL={S_CREATE}") + + +@and_test(expects=("interaction_create_count_grows",)) +def test_create_count_grows_by_one(): + """The discriminating grow-by-one flip: the marker's row-count goes up by + exactly one across the ADD (a dead shell that echoes state, or one that + overwrites the last row, does not grow the count).""" + restart_app() + if not ensure_free_workout(): + record("interaction_create_count_grows", False, + "setup_failed: Free-Workout ADD surface not reachable", + depth=0, jump_kind="transition", + expect=f"REPETITION_CELL {R_TRANSITION} count grows by 1") + return + before = reps_count(R_TRANSITION) + add_reps(R_TRANSITION) + after = reps_count(R_TRANSITION) + ok = after == before + 1 + record("interaction_create_count_grows", ok, + "" if ok else f"behavior_wrong: count {before}->{after} (want +1)", + depth=0, jump_kind="transition", + expect=f"REPETITION_CELL {R_TRANSITION} count {before}->{before+1}") + + +# ══════════════════════════════════════════════════════════════════════════════ +# UPDATE (Record Editor modal — depth 1) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_update_reps", "interaction_update_reps_vlm")) +def test_update_reps_via_editor(): + """UPDATE: create a record with marker A, open its Record Editor, change Reps to + marker B, UPDATE -> the top card's REPETITION_CELL flips A->B, and A is no + longer the top row's value (the edit replaced it, not appended).""" + restart_app() + if not ensure_free_workout(): + record("interaction_update_reps", False, "setup_failed: Free-Workout surface not reachable", + depth=1, jump_kind="value", expect=f"top REPETITION_CELL {R_EDIT_A}->{R_EDIT_B}") + return + if add_reps(R_EDIT_A) != R_EDIT_A: + record("interaction_update_reps", False, "setup_failed: seed record not created", + depth=1, jump_kind="value", expect=f"top REPETITION_CELL {R_EDIT_A}->{R_EDIT_B}") + return + if not and_enter_record_editor(): + record("interaction_update_reps", False, + "feature_missing: could not open the Record Editor via editButton", + depth=1, jump_kind="value", expect=f"top REPETITION_CELL {R_EDIT_A}->{R_EDIT_B}") + return + vlm_assert("interaction_update_reps", + "Is a modal editor dialog (a card titled 'Record Editor' with input " + "fields and UPDATE / CANCEL buttons) shown centered on top of the " + "screen, overlaying the record list behind it?", + expect="YES", depth=1, jump_kind="value", tag="shape") + if value_field(ui(), "reps") is None: + record("interaction_update_reps", False, "behavior_wrong: no Reps field in the Record Editor", + depth=1, jump_kind="value", expect=f"top REPETITION_CELL {R_EDIT_A}->{R_EDIT_B}") + return + clear_and_type(value_field(ui(), "reps"), R_EDIT_B) + dismiss_kb() + upd = node_by_id(ui(), "btn_update") + if upd is None or not tap_node(upd): + record("interaction_update_reps", False, "feature_missing: no UPDATE button in the Record Editor", + depth=1, jump_kind="value", expect=f"top REPETITION_CELL {R_EDIT_A}->{R_EDIT_B}") + return + settle("tap") + top = top_card_cell(ui(), "REPETITION_CELL") + ok = top == R_EDIT_B + record("interaction_update_reps", ok, + "" if ok else f"behavior_wrong: expected top REPETITION_CELL={R_EDIT_B} after UPDATE, got {top!r}", + depth=1, jump_kind="value", expect=f"top REPETITION_CELL {R_EDIT_A}->{R_EDIT_B}") + + +@and_test(expects=("interaction_update_weight",)) +def test_update_weight_via_editor(): + """UPDATE a different field: edit Weight in the Record Editor, UPDATE -> the + card's POIDS_CELL reflects the new weight (weight+unit, e.g. '75kg').""" + restart_app() + if not ensure_free_workout(): + record("interaction_update_weight", False, "setup_failed: Free-Workout surface not reachable", + depth=1, jump_kind="value", expect="top POIDS_CELL starts with '75'") + return + add_reps(R_WEIGHT_SEED) + if not and_enter_record_editor(): + record("interaction_update_weight", False, + "feature_missing: could not open the Record Editor via editButton", + depth=1, jump_kind="value", expect="top POIDS_CELL starts with '75'") + return + wf = value_field(ui(), "weight") + if wf is None: + record("interaction_update_weight", False, "behavior_wrong: no Weight field in the Record Editor", + depth=1, jump_kind="value", expect="top POIDS_CELL starts with '75'") + return + clear_and_type(wf, "75") + dismiss_kb() + tap_node(node_by_id(ui(), "btn_update")) + settle("tap") + top = top_card_cell(ui(), "POIDS_CELL") or "" + ok = top.startswith("75") + record("interaction_update_weight", ok, + "" if ok else f"behavior_wrong: expected top POIDS_CELL to start with '75', got {top!r}", + depth=1, jump_kind="value", expect="top POIDS_CELL starts with '75'") + + +@and_test(expects=("interaction_update_cancel_unchanged",)) +def test_update_cancel_leaves_record_unchanged(): + """UPDATE cancel: open the editor, change Reps to a throwaway value, then CANCEL + -> the top card keeps its ORIGINAL marker reps (the edit did not land) and the + throwaway value is absent from the top row.""" + restart_app() + if not ensure_free_workout(): + record("interaction_update_cancel_unchanged", False, "setup_failed: Free-Workout surface not reachable", + depth=1, jump_kind="transition", expect=f"REPETITION_CELL stays {R_CANCEL} after CANCEL") + return + if add_reps(R_CANCEL) != R_CANCEL: + record("interaction_update_cancel_unchanged", False, "setup_failed: seed record not created", + depth=1, jump_kind="transition", expect=f"REPETITION_CELL stays {R_CANCEL} after CANCEL") + return + if not and_enter_record_editor(): + record("interaction_update_cancel_unchanged", False, "feature_missing: could not open the Record Editor", + depth=1, jump_kind="transition", expect=f"REPETITION_CELL stays {R_CANCEL} after CANCEL") + return + clear_and_type(value_field(ui(), "reps"), "12321") + dismiss_kb() + cancel = node_by_id(ui(), "btn_cancel") + if cancel is None or not tap_node(cancel): + record("interaction_update_cancel_unchanged", False, "feature_missing: no CANCEL button in the Record Editor", + depth=1, jump_kind="transition", expect=f"REPETITION_CELL stays {R_CANCEL} after CANCEL") + return + settle("tap") + after = top_card_cell(ui(), "REPETITION_CELL") + ok = after == R_CANCEL + record("interaction_update_cancel_unchanged", ok, + "" if ok else f"behavior_wrong: after CANCEL expected {R_CANCEL}, got {after!r}", + depth=1, jump_kind="transition", expect=f"REPETITION_CELL stays {R_CANCEL} after CANCEL") + + +# ══════════════════════════════════════════════════════════════════════════════ +# MULTI-RECORD INTEGRITY +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_multi_two_records",)) +def test_multi_two_records_both_present(): + """Add TWO records with different markers; assert BOTH markers' counts grew by + one (neither add clobbered the other).""" + restart_app() + if not ensure_free_workout(): + record("interaction_multi_two_records", False, "setup_failed: Free-Workout surface not reachable", + depth=0, jump_kind="value", expect=f"both {R_MULTI_A} and {R_MULTI_B} counts +1") + return + a0, b0 = reps_count(R_MULTI_A), reps_count(R_MULTI_B) + add_reps(R_MULTI_A) + add_reps(R_MULTI_B) + a1, b1 = reps_count(R_MULTI_A), reps_count(R_MULTI_B) + ok = a1 == a0 + 1 and b1 == b0 + 1 + record("interaction_multi_two_records", ok, + "" if ok else f"behavior_wrong: {R_MULTI_A} {a0}->{a1}, {R_MULTI_B} {b0}->{b1} (want each +1)", + depth=0, jump_kind="value", expect=f"both {R_MULTI_A} and {R_MULTI_B} counts +1") + + +@and_test(expects=("interaction_multi_edit_middle_keeps_others", + "interaction_multi_stack_vlm")) +def test_multi_record_integrity_edit_middle(): + """Multi-record integrity: add 3 records A,B,C (newest C on top, then B, then A + among the three most-recent rows). Edit the MIDDLE one (B) to a new marker, then + assert the TOP THREE rows read C, , A in order — C and A survived intact + and stayed in their relative order while only B changed. Reads only the top 3 + rows, so residue from earlier runs (further down the list) cannot interfere.""" + restart_app() + if not ensure_free_workout(): + record("interaction_multi_edit_middle_keeps_others", False, "setup_failed: Free-Workout surface not reachable", + depth=1, jump_kind="value", expect=f"top3 == [{R_MULTI_C}, {R_MULTI_EDIT}, {R_MULTI_A}]") + return + add_reps(R_MULTI_A) # oldest of the three -> 3rd from top + add_reps(R_MULTI_B) # middle -> 2nd from top + add_reps(R_MULTI_C) # newest -> top + top3 = cells(ui(), "REPETITION_CELL")[:3] + if top3 != [R_MULTI_C, R_MULTI_B, R_MULTI_A]: + record("interaction_multi_edit_middle_keeps_others", False, + f"setup_failed: three adds did not stack as expected (top3={top3})", + depth=1, jump_kind="value", expect=f"top3 == [{R_MULTI_C}, {R_MULTI_EDIT}, {R_MULTI_A}]") + return + vlm_assert("interaction_multi_stack", + "In the workout record list, are there at least three record rows " + "stacked vertically one below another, each showing a sets / reps / " + "weight value block on its right side?", + expect="YES", depth=0, jump_kind="value", tag="layout") + # The middle row is the 2nd-from-top; edit exactly that card. + b_nodes = _cell_nodes(ui(), "REPETITION_CELL") + if len(b_nodes) < 2: + record("interaction_multi_edit_middle_keeps_others", False, + "setup_failed: fewer than two record rows visible before edit", + depth=1, jump_kind="value", expect=f"top3 == [{R_MULTI_C}, {R_MULTI_EDIT}, {R_MULTI_A}]") + return + if not and_enter_record_editor(near_y=b_nodes[1]["_center"][1]): + record("interaction_multi_edit_middle_keeps_others", False, + "feature_missing: could not open the Record Editor for the middle card", + depth=1, jump_kind="value", expect=f"top3 == [{R_MULTI_C}, {R_MULTI_EDIT}, {R_MULTI_A}]") + return + clear_and_type(value_field(ui(), "reps"), R_MULTI_EDIT) + dismiss_kb() + tap_node(node_by_id(ui(), "btn_update")) + settle("tap") + top3 = cells(ui(), "REPETITION_CELL")[:3] + ok = top3 == [R_MULTI_C, R_MULTI_EDIT, R_MULTI_A] + record("interaction_multi_edit_middle_keeps_others", ok, + "" if ok else f"behavior_wrong: expected top3 [{R_MULTI_C},{R_MULTI_EDIT},{R_MULTI_A}], got {top3}", + depth=1, jump_kind="value", expect=f"top3 == [{R_MULTI_C}, {R_MULTI_EDIT}, {R_MULTI_A}]") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3+ STEP SEQUENCE (machine picker + reps + ADD) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_seq_machine_then_reps",)) +def test_sequence_pick_machine_then_add(): + """3-step sequence, each step depending on the last: open the machine picker, + pick Example 1, set Reps to a marker, ADD -> top card MACHINE_CELL='Example 1' + AND REPETITION_CELL==marker together.""" + restart_app() + if not ensure_free_workout(): + record("interaction_seq_machine_then_reps", False, "setup_failed: Free-Workout surface not reachable", + depth=1, jump_kind="value", expect=f"top MACHINE_CELL='Example 1' & REPETITION_CELL={R_MACHINE}") + return + blm = node_by_id(ui(), "buttonListMachine") + if blm is None or not tap_node(blm): + record("interaction_seq_machine_then_reps", False, + "feature_missing: no machine-picker button (buttonListMachine)", + depth=1, jump_kind="value", expect=f"top MACHINE_CELL='Example 1' & REPETITION_CELL={R_MACHINE}") + return + settle("tap") + row = find_node_ci(ui(), "Example 1") + if row is None or not tap_node(row): + record("interaction_seq_machine_then_reps", False, + "setup_failed: 'Example 1' not offered in the exercise picker", + depth=1, jump_kind="value", expect=f"top MACHINE_CELL='Example 1' & REPETITION_CELL={R_MACHINE}") + return + and_enter("exercise_picker") + settle("tap") + em = node_by_id(ui(), "editMachine") + if em is None or (em.get("text") or "").strip() != "Example 1": + record("interaction_seq_machine_then_reps", False, + f"behavior_wrong: machine not set to Example 1 (editMachine={(em.get('text') if em else None)!r})", + depth=1, jump_kind="value", expect=f"top MACHINE_CELL='Example 1' & REPETITION_CELL={R_MACHINE}") + return + add_reps(R_MACHINE) + nodes = ui() + machine = top_card_cell(nodes, "MACHINE_CELL") + reps = top_card_cell(nodes, "REPETITION_CELL") + ok = machine == "Example 1" and reps == R_MACHINE + record("interaction_seq_machine_then_reps", ok, + "" if ok else f"behavior_wrong: expected Example 1/{R_MACHINE}, got {machine!r}/{reps!r}", + depth=1, jump_kind="value", expect=f"top MACHINE_CELL='Example 1' & REPETITION_CELL={R_MACHINE}") + + +@and_test(expects=("interaction_create_then_edit_sequence",)) +def test_create_then_edit_full_sequence(): + """4-step dependent sequence: CREATE a record (reps=A) -> confirm it is on top + -> open its editor -> UPDATE reps to B -> confirm the top card now shows B.""" + restart_app() + if not ensure_free_workout(): + record("interaction_create_then_edit_sequence", False, "setup_failed: Free-Workout surface not reachable", + depth=1, jump_kind="value", expect=f"top REPETITION_CELL {R_SEQ_A}->{R_SEQ_B}") + return + if add_reps(R_SEQ_A) != R_SEQ_A: + record("interaction_create_then_edit_sequence", False, "setup_failed: create step did not land", + depth=1, jump_kind="value", expect=f"top REPETITION_CELL {R_SEQ_A}->{R_SEQ_B}") + return + if not and_enter_record_editor(): + record("interaction_create_then_edit_sequence", False, "feature_missing: could not open Record Editor", + depth=1, jump_kind="value", expect=f"top REPETITION_CELL {R_SEQ_A}->{R_SEQ_B}") + return + clear_and_type(value_field(ui(), "reps"), R_SEQ_B) + dismiss_kb() + tap_node(node_by_id(ui(), "btn_update")) + settle("tap") + top = top_card_cell(ui(), "REPETITION_CELL") + ok = top == R_SEQ_B + record("interaction_create_then_edit_sequence", ok, + "" if ok else f"behavior_wrong: after create+edit expected {R_SEQ_B}, got {top!r}", + depth=1, jump_kind="value", expect=f"top REPETITION_CELL {R_SEQ_A}->{R_SEQ_B}") + + +@and_test(expects=("interaction_two_identical_adds",)) +def test_two_identical_adds_create_two_rows(): + """Add the SAME reps marker twice; assert its row-count grows by exactly TWO (a + recreation that overwrites instead of appending grows it by one or zero).""" + restart_app() + if not ensure_free_workout(): + record("interaction_two_identical_adds", False, "setup_failed: Free-Workout surface not reachable", + depth=0, jump_kind="value", expect=f"REPETITION_CELL {R_DUP} count +2") + return + before = reps_count(R_DUP) + add_reps(R_DUP) + add_reps(R_DUP) + after = reps_count(R_DUP) + ok = after == before + 2 + record("interaction_two_identical_adds", ok, + "" if ok else f"behavior_wrong: count {before}->{after} (want +2)", + depth=0, jump_kind="value", expect=f"REPETITION_CELL {R_DUP} count {before}->{before+2}") + + +# ══════════════════════════════════════════════════════════════════════════════ +# DATA PERSISTENCE ACROSS PROCESS DEATH (the highest-value probe) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_persist_across_kill",)) +def test_record_persists_across_process_death(): + """DATA persistence: ADD a record (marker count +1), force_stop_and_relaunch, + then assert the marker's row-count is UNCHANGED by the kill (the row survived). + An in-memory-only recreation would lose it and the count would drop back.""" + restart_app() + if not ensure_free_workout(): + record("interaction_persist_across_kill", False, "setup_failed: Free-Workout surface not reachable", + depth=0, jump_kind="transition", expect=f"REPETITION_CELL {R_PERSIST} survives relaunch (count steady)") + return + before = reps_count(R_PERSIST) + add_reps(R_PERSIST) + before_kill = reps_count(R_PERSIST) + force_stop_and_relaunch() + ensure_free_workout() + after = reps_count(R_PERSIST) + ok = before_kill == before + 1 and after == before_kill + record("interaction_persist_across_kill", ok, + "" if ok else f"behavior_wrong: count {before}->add->{before_kill}->kill->{after} (want +1 then steady)", + depth=0, jump_kind="transition", + expect=f"REPETITION_CELL {R_PERSIST} count {before}->{before+1} and survives relaunch") + + +@and_test(expects=("interaction_persist_second_record",)) +def test_second_record_persists_across_kill(): + """A second, independent persistence probe: ADD a distinct-Sets, marker-reps row + -> kill -> relaunch -> the top row after relaunch still shows the marker reps AND + the distinct Sets (the whole row persisted, not one field).""" + restart_app() + if not ensure_free_workout(): + record("interaction_persist_second_record", False, "setup_failed: Free-Workout surface not reachable", + depth=0, jump_kind="value", expect=f"top row reps={R_PERSIST2}/sets=5 after relaunch") + return + uncheck_rest_timer() + clear_and_type(value_field(ui(), "sets"), "5") + dismiss_kb() + clear_and_type(value_field(ui(), "reps"), R_PERSIST2) + dismiss_kb() + tap_node(node_by_id(ui(), "addperff")) + settle("tap") + before_kill_top = (top_card_cell(ui(), "REPETITION_CELL"), top_card_cell(ui(), "SERIE_CELL")) + force_stop_and_relaunch() + ensure_free_workout() + nodes = ui() + after_top = (top_card_cell(nodes, "REPETITION_CELL"), top_card_cell(nodes, "SERIE_CELL")) + ok = (before_kill_top == (R_PERSIST2, "5")) and (after_top == (R_PERSIST2, "5")) + record("interaction_persist_second_record", ok, + "" if ok else f"behavior_wrong: top before kill={before_kill_top}, after relaunch={after_top} (want ({R_PERSIST2!r},'5'))", + depth=0, jump_kind="value", expect=f"top row reps={R_PERSIST2}/sets=5 after relaunch") + + +# ══════════════════════════════════════════════════════════════════════════════ +# CROSS-SURFACE INTEGRITY (record shows in HISTORY) + HISTORY filter +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_record_in_history", "interaction_record_in_history_vlm")) +def test_added_record_appears_in_history(): + """Cross-surface integrity: ADD a marker record on FREE WORKOUT, switch to the + HISTORY tab, and read the same marker back out of the history list.""" + restart_app() + if not ensure_free_workout(): + record("interaction_record_in_history", False, "setup_failed: Free-Workout surface not reachable", + depth=1, jump_kind="value", expect=f"HISTORY REPETITION_CELL contains {R_HISTORY}") + return + add_reps(R_HISTORY) + if not and_enter_history(): + record("interaction_record_in_history", False, "setup_failed: could not reach the HISTORY tab", + depth=1, jump_kind="value", expect=f"HISTORY REPETITION_CELL contains {R_HISTORY}") + return + reps = cells(ui(), "REPETITION_CELL") + ok = R_HISTORY in reps + record("interaction_record_in_history", ok, + "" if ok else f"behavior_wrong: {R_HISTORY} not in HISTORY reps {reps}", + depth=1, jump_kind="value", expect=f"HISTORY REPETITION_CELL contains {R_HISTORY}") + vlm_assert("interaction_record_in_history", + "Is the HISTORY tab currently selected and showing a vertical list of " + "workout record cards (each with an exercise name and sets/reps/weight " + "values)?", + expect="YES", depth=1, jump_kind="value", tag="position") + + +@and_test(expects=("interaction_history_filter_machine", + "interaction_history_filter_vlm")) +def test_history_filter_narrows_to_one_machine(): + """HISTORY filterMachine is a real narrowing control: pick 'Example 2' (which + has many records) and confirm every visible card is Example 2; then pick + 'Example 1' and confirm every visible card is Example 1 with NONE showing + Example 2 — the switch changed the set, proving the filter narrows.""" + restart_app() + if not ensure_free_workout(): + record("interaction_history_filter_machine", False, "setup_failed: Free-Workout surface not reachable", + depth=1, jump_kind="value", expect="HISTORY list -> all 'Example 1', none 'Example 2'") + return + if not and_enter_history(): + record("interaction_history_filter_machine", False, "setup_failed: could not reach the HISTORY tab", + depth=1, jump_kind="value", expect="HISTORY list -> all 'Example 1', none 'Example 2'") + return + if not pick_history_machine("Example 2"): + record("interaction_history_filter_machine", False, + "feature_missing: could not select 'Example 2' in the machine filter", + depth=1, jump_kind="value", expect="HISTORY list -> all 'Example 1', none 'Example 2'") + return + e2_view = cells(ui(), "MACHINE_CELL") + all_e2 = bool(e2_view) and all(m == "Example 2" for m in e2_view) + if not pick_history_machine("Example 1"): + record("interaction_history_filter_machine", False, + "setup_failed: 'Example 1' not offered in the machine filter", + depth=1, jump_kind="value", expect="HISTORY list -> all 'Example 1', none 'Example 2'") + return + e1_view = cells(ui(), "MACHINE_CELL") + only_e1 = bool(e1_view) and all(m == "Example 1" for m in e1_view) + no_e2 = "Example 2" not in e1_view + ok = all_e2 and only_e1 and no_e2 + record("interaction_history_filter_machine", ok, + "" if ok else f"behavior_wrong: E2-filter all_e2={all_e2} ({e2_view[:4]}), E1-filter view={e1_view[:4]}", + depth=1, jump_kind="value", expect="HISTORY list -> all 'Example 1', none 'Example 2'") + vlm_assert("interaction_history_filter", + "In this filtered history list, does every visible record row show " + "the SAME exercise name ('Example 1'), with no other exercise names " + "present?", + expect="YES", depth=1, jump_kind="value", tag="content") + + +# ══════════════════════════════════════════════════════════════════════════════ +# EXERCISES SEARCH FILTER (depth 1) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_exercise_search_filter",)) +def test_exercise_search_filters_list(): + """Exercises searchField: drawer -> Exercises, type 'Example 1' -> listMachine + shows ONLY the Example 1 row (Example 2 gone), changed from the unfiltered set.""" + restart_app() + if not ensure_free_workout(): + record("interaction_exercise_search_filter", False, "setup_failed: home not reachable", + depth=1, jump_kind="value", expect="listMachine shows only 'Example 1' after search") + return + if not and_enter_exercises(): + record("interaction_exercise_search_filter", False, "setup_failed: could not reach the Exercises list", + depth=1, jump_kind="value", expect="listMachine shows only 'Example 1' after search") + return + before = [n.get("text") for n in ui() + if n.get("resource-id", "").rsplit("/", 1)[-1] == "LIST_MACHINE_NAME"] + sf = node_by_id(ui(), "searchField") + if sf is None: + record("interaction_exercise_search_filter", False, "feature_missing: no searchField on the Exercises list", + depth=1, jump_kind="value", expect="listMachine shows only 'Example 1' after search") + return + clear_and_type(sf, "Example 1") + settle("text") + after = [n.get("text") for n in ui() + if n.get("resource-id", "").rsplit("/", 1)[-1] == "LIST_MACHINE_NAME"] + only_e1 = after == ["Example 1"] + changed = "Example 2" in before + ok = only_e1 and changed + record("interaction_exercise_search_filter", ok, + "" if ok else f"behavior_wrong: after search rows={after} (before={before})", + depth=1, jump_kind="value", expect="listMachine shows only 'Example 1' after search") + + +# ══════════════════════════════════════════════════════════════════════════════ +# EXTRA VLM CONSEQUENCES +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_card_action_icons_vlm",)) +def test_card_action_icon_row_rendered(): + """VLM-only: every record card renders a copy/edit/delete icon row on its right + side. The icons are textless ImageViews, so this is a rendered-property question + the dump cannot fully answer.""" + restart_app() + if ensure_free_workout() and not cells(ui(), "MACHINE_CELL"): + add_reps("14") + vlm_assert("interaction_card_action_icons", + "Does each workout record row show a row of small action icons (copy, " + "edit and delete) on its right-hand side?", + expect="YES", depth=0, jump_kind="value", tag="position") + + +TESTS = [ + test_create_record_with_distinct_reps, + test_create_record_with_distinct_sets, + test_create_count_grows_by_one, + test_update_reps_via_editor, + test_update_weight_via_editor, + test_update_cancel_leaves_record_unchanged, + test_multi_two_records_both_present, + test_multi_record_integrity_edit_middle, + test_sequence_pick_machine_then_add, + test_create_then_edit_full_sequence, + test_two_identical_adds_create_two_rows, + test_record_persists_across_process_death, + test_second_record_persists_across_kill, + test_added_record_appears_in_history, + test_history_filter_narrows_to_one_machine, + test_exercise_search_filters_list, + test_card_action_icon_row_rendered, +] + +if __name__ == "__main__": + run_suite(TESTS, "interaction") diff --git a/android/brodeurlv-fastnfitness/tests/test_android_navigation.py b/android/brodeurlv-fastnfitness/tests/test_android_navigation.py new file mode 100644 index 0000000000000000000000000000000000000000..867c801b19ecad50c033d08b05f0afc54a70aa0f --- /dev/null +++ b/android/brodeurlv-fastnfitness/tests/test_android_navigation.py @@ -0,0 +1,547 @@ +#!/usr/bin/env python3 +"""NAVIGATION lane — FastNFitness (com.easyfitness.debug). + +Owns surface REACHABILITY and back-stack integrity: every jump is PROVEN +(target surface's discriminating element APPEARED and source surface's +DISAPPEARED), and every pushed detail is unwound hop-by-hop with BACK. Sole +owner of jump_kind="reach" and of depth>=2 chains. + +Facts confirmed on the running original (see recon.md), that shape this file: + + * A clean restart_app() lands on Workout / FREE WORKOUT tab: toolbar title + "Fast N Fitness Debug", tab strip `fontes_pagertab`, and a FREE-WORKOUT-only + input block `WorkoutValuesInput`. + * MARKERS ARE MATCHED AGAINST and_showing() SURFACE KEYS, which are + "|" where identity is the node's TEXT if it has one, + else its content-desc, else its resource-id LAST segment. So an id like + `addExercise` is NOT a usable marker (that Button's key is `Button|ADD NEW + EXERCISE`); ids only surface when the node is textless (e.g. + `ListView|listWorkout`, `ViewGroup|graphLineChart`). Every target/source below + was read straight off and_showing() on the running app. + * The drawer opens by TAPPING the toolbar hamburger (content-desc + "Open navigation drawer"); the left-edge swipe is unreliable on this build. + Once opened, the drawer subtree STAYS in the dump even after it closes — so it + is NOT a source-vanished signal. The FREE-WORKOUT input block + `WorkoutValuesInput` IS still in the tree while the drawer is open and + DISAPPEARS once a fragment swaps in, so it is the reliable "left Workout" + source for every drawer/tab reach. CAUTION: a destination TITLE that equals a + drawer item label (e.g. "Weight Track", "Progress Images") is ALSO in the + drawer-open before-set, so it cannot be a reach target — those use a textless + content id instead. + * The profile popup and the overflow menu (unlike the drawer) do NOT keep the + Workout content on-screen, so `WorkoutValuesInput` is a clean source for the + first hop into either. + * BACK does NOT unwind drawer top-level fragment navigation (Exercises/Settings/… + ignore BACK). BACK DOES pop pushed surfaces: Exercise Detail -> Exercises, + Weight/Body metric detail -> its list, Program editor -> Workout pager. The + back-stack tests therefore target only surfaces that genuinely pop. + * Never tap: overflow Reset app / Export|Import Records, any deleteButton. +""" +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 + + +# ── Markers observed on the running original, as they appear in and_showing() ── +# FREE-WORKOUT-only input block; textless -> key is `LinearLayout|WorkoutValuesInput`. +# Present while the drawer/nothing overlays it, gone once a fragment swaps in. +WORKOUT_SRC = "WorkoutValuesInput" + +# ══════════════════════════════════════════════════════════════════════════════ +# Depth-family helpers (named and_enter_*/and_reach_* so the depth auditor sees +# the navigation backing every declared depth/reach). +# ══════════════════════════════════════════════════════════════════════════════ + +def open_nav_drawer(): + """Open the nav drawer via the toolbar 'Open navigation drawer' hamburger + (the left-edge swipe is unreliable on this build). Returns True on success. + Not a surface-crossing on its own — the reach is the item tap that follows.""" + n = find_node(ui(), content_desc="Open navigation drawer") + return bool(n) and tap_node(n) + + +def fresh_home(): + """Per-test SETUP entry point: force-stop + relaunch, which lands on Workout / + FREE WORKOUT (the known starting surface). This is NOT the navigation under + test — every reach below is proven by a subsequent and_reach* call that crosses + a surface from this home; the relaunch only establishes where we start from.""" + restart_app() + + +def and_reach_drawer(item_text, target, source=WORKOUT_SRC): + """Open the drawer, tap a named item, and PROVE the reach: `target` appeared + and `source` (the Workout marker) disappeared. Counts one surface. + + `before` is snapshotted (inside and_reach_surface) with the drawer OPEN — + `source`=WorkoutValuesInput is present in the tree then (behind the drawer) and + gone after the fragment swaps, while `target` is absent until the destination + fragment inflates, so and_reach reads a true jump.""" + if not open_nav_drawer(): + return False + item = find_node(ui(), text=item_text) or find_node_ci(ui(), item_text) + if not item: + return False + return and_reach_surface(item, target, source) + + +def and_reach_tab(tab_text, target, source): + """Tap a Workout-pager tab and prove a surface swap by unique-element delta. + A pager page is a surface: the destination page's unique element appears while + the source page's unique element disappears.""" + tab = find_node(ui(), text=tab_text) + return bool(tab) and and_reach_surface(tab, target, source) + + +def and_enter_exercise_detail(): + """Exercises list -> tap an exercise row -> Exercise Detail (a pushed surface). + Returns True once the detail's photo/tab-host appear and the list's + 'ADD NEW EXERCISE' is gone. Assumes the Exercises list is showing.""" + row = node_by_id(ui(), "LIST_MACHINE_NAME") + if not row: + return False + # target: textless machine_photo -> `ImageView|machine_photo`. + # source: the Exercises list's Button text 'ADD NEW EXERCISE'. + return and_reach_surface(row, target="machine_photo", source="ADD NEW EXERCISE") + + +def and_reach_metric_detail(details_rid, source_marker): + """Weight Track -> a per-metric DETAILS button -> the measurement-history + detail (bodymeasureChart). Counts one surface.""" + btn = node_by_id(ui(), details_rid) + return bool(btn) and and_reach_surface(btn, "bodymeasureChart", source_marker) + + +def and_reach_bodypart_detail(): + """Body Track -> tap a body-part row -> its measurement-history detail.""" + row = node_by_id(ui(), "LIST_BODYPART") + # source: textless listBodyMeasures -> `ListView|listBodyMeasures`. + return bool(row) and and_reach_surface(row, "bodymeasureChart", "listBodyMeasures") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1. Drawer reaches — the primary navigation hub (8 tests, depth 1) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_exercises",)) +def test_reach_exercises(): + fresh_home() + ok = and_reach_drawer("Exercises", target="ADD NEW EXERCISE") + ok = ok and find_node_ci(ui(), "Exercises") is not None + record("nav_reach_exercises", ok, + "" if ok else "feature_missing: Exercises surface not reached from the drawer", + depth=1, jump_kind="reach", + expect="'ADD NEW EXERCISE' button appeared; Workout WorkoutValuesInput gone; title 'Exercises'") + + +@and_test(expects=("nav_reach_program_list",)) +def test_reach_program_list(): + fresh_home() + # target: textless listWorkout -> `ListView|listWorkout` (unambiguous; + # 'NEW PROGRAM' would collide with the tab strip's 'PROGRAM'). + ok = and_reach_drawer("Program List", target="listWorkout") + ok = ok and find_node_ci(ui(), "Program List") is not None + record("nav_reach_program_list", ok, + "" if ok else "feature_missing: Program List surface not reached from the drawer", + depth=1, jump_kind="reach", + expect="listWorkout list + 'NEW PROGRAM' appeared; Workout WorkoutValuesInput gone; title 'Program List'") + + +@and_test(expects=("nav_reach_weight_track", "nav_reach_weight_widgets_vlm")) +def test_reach_weight_track(): + fresh_home() + # target: textless activityLevelSpinner -> `Spinner|activityLevelSpinner` + # (the title 'Weight Track' collides with the drawer item label, so it can't + # be the target). + ok = and_reach_drawer("Weight Track", target="activityLevelSpinner") + ok = ok and node_by_id(ui(), "weightDetailsButton") is not None + record("nav_reach_weight_track", ok, + "" if ok else "feature_missing: Weight Track surface not reached from the drawer", + depth=1, jump_kind="reach", + expect="activityLevelSpinner + weightDetailsButton (DETAILS) appeared; Workout WorkoutValuesInput gone") + vlm_assert("nav_reach_weight_widgets", + "Are there four cards arranged in a two-by-two grid, labelled " + "'Weight', 'Fat', 'Muscles' and 'Water', each with a 'DETAILS' " + "button at its bottom?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("nav_reach_body_track",)) +def test_reach_body_track(): + fresh_home() + ok = and_reach_drawer("Body Track", target="listBodyMeasures") + ok = ok and find_node_ci(ui(), "Body Track") is not None + record("nav_reach_body_track", ok, + "" if ok else "feature_missing: Body Track surface not reached from the drawer", + depth=1, jump_kind="reach", + expect="listBodyMeasures list + title 'Body Track' appeared; Workout WorkoutValuesInput gone") + + +@and_test(expects=("nav_reach_progress_images",)) +def test_reach_progress_images(): + fresh_home() + # target: textless currentProgressImage (the title 'Progress Images' collides + # with the drawer item label). + ok = and_reach_drawer("Progress Images", target="currentProgressImage") + ok = ok and node_by_id(ui(), "progressImageIndex") is not None + record("nav_reach_progress_images", ok, + "" if ok else "feature_missing: Progress Images surface not reached from the drawer", + depth=1, jump_kind="reach", + expect="currentProgressImage + progressImageIndex ('1 / 0') + NEWER/OLDER appeared; Workout WorkoutValuesInput gone") + + +@and_test(expects=("nav_reach_settings",)) +def test_reach_settings(): + fresh_home() + ok = and_reach_drawer("Settings", target="Unit System") + ok = ok and node_by_id(ui(), "recycler_view") is not None + record("nav_reach_settings", ok, + "" if ok else "feature_missing: Settings surface not reached from the drawer", + depth=1, jump_kind="reach", + expect="'Unit System' section + Settings recycler_view appeared; Workout WorkoutValuesInput gone") + + +@and_test(expects=("nav_reach_about_drawer", "nav_reach_about_credits_vlm")) +def test_reach_about_via_drawer(): + fresh_home() + ok = and_reach_drawer("About", target="Libraries used in this app:") + record("nav_reach_about_drawer", ok, + "" if ok else "feature_missing: About surface not reached from the drawer", + depth=1, jump_kind="reach", + expect="'Libraries used in this app:' + library rows appeared; Workout WorkoutValuesInput gone") + vlm_assert("nav_reach_about_credits", + "Does this screen show a scrollable list of library/credit rows, each " + "a library name followed by its licence in parentheses (e.g. 'Apache 2.0')?", + RESULTS_DIR, tag="layout") + + +@and_test(expects=("nav_reach_workout_from_drawer",)) +def test_reach_workout_from_drawer(): + """Return to Workout via the drawer 'Workout' item FROM another destination, + proving the hub round-trips (not just Workout->X).""" + fresh_home() + # First leave Workout for Program List (proven reachable above). + left = and_reach_drawer("Program List", target="listWorkout") + # Now drawer -> Workout: WorkoutValuesInput reappears, Program List's + # listWorkout vanishes. + back_home = False + if left and open_nav_drawer(): + item = find_node(ui(), text="Workout") + back_home = bool(item) and and_reach_surface(item, WORKOUT_SRC, "listWorkout") + ok = left and back_home + record("nav_reach_workout_from_drawer", ok, + "" if ok else "behavior_wrong: drawer 'Workout' item did not restore the Workout home", + depth=1, jump_kind="reach", + expect="From Program List: WorkoutValuesInput reappeared and listWorkout disappeared after tapping drawer 'Workout'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2. Tab reaches within the Workout pager (4 tests, depth 1) — each page is a +# surface: destination-unique element appears, FREE-WORKOUT input block goes. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_tab_program", "nav_tab_program_vlm")) +def test_tab_program(): + fresh_home() + ok = and_reach_tab("PROGRAM", target="START PROGRAM", source=WORKOUT_SRC) + record("nav_tab_program", ok, + "" if ok else "behavior_wrong: PROGRAM tab did not swap in the program page", + depth=1, jump_kind="reach", + expect="'START PROGRAM' button + 'Program preview:' appeared; FREE WORKOUT's WorkoutValuesInput gone") + vlm_assert("nav_tab_program", + "Is a wide 'START PROGRAM' button shown in the content area below a " + "row of tabs, with the 'PROGRAM' tab highlighted?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("nav_tab_graphs", "nav_tab_graphs_chart_vlm")) +def test_tab_graphs(): + fresh_home() + # target: textless graphLineChart -> `ViewGroup|graphLineChart`. + ok = and_reach_tab("GRAPHS", target="graphLineChart", source=WORKOUT_SRC) + record("nav_tab_graphs", ok, + "" if ok else "behavior_wrong: GRAPHS tab did not swap in the chart page", + depth=1, jump_kind="reach", + expect="graphLineChart + zoom buttons (ALL/LAST YEAR) appeared; FREE WORKOUT's WorkoutValuesInput gone") + vlm_assert("nav_tab_graphs_chart", + "Is a line chart with plotted data points/lines rendered in the " + "content area of this screen?", + RESULTS_DIR, tag="shape") + + +@and_test(expects=("nav_tab_history",)) +def test_tab_history(): + fresh_home() + # target: textless listFilterRecord -> `ListView|listFilterRecord`. + ok = and_reach_tab("HISTORY", target="listFilterRecord", source=WORKOUT_SRC) + record("nav_tab_history", ok, + "" if ok else "behavior_wrong: HISTORY tab did not swap in the filtered-record page", + depth=1, jump_kind="reach", + expect="listFilterRecord + filterMachine appeared; FREE WORKOUT's WorkoutValuesInput gone") + + +@and_test(expects=("nav_tab_back_to_free_workout",)) +def test_tab_program_then_free_workout(): + """PROGRAM -> FREE WORKOUT: the reverse tab swap is its own reach.""" + fresh_home() + to_program = and_reach_tab("PROGRAM", target="START PROGRAM", source=WORKOUT_SRC) + # Back to FREE WORKOUT: WorkoutValuesInput reappears, START PROGRAM disappears. + tab = find_node(ui(), text="FREE WORKOUT") + to_free = to_program and tab is not None and and_reach_surface( + tab, target=WORKOUT_SRC, source="START PROGRAM") + ok = to_program and to_free + record("nav_tab_back_to_free_workout", ok, + "" if ok else "behavior_wrong: FREE WORKOUT tab did not restore the add-record page", + depth=1, jump_kind="reach", + expect="From PROGRAM: WorkoutValuesInput reappeared and START PROGRAM disappeared on FREE WORKOUT") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3. Deep chains + back-stack integrity (depth 2/3) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_exercise_detail", "nav_exercise_detail_affordance_vlm")) +def test_exercise_detail_depth2(): + """Exercises (drawer, hop 1) -> exercise row -> Exercise Detail (hop 2).""" + fresh_home() + to_list = and_reach_drawer("Exercises", target="ADD NEW EXERCISE") + deep = to_list and and_enter_exercise_detail() + ok = deep and node_by_id(ui(), "favButton") is not None + record("nav_exercise_detail", ok, + "" if ok else "feature_missing: Exercise Detail not reached from an exercise row", + depth=2, jump_kind="reach", + expect="Exercise Detail: machine_photo + EXERCISE/HISTORY tab host + favButton appeared; 'ADD NEW EXERCISE' gone") + vlm_assert("nav_exercise_detail_affordance", + "Does the top toolbar of this screen show a star (favourite) icon and " + "a trash/delete (bin) icon?", + RESULTS_DIR, tag="shape") + + +@and_test(expects=("nav_exercise_detail_back",)) +def test_exercise_detail_back_stack(): + """Deepest surface -> BACK unwinds one hop to the Exercises list.""" + fresh_home() + to_list = and_reach_drawer("Exercises", target="ADD NEW EXERCISE") + deep = to_list and and_enter_exercise_detail() + restored = False + if deep: + and_back() # pops the pushed detail + back_nodes = ui() + restored = (node_by_id(back_nodes, "addExercise") is not None + and node_by_id(back_nodes, "favButton") is None) + ok = deep and restored + record("nav_exercise_detail_back", ok, + "" if ok else "behavior_wrong: BACK from Exercise Detail did not return to the Exercises list", + depth=2, jump_kind="reach", + expect="After one BACK: Exercises addExercise restored, detail favButton gone") + + +@and_test(expects=("nav_exercise_history_subtab",)) +def test_exercise_detail_history_subtab(): + """Exercises (1) -> detail (2) -> HISTORY sub-tab (3): the sub-tab swaps the + EXERCISE info panel for the record list.""" + fresh_home() + to_list = and_reach_drawer("Exercises", target="ADD NEW EXERCISE") + deep = to_list and and_enter_exercise_detail() + hist = False + if deep: + tab = find_node(ui(), text="HISTORY") + # source: EXERCISE-tab-only textless machine_description; target: record list. + hist = tab is not None and and_reach_surface( + tab, target="listFilterRecord", source="machine_description") + ok = deep and hist + record("nav_exercise_history_subtab", ok, + "" if ok else "behavior_wrong: HISTORY sub-tab did not swap in the exercise's record list", + depth=3, jump_kind="reach", + expect="listFilterRecord appeared; EXERCISE-tab machine_description gone") + + +@and_test(expects=("nav_weight_metric_detail",)) +def test_weight_metric_detail_depth2(): + """Weight Track (drawer, hop 1) -> weight DETAILS -> metric detail (hop 2).""" + fresh_home() + to_wt = and_reach_drawer("Weight Track", target="activityLevelSpinner") + # source: the Weight-Track-only activityLevelSpinner (gone on the detail screen). + deep = to_wt and and_reach_metric_detail("weightDetailsButton", "activityLevelSpinner") + ok = deep and node_by_id(ui(), "bodymeasureChart") is not None + record("nav_weight_metric_detail", ok, + "" if ok else "feature_missing: weight metric detail not reached from a DETAILS button", + depth=2, jump_kind="reach", + expect="Metric detail: bodymeasureChart + 'Measurement history:' appeared; Weight-Track activityLevelSpinner gone") + + +@and_test(expects=("nav_weight_metric_back",)) +def test_weight_metric_back_stack(): + fresh_home() + to_wt = and_reach_drawer("Weight Track", target="activityLevelSpinner") + deep = to_wt and and_reach_metric_detail("weightDetailsButton", "activityLevelSpinner") + restored = False + if deep: + and_back() + back_nodes = ui() + restored = (node_by_id(back_nodes, "weightDetailsButton") is not None + and node_by_id(back_nodes, "bodymeasureChart") is None) + ok = deep and restored + record("nav_weight_metric_back", ok, + "" if ok else "behavior_wrong: BACK from the weight metric detail did not return to Weight Track", + depth=2, jump_kind="reach", + expect="After one BACK: weightDetailsButton restored, bodymeasureChart gone") + + +@and_test(expects=("nav_bodypart_detail",)) +def test_bodypart_detail_depth2(): + """Body Track (drawer, hop 1) -> body-part row -> measurement detail (hop 2).""" + fresh_home() + to_bt = and_reach_drawer("Body Track", target="listBodyMeasures") + deep = to_bt and and_reach_bodypart_detail() + ok = deep and node_by_id(ui(), "bodymeasureChart") is not None + record("nav_bodypart_detail", ok, + "" if ok else "feature_missing: body-part measurement detail not reached from a body-part row", + depth=2, jump_kind="reach", + expect="Body-part detail: bodymeasureChart + 'Measurement history:' appeared; Body-Track listBodyMeasures gone") + + +@and_test(expects=("nav_bodypart_back",)) +def test_bodypart_back_stack(): + fresh_home() + to_bt = and_reach_drawer("Body Track", target="listBodyMeasures") + deep = to_bt and and_reach_bodypart_detail() + restored = False + if deep: + and_back() + back_nodes = ui() + restored = (node_by_id(back_nodes, "addBodyPart") is not None + and node_by_id(back_nodes, "bodymeasureChart") is None) + ok = deep and restored + record("nav_bodypart_back", ok, + "" if ok else "behavior_wrong: BACK from the body-part detail did not return to Body Track", + depth=2, jump_kind="reach", + expect="After one BACK: addBodyPart restored, bodymeasureChart gone") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4. Profile popup -> Profile page (depth 2 via a popup menu) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_profile_page",)) +def test_profile_page_depth2(): + """Tap the toolbar avatar (imageProfile) -> popup menu (hop 1) -> 'Profile + page' -> the profile editor (hop 2).""" + fresh_home() + avatar = node_by_id(ui(), "imageProfile") + # hop 1: open the popup (a surface with the 'Profile page' item); the popup + # replaces the visible Workout surface, so WorkoutValuesInput vanishes. + popup_ok = avatar is not None and and_reach_surface( + avatar, target="Profile page", source=WORKOUT_SRC) + # hop 2: tap 'Profile page' -> editor; popup items vanish, gender/size appear. + editor_ok = False + if popup_ok: + item = find_node(ui(), text="Profile page") + editor_ok = item is not None and and_reach_surface( + item, target="gender", source="Change profile") + ok = popup_ok and editor_ok and node_by_id(ui(), "size") is not None + record("nav_profile_page", ok, + "" if ok else "feature_missing: Profile page editor not reached via the avatar popup", + depth=2, jump_kind="reach", + expect="Popup 'Profile page' item appeared; then editor gender/birthday/size appeared, popup 'Change profile' gone") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5. About via the overflow menu (distinct entry point from the drawer, depth 1) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_about_overflow",)) +def test_reach_about_via_overflow(): + fresh_home() + overflow = find_node(ui(), content_desc="More options") + # hop: open the overflow menu (its 'About' item marks the popup). + menu_ok = overflow is not None and and_reach_surface( + overflow, target="About", source=WORKOUT_SRC) + about_ok = False + if menu_ok: + item = find_node(ui(), text="About") + about_ok = item is not None and and_reach_surface( + item, target="Libraries used in this app:", source="Reset app") + ok = menu_ok and about_ok + record("nav_reach_about_overflow", ok, + "" if ok else "feature_missing: About surface not reached from the overflow menu", + depth=1, jump_kind="reach", + expect="From overflow: 'Libraries used in this app:' appeared; menu 'Reset app' item gone") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 6. PROGRAM tab -> program editor (depth 2) + back-stack unwind +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_program_editor",)) +def test_program_editor_depth2(): + """FREE WORKOUT -> PROGRAM tab (hop 1) -> EDIT -> program editor (hop 2).""" + fresh_home() + to_program = and_reach_tab("PROGRAM", target="START PROGRAM", source=WORKOUT_SRC) + edit = False + if to_program: + btn = node_by_id(ui(), "editProgram") + # target: textless program_pagertab -> `HorizontalScrollView|program_pagertab`. + edit = btn is not None and and_reach_surface( + btn, target="program_pagertab", source="START PROGRAM") + ok = to_program and edit and node_by_id(ui(), "workout_name") is not None + record("nav_program_editor", ok, + "" if ok else "feature_missing: program editor not reached from the PROGRAM tab EDIT button", + depth=2, jump_kind="reach", + expect="Editor: program_pagertab (EDITOR/INFO) + workout_name appeared; START PROGRAM gone") + + +@and_test(expects=("nav_program_editor_back",)) +def test_program_editor_back_stack(): + """Deepest pushed surface -> BACK unwinds to the Workout pager.""" + fresh_home() + to_program = and_reach_tab("PROGRAM", target="START PROGRAM", source=WORKOUT_SRC) + edit = False + if to_program: + btn = node_by_id(ui(), "editProgram") + edit = btn is not None and and_reach_surface( + btn, target="program_pagertab", source="START PROGRAM") + restored = False + if edit: + and_back() # pops the editor -> pager returns + back_nodes = ui() + restored = (node_by_id(back_nodes, "startStopProgram") is not None + and node_by_id(back_nodes, "program_pagertab") is None) + ok = edit and restored + record("nav_program_editor_back", ok, + "" if ok else "behavior_wrong: BACK from the program editor did not return to the Workout pager", + depth=2, jump_kind="reach", + expect="After one BACK: startStopProgram restored, program_pagertab (editor) gone") + + +TESTS = [ + # drawer reaches (depth 1) + test_reach_exercises, + test_reach_program_list, + test_reach_weight_track, + test_reach_body_track, + test_reach_progress_images, + test_reach_settings, + test_reach_about_via_drawer, + test_reach_workout_from_drawer, + # tab reaches (depth 1) + test_tab_program, + test_tab_graphs, + test_tab_history, + test_tab_program_then_free_workout, + # deep chains + back-stack (depth 2/3) + test_exercise_detail_depth2, + test_exercise_detail_back_stack, + test_exercise_detail_history_subtab, + test_weight_metric_detail_depth2, + test_weight_metric_back_stack, + test_bodypart_detail_depth2, + test_bodypart_back_stack, + # popup + overflow + program editor + test_profile_page_depth2, + test_reach_about_via_overflow, + test_program_editor_depth2, + test_program_editor_back_stack, +] + +if __name__ == "__main__": + run_suite(TESTS, "navigation") diff --git a/android/brodeurlv-fastnfitness/tests/test_android_states.py b/android/brodeurlv-fastnfitness/tests/test_android_states.py new file mode 100644 index 0000000000000000000000000000000000000000..2fa03f7cacd3db9cdca18188f125d17aeb5219b2 --- /dev/null +++ b/android/brodeurlv-fastnfitness/tests/test_android_states.py @@ -0,0 +1,949 @@ +#!/usr/bin/env python3 +"""STATES lane — FastNFitness (com.easyfitness.debug). + +Owns widget-state transitions (checked / selected / focused) each PAIRED with the +app-authored consequence, page/dialog state machines, and SETTINGS/mode +persistence across process death. Every test reads the state BEFORE from a fresh +ui(), drives the user path, reads AFTER from a fresh ui(), asserts the transition +AND its consequence, then restores. + +Run: python3 test_android_states.py +""" +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ── shared helpers ────────────────────────────────────────────────────────────── + +def _mmss(s): + """Parse 'mm:ss' -> total seconds; None if unparseable.""" + try: + m, ss = s.strip().split(":") + return int(m) * 60 + int(ss) + except Exception: + return None + + +def _open_drawer(): + """The nav drawer opens reliably via the hamburger button on this device + (the edge-swipe gesture does not register). Returns the fresh tree.""" + ham = find_node(ui(), content_desc="Open navigation drawer") + if ham: + tap_node(ham) + settle("tap") + return ui() + + +def and_enter_drawer_item(label): + """Open the drawer and tap a drawer item, then confirm we left the Workout + home (the tab strip disappears). Counts ONE crossed surface, so a depth>=1 + record backed by this call is honest. Returns (ok, fresh_nodes).""" + before = and_showing() + nodes = _open_drawer() + item = find_node_ci(nodes, label) + if item is None: + return False, nodes + tap_node(item) + settle("tap") + after_nodes = ui() + after = and_showing(after_nodes) + # The drawer replaces the whole fragment; require a material surface change. + if not surface_changed(before, after): + return False, after_nodes + and_enter(label) + return True, after_nodes + + +def and_enter_settings(): + return and_enter_drawer_item("Settings") + + +def and_enter_exercises(): + return and_enter_drawer_item("Exercises") + + +def and_enter_weight_track(): + return and_enter_drawer_item("Weight Track") + + +def _spinner_label(nodes, rid): + """The visible label of a Spinner: its child text1 (or any text) inside the + spinner's bounds. Some spinners render the selection as a bare TextView with + no resource-id, so fall back to that.""" + f = node_by_id(nodes, rid) + if not f or "_bounds" not in f: + return None + x1, y1, x2, y2 = f["_bounds"] + labelled = None + for n in nodes: + c = n.get("_center") + if not c: + continue + if x1 - 2 <= c[0] <= x2 + 2 and y1 - 2 <= c[1] <= y2 + 2: + if n.get("resource-id", "").endswith("text1") and n.get("text", "").strip(): + return n.get("text") + if n.get("text", "").strip() and n.get("resource-id", "") == "": + labelled = n.get("text") + return labelled + + +def _tab_selected(nodes, label): + n = find_node_ci(nodes, label) + return (n or {}).get("selected") if n else None + + +def _checkbox_for(nodes, label): + """The CheckBox belonging to the preference row whose title is `label` + (same y-band, on the right).""" + lbl = find_node_ci(nodes, label) + if not lbl or "_center" not in lbl: + return None + ly = lbl["_center"][1] + cands = [c for c in find_by_class(nodes, "CheckBox") + if "_center" in c and abs(c["_center"][1] - ly) < 90] + return cands[0] if cands else None + + +def _summary_below(nodes, label, prefix): + """A summary line beginning with `prefix` that sits just below `label`.""" + lbl = find_node_ci(nodes, label) + if not lbl or "_center" not in lbl: + return None + ly = lbl["_center"][1] + for n in nodes: + c = n.get("_center") + if c and prefix in n.get("text", "") and 0 < c[1] - ly < 90: + return n.get("text") + return None + + +def _open_rest_dialog(): + """Precondition the Free Workout home so ADD opens the Rest-time countdown: + restTimeCheckBox CHECKED and a non-zero rest time. Returns the dialog tree, + or None if the dialog never appeared.""" + nodes = ui() + cb = node_by_id(nodes, "restTimeCheckBox") + if cb is None: + return None + if cb.get("checked") != "true": + tap_node(cb) + nodes = ui() + rt = node_by_id(nodes, "restTimeEditText") + if rt is not None and rt.get("text", "").strip() in ("", "0"): + type_text(rt, "60") + nodes = ui() + back() # dismiss keyboard (no nav on the home) + settle("keyboard") + add = node_by_id(ui(), "addperff") + if add is None: + return None + tap_node(add) + settle("tap") + settle("tap") + dlg = ui() + return dlg if node_by_id(dlg, "chronoValue") else None + + +def _close_rest_dialog(): + ex = node_by_id(ui(), "btn_exit") + if ex: + tap_node(ex) + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1. restTimeCheckBox toggle -> ADD opens the Rest-time dialog (consequence) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_resttime_checkbox_dialog", + "states_resttime_checkbox_dialog_vlm")) +def test_resttime_checkbox_opens_dialog(): + restart_app() + wait_for_foreground() + nodes = ui() + cb = node_by_id(nodes, "restTimeCheckBox") + if cb is None: + record("states_resttime_checkbox_dialog", False, + "feature_missing: no restTimeCheckBox on Free Workout", + depth=0, jump_kind="transition", + expect="checked false->true; ADD then opens Rest-time dialog") + return + before = cb.get("checked") + if before != "true": + tap_node(cb) + nodes = ui() + cb = node_by_id(nodes, "restTimeCheckBox") + after = (cb or {}).get("checked") + dlg = _open_rest_dialog() + dialog_shown = dlg is not None and node_by_id(dlg, "chronoValue") is not None + ok = after == "true" and dialog_shown + record("states_resttime_checkbox_dialog", ok, + "" if ok else "behavior_wrong: checkbox checked but ADD did not open " + "the Rest-time countdown dialog", + depth=0, jump_kind="transition", + expect="restTimeCheckBox checked=true; ADD opens Rest-time dialog " + "(chronoValue present)") + # VLM on the countdown donut ring while the dialog is up. + vlm_assert("states_resttime_checkbox_dialog", + "Is a large circular progress ring (a grey circle with a coloured " + "arc segment) drawn around a mm:ss countdown time in the centre of " + "the screen?", RESULTS_DIR, tag="shape") + _close_rest_dialog() + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2. restTimeCheckBox UNCHECKED -> ADD adds directly, NO dialog (consequence) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_resttime_unchecked_no_dialog",)) +def test_resttime_unchecked_no_dialog(): + restart_app() + wait_for_foreground() + nodes = ui() + cb = node_by_id(nodes, "restTimeCheckBox") + if cb is None: + record("states_resttime_unchecked_no_dialog", False, + "feature_missing: no restTimeCheckBox on Free Workout", + depth=0, jump_kind="transition", + expect="checked true->false; ADD then adds with NO dialog") + return + if cb.get("checked") == "true": + tap_node(cb) + nodes = ui() + cb = node_by_id(nodes, "restTimeCheckBox") + unchecked = (cb or {}).get("checked") == "false" + add = node_by_id(ui(), "addperff") + tap_node(add) + settle("tap") + settle("tap") + after = ui() + no_dialog = node_by_id(after, "chronoValue") is None \ + and find_node_ci(after, "Rest time") is None + still_home = node_by_id(after, "addperff") is not None + ok = unchecked and no_dialog and still_home + record("states_resttime_unchecked_no_dialog", ok, + "" if ok else "behavior_wrong: with the checkbox unchecked, ADD still " + "opened the Rest-time dialog (or left the Workout screen)", + depth=0, jump_kind="transition", + expect="restTimeCheckBox checked=false; ADD adds inline, no countdown " + "dialog, still on Workout home") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3. Rest-countdown chronoValue DECREASES over time (page state transition) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_countdown_decreases", + "states_countdown_decreases_vlm")) +def test_countdown_decreases(): + restart_app() + wait_for_foreground() + dlg = _open_rest_dialog() + if dlg is None: + record("states_countdown_decreases", False, + "setup_failed: could not open the Rest-time countdown dialog", + depth=1, jump_kind="transition", + expect="chronoValue decreases over ~3s") + return + and_enter("rest_dialog") + c0 = node_by_id(dlg, "chronoValue") + t0 = _mmss(c0.get("text")) if c0 else None + time.sleep(3.0) + c1 = node_by_id(ui(), "chronoValue") + t1 = _mmss(c1.get("text")) if c1 else None + ok = t0 is not None and t1 is not None and t1 < t0 + record("states_countdown_decreases", ok, + "" if ok else f"behavior_wrong: chronoValue did not decrease " + f"(t0={t0}, t1={t1})", + depth=1, jump_kind="transition", + expect=f"chronoValue counts down (observed {t0}s -> lower after ~3s)") + vlm_assert("states_countdown_decreases", + "Is the coloured progress arc a BLUE segment sitting on a grey " + "circular ring near the top of the donut?", RESULTS_DIR, tag="color") + _close_rest_dialog() + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4. Settings "Show Audio Player" checkbox toggle PERSISTS across process death +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_settings_audio_persists",)) +def test_settings_audio_persists(): + restart_app() + wait_for_foreground() + ok_nav, s = and_enter_settings() + if not ok_nav: + record("states_settings_audio_persists", False, + "setup_failed: could not reach Settings via the drawer", + depth=1, jump_kind="transition", + expect="Show Audio Player checked flip survives restart") + return + cb = _checkbox_for(s, "Show Audio Player") + if cb is None: + record("states_settings_audio_persists", False, + "feature_missing: no 'Show Audio Player' checkbox in Settings", + depth=1, jump_kind="transition", + expect="Show Audio Player checked flip survives restart") + return + before = cb.get("checked") + tap_node(cb) + settle("tap") + s2 = ui() + cb2 = _checkbox_for(s2, "Show Audio Player") + flipped = (cb2 or {}).get("checked") != before + # persistence probe + force_stop_and_relaunch() + wait_for_foreground() + ok_nav2, s3 = and_enter_settings() + cb3 = _checkbox_for(s3, "Show Audio Player") if ok_nav2 else None + persisted = cb3 is not None and cb3.get("checked") != before + ok = flipped and persisted + record("states_settings_audio_persists", ok, + "" if ok else "behavior_wrong: 'Show Audio Player' did not flip or did " + "not retain the new state after force-stop + relaunch", + depth=1, jump_kind="transition", + expect=f"Show Audio Player checked {before}->{'true' if before=='false' else 'false'} " + f"and still that after restart") + if cb3 is not None: # restore original state + tap_node(cb3) + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5. Settings "Beep" checkbox flips (checked transition) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_settings_beep_toggle", + "states_settings_beep_toggle_vlm")) +def test_settings_beep_toggle(): + restart_app() + wait_for_foreground() + ok_nav, s = and_enter_settings() + if not ok_nav: + record("states_settings_beep_toggle", False, + "setup_failed: could not reach Settings via the drawer", + depth=1, jump_kind="transition", + expect="Beep checked true<->false") + return + cb = _checkbox_for(s, "Beep") + if cb is None: + record("states_settings_beep_toggle", False, + "feature_missing: no 'Beep' checkbox in Settings", + depth=1, jump_kind="transition", + expect="Beep checked true<->false") + return + before = cb.get("checked") + tap_node(cb) + settle("tap") + s2 = ui() + cb2 = _checkbox_for(s2, "Beep") + after = (cb2 or {}).get("checked") + ok = after is not None and after != before + record("states_settings_beep_toggle", ok, + "" if ok else f"behavior_wrong: Beep checkbox did not flip " + f"(before={before}, after={after})", + depth=1, jump_kind="transition", + expect=f"Beep checked {before}->{after}") + vlm_assert("states_settings_beep_toggle", + "In this Settings list, is the 'Beep' row's control a small square " + "checkbox (checked ones show a filled square with a white tick)?", + RESULTS_DIR, tag="shape") + if cb2 is not None: # restore + tap_node(cb2) + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 6. Settings Weight-unit dialog pick -> summary changes AND persists +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_weight_unit_persists", + "states_weight_unit_persists_vlm")) +def test_weight_unit_persists(): + restart_app() + wait_for_foreground() + ok_nav, s = and_enter_settings() + if not ok_nav: + record("states_weight_unit_persists", False, + "setup_failed: could not reach Settings via the drawer", + depth=1, jump_kind="value", + expect="Weight summary contains 'lb' and persists") + return + w = find_node_ci(s, "Weight") + before = _summary_below(s, "Weight", "Preferred unit") + if w is None or before is None: + record("states_weight_unit_persists", False, + "feature_missing: no Weight unit preference with a 'Preferred unit' " + "summary", + depth=1, jump_kind="value", + expect="Weight summary contains 'lb' and persists") + return + # pick a unit different from the current one + target = "lb" if "kg" in before.lower() else "kg" + tap_node(w) + settle("tap") + # The unit picker is a radio-button dialog; the SELECTED unit shows a filled + # (coloured) radio while the others are empty rings — a mode-selection visual. + vlm_assert("states_weight_unit_persists", + "In this pop-up unit chooser (options kg, lb, st), is exactly ONE " + "option marked with a filled/solid coloured radio button while the " + "others show empty circular outlines?", RESULTS_DIR, tag="shape") + opt = find_node_ci(ui(), target) + if opt is None: + record("states_weight_unit_persists", False, + "setup_failed: unit-picker dialog did not offer the alternate unit", + depth=1, jump_kind="value", + expect=f"Weight summary contains '{target}' and persists") + return + tap_node(opt) + settle("tap") + s2 = ui() + changed = (_summary_below(s2, "Weight", "Preferred unit") or "") + changed_ok = target in changed.lower() + # persistence probe + force_stop_and_relaunch() + wait_for_foreground() + ok_nav2, s3 = and_enter_settings() + persisted_summary = _summary_below(s3, "Weight", "Preferred unit") or "" if ok_nav2 else "" + persisted = target in persisted_summary.lower() + ok = changed_ok and persisted + record("states_weight_unit_persists", ok, + "" if ok else "behavior_wrong: weight-unit summary did not change to the " + "picked unit or did not persist across restart", + depth=1, jump_kind="value", + expect=f"Weight summary contains '{target}' after pick and after restart") + # restore to the original unit + if ok_nav2: + w3 = find_node_ci(s3, "Weight") + if w3: + orig = "kg" if "kg" in before.lower() else ("lb" if "lb" in before.lower() else "st") + tap_node(w3) + settle("tap") + o = find_node_ci(ui(), orig) + if o: + tap_node(o) + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 7. activityLevelSpinner selection changes label AND persists (Weight Track) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_activity_level_persists",)) +def test_activity_level_persists(): + restart_app() + wait_for_foreground() + ok_nav, s = and_enter_weight_track() + if not ok_nav: + record("states_activity_level_persists", False, + "setup_failed: could not reach Weight Track via the drawer", + depth=1, jump_kind="value", + expect="activityLevelSpinner label = 'active' and persists") + return + als = node_by_id(s, "activityLevelSpinner") + if als is None: + record("states_activity_level_persists", False, + "feature_missing: no activityLevelSpinner on Weight Track", + depth=1, jump_kind="value", + expect="activityLevelSpinner label = 'active' and persists") + return + before = _spinner_label(s, "activityLevelSpinner") + target = "active" if (before or "").lower() != "active" else "moderate" + tap_node(als) + settle("tap") + opt = find_node_ci(ui(), target) + if opt is None: + record("states_activity_level_persists", False, + "setup_failed: activity-level dropdown did not offer the target level", + depth=1, jump_kind="value", + expect=f"activityLevelSpinner label = '{target}' and persists") + return + tap_node(opt) + settle("tap") + changed = (_spinner_label(ui(), "activityLevelSpinner") or "").lower() == target + # persistence probe + force_stop_and_relaunch() + wait_for_foreground() + ok_nav2, s3 = and_enter_weight_track() + persisted_lbl = (_spinner_label(s3, "activityLevelSpinner") or "").lower() if ok_nav2 else "" + persisted = persisted_lbl == target + ok = changed and persisted + record("states_activity_level_persists", ok, + "" if ok else "behavior_wrong: activity-level spinner did not change to " + "the picked level or did not persist across restart", + depth=1, jump_kind="value", + expect=f"activityLevelSpinner shows '{target}' after pick and after restart") + # restore original level + if ok_nav2 and before: + als3 = node_by_id(s3, "activityLevelSpinner") + if als3: + tap_node(als3) + settle("tap") + o = find_node_ci(ui(), before) + if o: + tap_node(o) + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 8. filterGraphFunction spinner selection changes the displayed label (GRAPHS) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_graph_function_spinner", + "states_graph_function_spinner_vlm")) +def test_graph_function_spinner(): + restart_app() + wait_for_foreground() + g = find_node_ci(ui(), "GRAPHS") + if g is None: + record("states_graph_function_spinner", False, + "feature_missing: no GRAPHS tab", + depth=0, jump_kind="transition", + expect="filterGraphFunction label changes to 'Weight Sum'") + return + tap_node(g) + settle("tap") + s = ui() + fgf = node_by_id(s, "filterGraphFunction") + if fgf is None: + record("states_graph_function_spinner", False, + "feature_missing: no filterGraphFunction spinner on GRAPHS", + depth=0, jump_kind="transition", + expect="filterGraphFunction label changes to 'Weight Sum'") + return + before = _spinner_label(s, "filterGraphFunction") + target = "Weight Sum" if (before or "") != "Weight Sum" else "Reps Sum" + tap_node(fgf) + settle("tap") + opt = find_node_ci(ui(), target) + if opt is None: + record("states_graph_function_spinner", False, + "setup_failed: function dropdown did not offer the target option", + depth=0, jump_kind="transition", + expect=f"filterGraphFunction label changes to '{target}'") + return + tap_node(opt) + settle("tap") + after = _spinner_label(ui(), "filterGraphFunction") + ok = after == target and after != before + record("states_graph_function_spinner", ok, + "" if ok else f"behavior_wrong: graph-function label did not change " + f"(before={before!r}, after={after!r})", + depth=0, jump_kind="transition", + expect=f"filterGraphFunction label {before!r} -> '{target}'") + vlm_assert("states_graph_function_spinner", + "Is a line/point chart with visible axes rendered in the main area " + "of this GRAPHS screen, positioned below the two dropdown filters?", + RESULTS_DIR, tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 9. filterMachine spinner selection changes the displayed label (HISTORY) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_history_filter_spinner",)) +def test_history_filter_spinner(): + restart_app() + wait_for_foreground() + h = find_node_ci(ui(), "HISTORY") + if h is None: + record("states_history_filter_spinner", False, + "feature_missing: no HISTORY tab", + depth=0, jump_kind="transition", + expect="filterMachine label changes to 'Example 1'") + return + tap_node(h) + settle("tap") + s = ui() + fm = node_by_id(s, "filterMachine") + if fm is None: + record("states_history_filter_spinner", False, + "feature_missing: no filterMachine spinner on HISTORY", + depth=0, jump_kind="transition", + expect="filterMachine label changes to 'Example 1'") + return + before = _spinner_label(s, "filterMachine") + target = "Example 1" if (before or "") != "Example 1" else "Example 2" + tap_node(fm) + settle("tap") + opt = find_node_ci(ui(), target) + if opt is None: + record("states_history_filter_spinner", False, + "setup_failed: filter dropdown did not offer the target exercise", + depth=0, jump_kind="transition", + expect=f"filterMachine label changes to '{target}'") + return + tap_node(opt) + settle("tap") + after = _spinner_label(ui(), "filterMachine") + ok = after == target and after != before + record("states_history_filter_spinner", ok, + "" if ok else f"behavior_wrong: history filter label did not change " + f"(before={before!r}, after={after!r})", + depth=0, jump_kind="transition", + expect=f"filterMachine label {before!r} -> '{target}'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 10. Weight unit spinner on Free Workout: label changes (value unchanged) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_unit_spinner_label",)) +def test_unit_spinner_label(): + restart_app() + wait_for_foreground() + s = ui() + us = node_by_id(s, "singlevalueinput_unitSpinner") + if us is None: + record("states_unit_spinner_label", False, + "feature_missing: no singlevalueinput_unitSpinner on Free Workout", + depth=0, jump_kind="transition", + expect="unit spinner label switches unit") + return + before = _spinner_label(s, "singlevalueinput_unitSpinner") + target = "kg" if (before or "") != "kg" else "st" + tap_node(us) + settle("tap") + opt = find_node_ci(ui(), target) + if opt is None: + record("states_unit_spinner_label", False, + "setup_failed: unit dropdown did not offer the target unit", + depth=0, jump_kind="transition", + expect=f"unit spinner label -> '{target}'") + return + tap_node(opt) + settle("tap") + after = _spinner_label(ui(), "singlevalueinput_unitSpinner") + ok = after == target and after != before + record("states_unit_spinner_label", ok, + "" if ok else f"behavior_wrong: unit spinner label did not change " + f"(before={before!r}, after={after!r})", + depth=0, jump_kind="transition", + expect=f"unit spinner label {before!r} -> '{target}'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 11. Tab selected-state transition (FREE WORKOUT -> GRAPHS) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_tab_selected", + "states_tab_selected_vlm")) +def test_tab_selected_transition(): + restart_app() + wait_for_foreground() + s = ui() + fw_before = _tab_selected(s, "FREE WORKOUT") + graphs_before = _tab_selected(s, "GRAPHS") + g = find_node_ci(s, "GRAPHS") + if g is None or fw_before is None: + record("states_tab_selected", False, + "feature_missing: tab strip FREE WORKOUT/GRAPHS not found", + depth=0, jump_kind="transition", + expect="GRAPHS selected false->true; FREE WORKOUT true->false") + return + tap_node(g) + settle("tap") + s2 = ui() + fw_after = _tab_selected(s2, "FREE WORKOUT") + graphs_after = _tab_selected(s2, "GRAPHS") + ok = (graphs_before == "false" and graphs_after == "true" + and fw_before == "true" and fw_after == "false") + record("states_tab_selected", ok, + "" if ok else f"behavior_wrong: tab selected-state did not move to GRAPHS " + f"(FW {fw_before}->{fw_after}, GRAPHS {graphs_before}->{graphs_after})", + depth=0, jump_kind="transition", + expect="GRAPHS selected false->true; FREE WORKOUT true->false") + vlm_assert("states_tab_selected", + "In the tab strip (FREE WORKOUT / PROGRAM / GRAPHS / HISTORY), is a " + "coloured underline indicator positioned directly beneath the GRAPHS " + "tab (and not under FREE WORKOUT)?", RESULTS_DIR, tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 12. Tab selected-state transition to HISTORY (a different tab, VLM on highlight) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_tab_history_selected", + "states_tab_history_selected_vlm")) +def test_tab_history_selected(): + restart_app() + wait_for_foreground() + s = ui() + hist_before = _tab_selected(s, "HISTORY") + h = find_node_ci(s, "HISTORY") + if h is None: + record("states_tab_history_selected", False, + "feature_missing: no HISTORY tab in the strip", + depth=0, jump_kind="transition", + expect="HISTORY selected false->true") + return + tap_node(h) + settle("tap") + s2 = ui() + hist_after = _tab_selected(s2, "HISTORY") + fw_after = _tab_selected(s2, "FREE WORKOUT") + ok = hist_before == "false" and hist_after == "true" and fw_after == "false" + record("states_tab_history_selected", ok, + "" if ok else f"behavior_wrong: HISTORY tab did not become the selected " + f"tab (HISTORY {hist_before}->{hist_after}, FW after={fw_after})", + depth=0, jump_kind="transition", + expect="HISTORY selected false->true; FREE WORKOUT no longer selected") + vlm_assert("states_tab_history_selected", + "Is the coloured underline indicator in the tab strip positioned " + "beneath the HISTORY tab?", RESULTS_DIR, tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 13. Focus transition — tapping the Reps field gives it focus (and only it) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_focus_reps_field",)) +def test_focus_reps_field(): + restart_app() + wait_for_foreground() + s = ui() + vals = sorted([n for n in s if n.get("resource-id", "").endswith("singlevalueinput_value") + and "_center" in n], key=lambda n: n["_center"][0]) + if len(vals) < 3: + record("states_focus_reps_field", False, + "feature_missing: fewer than 3 value inputs on Free Workout", + depth=0, jump_kind="transition", + expect="Reps field focused=false->true; others stay false") + return + reps = vals[1] # x-order: Sets, Reps, Weight + before = reps.get("focused") + tap_node(reps) + settle("keyboard") + s2 = ui() + vals2 = sorted([n for n in s2 if n.get("resource-id", "").endswith("singlevalueinput_value") + and "_center" in n], key=lambda n: n["_center"][0]) + reps_after = vals2[1].get("focused") if len(vals2) >= 3 else None + others_unfocused = len(vals2) >= 3 and vals2[0].get("focused") == "false" \ + and vals2[2].get("focused") == "false" + ok = before == "false" and reps_after == "true" and others_unfocused + record("states_focus_reps_field", ok, + "" if ok else f"behavior_wrong: Reps field did not become the sole " + f"focused input (before={before}, after={reps_after})", + depth=0, jump_kind="transition", + expect="Reps EditText focused false->true; Sets & Weight stay false") + back() # dismiss keyboard + + +# ══════════════════════════════════════════════════════════════════════════════ +# 14. LIST_MACHINE_FAVORITE star toggle -> MaterialFavoriteButton icon box changes +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_favorite_toggle",)) +def test_favorite_toggle(): + restart_app() + wait_for_foreground() + ok_nav, s = and_enter_exercises() + if not ok_nav: + record("states_favorite_toggle", False, + "setup_failed: could not reach Exercises via the drawer", + depth=1, jump_kind="transition", + expect="favorite star tapped; icon box changes as it fills") + return + favs = [n for n in s if n.get("resource-id", "").endswith("LIST_MACHINE_FAVORITE") + and "_center" in n] + if not favs: + record("states_favorite_toggle", False, + "feature_missing: no LIST_MACHINE_FAVORITE star in the exercise list", + depth=1, jump_kind="transition", + expect="favorite star tapped; icon box changes as it fills") + return + star = favs[0] + b0 = star.get("_bounds") + tapped = tap_node(star) + settle("tap") + s2 = ui() + favs2 = [n for n in s2 if n.get("resource-id", "").endswith("LIST_MACHINE_FAVORITE") + and "_center" in n] + # The favorite state is NOT exposed as checked/selected/content-desc; the only + # dump signal is the MaterialFavoriteButton animating its icon box (the active + # star renders larger/filled). Assert the tap was accepted and the star's icon + # box changed size as it fills — the app-authored consequence of favoriting. + b1 = favs2[0].get("_bounds") if favs2 else None + box_changed = tapped and b0 is not None and b1 is not None and b1 != b0 + record("states_favorite_toggle", box_changed, + "" if box_changed else "behavior_wrong: tapping the favorite star " + "produced no observable change in its icon box", + depth=1, jump_kind="transition", + expect="favorite star tapped; icon box changes (fills to a solid star)") + # restore: tap again to unfavorite + star_now = [n for n in ui() if n.get("resource-id", "").endswith("LIST_MACHINE_FAVORITE") + and "_center" in n] + if star_now: + tap_node(star_now[0]) + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 15. restTimeCheckBox checked-visual (VLM color/shape of the checked box) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_checkbox_checked_visual", + "states_checkbox_checked_visual_vlm")) +def test_checkbox_checked_visual(): + restart_app() + wait_for_foreground() + s = ui() + cb = node_by_id(s, "restTimeCheckBox") + if cb is None: + record("states_checkbox_checked_visual", False, + "feature_missing: no restTimeCheckBox on Free Workout", + depth=0, jump_kind="transition", + expect="checked=true; filled tick box rendered") + return + before = cb.get("checked") + if before != "true": + tap_node(cb) + s = ui() + cb = node_by_id(s, "restTimeCheckBox") + after = (cb or {}).get("checked") + ok = after == "true" + record("states_checkbox_checked_visual", ok, + "" if ok else "behavior_wrong: restTimeCheckBox did not reach checked=true", + depth=0, jump_kind="transition", + expect="restTimeCheckBox checked=true") + vlm_assert("states_checkbox_checked_visual", + "Next to the 'Activate rest countdown' label, is the checkbox a " + "filled coloured (teal/green) square containing a white check-mark?", + RESULTS_DIR, tag="color") + # restore to unchecked + cb2 = node_by_id(ui(), "restTimeCheckBox") + if cb2 and cb2.get("checked") == "true": + tap_node(cb2) + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 16. Settings checkbox checked-visual for Vibration (VLM shape) + rule flip +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_settings_vibration_toggle", + "states_settings_vibration_toggle_vlm")) +def test_settings_vibration_toggle(): + restart_app() + wait_for_foreground() + ok_nav, s = and_enter_settings() + if not ok_nav: + record("states_settings_vibration_toggle", False, + "setup_failed: could not reach Settings via the drawer", + depth=1, jump_kind="transition", + expect="Vibration checked true<->false") + return + cb = _checkbox_for(s, "Vibration") + if cb is None: + record("states_settings_vibration_toggle", False, + "feature_missing: no 'Vibration' checkbox in Settings", + depth=1, jump_kind="transition", + expect="Vibration checked true<->false") + return + before = cb.get("checked") + tap_node(cb) + settle("tap") + s2 = ui() + cb2 = _checkbox_for(s2, "Vibration") + after = (cb2 or {}).get("checked") + ok = after is not None and after != before + record("states_settings_vibration_toggle", ok, + "" if ok else f"behavior_wrong: Vibration checkbox did not flip " + f"(before={before}, after={after})", + depth=1, jump_kind="transition", + expect=f"Vibration checked {before}->{after}") + vlm_assert("states_settings_vibration_toggle", + "In this Settings list, does the 'Rest Timer Settings' section show " + "small square checkbox controls on the right of the Beep and " + "Vibration rows?", RESULTS_DIR, tag="shape") + if cb2 is not None: # restore + tap_node(cb2) + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 17. Spinner selected-highlight VLM (activity-level dropdown open) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_activity_spinner_change", + "states_activity_spinner_change_vlm")) +def test_activity_spinner_change(): + restart_app() + wait_for_foreground() + ok_nav, s = and_enter_weight_track() + if not ok_nav: + record("states_activity_spinner_change", False, + "setup_failed: could not reach Weight Track via the drawer", + depth=1, jump_kind="transition", + expect="activity spinner label sedentary->active") + return + als = node_by_id(s, "activityLevelSpinner") + if als is None: + record("states_activity_spinner_change", False, + "feature_missing: no activityLevelSpinner on Weight Track", + depth=1, jump_kind="transition", + expect="activity spinner label sedentary->active") + return + before = _spinner_label(s, "activityLevelSpinner") + target = "active" if (before or "").lower() != "active" else "moderate" + tap_node(als) + settle("tap") + # screenshot the OPEN dropdown for the VLM (list of level options visible) + vlm_assert("states_activity_spinner_change", + "Is an open dropdown/list of selectable text options (such as " + "sedentary, moderate, active) currently displayed on top of the " + "screen?", RESULTS_DIR, tag="layout") + opt = find_node_ci(ui(), target) + if opt is None: + record("states_activity_spinner_change", False, + "setup_failed: activity-level dropdown did not offer the target level", + depth=1, jump_kind="transition", + expect=f"activity spinner label -> '{target}'") + return + tap_node(opt) + settle("tap") + after = (_spinner_label(ui(), "activityLevelSpinner") or "").lower() + ok = after == target and after != (before or "").lower() + record("states_activity_spinner_change", ok, + "" if ok else f"behavior_wrong: activity-level label did not change " + f"(before={before!r}, after={after!r})", + depth=1, jump_kind="transition", + expect=f"activityLevelSpinner label {before!r} -> '{target}'") + # restore + if before: + als2 = node_by_id(ui(), "activityLevelSpinner") + if als2: + tap_node(als2) + settle("tap") + o = find_node_ci(ui(), before) + if o: + tap_node(o) + settle("tap") + + +TESTS = [ + test_resttime_checkbox_opens_dialog, + test_resttime_unchecked_no_dialog, + test_countdown_decreases, + test_settings_audio_persists, + test_settings_beep_toggle, + test_weight_unit_persists, + test_activity_level_persists, + test_graph_function_spinner, + test_history_filter_spinner, + test_unit_spinner_label, + test_tab_selected_transition, + test_tab_history_selected, + test_focus_reps_field, + test_favorite_toggle, + test_checkbox_checked_visual, + test_settings_vibration_toggle, + test_activity_spinner_change, +] + +if __name__ == "__main__": + run_suite(TESTS, "states") diff --git a/android/brodeurlv-fastnfitness/tests/test_android_structure.py b/android/brodeurlv-fastnfitness/tests/test_android_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..fd96fde4c18b93fae6dab208852c13b0ed2d866b --- /dev/null +++ b/android/brodeurlv-fastnfitness/tests/test_android_structure.py @@ -0,0 +1,600 @@ +#!/usr/bin/env python3 +"""STRUCTURE lane for FastNFitness (com.easyfitness.debug). + +Owns the GATE (app launches to foreground with its top-level surfaces present) +and TREE-SHAPE deltas (an interaction changes the view tree's shape: a tab switch +that adds/removes a whole class of widget, a dialog that adds a modal window +layer, a details card that adds input rows). Every reversible shape delta is +asserted as a count/surface change AND reversed to assert it restores. + +Cedes to other lanes: content strings -> text; checked/selected -> states; +whether a named screen is reachable -> navigation; computed values -> computation; +CRUD on records -> interaction. + +All shape deltas below were OBSERVED on the running original app: + - FREE WORKOUT tab carries 4 EditText input fields; PROGRAM / GRAPHS / HISTORY + carry 0. Switching tabs therefore drives EditText 4 -> 0 and back. + - HISTORY carries 2 filter Spinners (FREE WORKOUT carries 1). + - GRAPHS renders a graphLineChart ViewGroup that is absent on FREE WORKOUT. + - The workout details card is toggled by buttonExpandArrow; toggling it flips + the CheckBox count by exactly 1 (autoTimeCheckBox appears/disappears) and a + second tap restores it. (Direction is state-dependent across a fresh install, + so the assertion checks |delta|==1 + restore, never a fixed direction.) + - The nav drawer inflates a left_drawer ListView subtree on first open. That + subtree is a ONE-WAY tree addition within a session (the DrawerLayout retains + it once closed), so the drawer test asserts only the forward appearance. + - ADD (rest countdown on by default) opens a modal "Rest time" dialog + (chronoValue + donut_progress); a record card's editButton opens a "Record + Editor" modal (btn_update); buttonListMachine opens an exercise-picker modal + (listMachine). Each modal is dismissed with BACK and the dialog element is + then gone (the modal layer is truly removed, unlike the drawer). + - Drawer -> Exercises / Weight Track / Body Track / Settings replace the content + subtree with a list / metric-card grid / body-part list / preference recycler. +""" +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 + + +# ── local helpers ──────────────────────────────────────────────────────────── +def _n_editext(nodes): + return len(find_by_class(nodes, "EditText")) + + +def _n_spinner(nodes): + return len(find_by_class(nodes, "Spinner")) + + +def _n_checkbox(nodes): + return len(find_by_class(nodes, "CheckBox")) + + +def _on_free_workout(nodes): + """A stable fingerprint of the FREE WORKOUT home surface: its ADD button plus + the record list are both present. Used to assert a modal reversal really + landed us back home.""" + return (node_by_id(nodes, "addperff") is not None + and node_by_id(nodes, "listRecord") is not None) + + +def and_enter_drawer(): + """Open the nav drawer via the toolbar 'Open navigation drawer' affordance + (a left-edge swipe is unreliable on this build) and count one surface. Named + in the and_enter_* family so it backs a depth>=1 declaration.""" + n = find_node(ui(), content_desc="Open navigation drawer") + if not n or not tap_node(n): + return False + and_enter("drawer") + return True + + +def and_enter_drawer_item(item_text): + """Open the drawer, tap a named item, count one surface. The drawer closes + itself after the selection, replacing the content fragment.""" + if not and_enter_drawer(): + return False + n = find_node(ui(), text=item_text) or find_node_ci(ui(), item_text) + if not n or not tap_node(n): + return False + return True + + +def and_enter_modal(trigger_rid): + """Tap a resource-id trigger that opens a modal dialog and count one surface. + Returns the fresh tree after the dialog appears, or None if the trigger was + missing/untappable.""" + home = ui() + trig = node_by_id(home, trigger_rid) + if not trig or not tap_node(trig): + return None + and_enter("modal") + return ui() + + +def and_enter_rest_modal(): + """Open the rest-time countdown modal from Free Workout. The dialog only shows + when restTimeCheckBox is CHECKED and rest-seconds > 0 — and both are app-persisted + preferences that earlier tests may have toggled off, so we set the precondition + ourselves rather than trusting the seeded default. Counts one surface (and_enter) + so the depth>=1 declaration is backed. Returns the dialog tree, or None.""" + nodes = ui() + cb = node_by_id(nodes, "restTimeCheckBox") + if cb is None: + return None + if cb.get("checked") != "true": + tap_node(cb) + nodes = ui() + rt = node_by_id(nodes, "restTimeEditText") + if rt is not None and rt.get("text", "").strip() in ("", "0"): + type_text(rt, "60") + back() # dismiss keyboard (no nav on the home) + settle("keyboard") + add = node_by_id(ui(), "addperff") + if add is None or not tap_node(add): + return None + and_enter("modal") + settle("tap") + dlg = ui() + return dlg if node_by_id(dlg, "chronoValue") else None + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1. GATE — depth 0, jump_kind="none" (kept to <=30% of the module) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("structure_gate_launch", "structure_gate_tabstrip_vlm")) +def test_gate_launch(): + restart_app() + fg = wait_for_foreground() + nodes = ui() + toolbar = node_by_id(nodes, "actionToolbar") is not None + tabstrip = node_by_id(nodes, "fontes_pagertab") is not None + add = node_by_id(nodes, "addperff") is not None + ok = fg and toolbar and tabstrip and add + if not ok: + msg = ("setup_failed: app did not reach the foreground" if not fg else + "feature_missing: top-level surfaces absent " + f"(toolbar={toolbar} tabstrip={tabstrip} addBtn={add})") + else: + msg = "" + record("structure_gate_launch", ok, msg, depth=0, jump_kind="none") + # VLM (position): the four workout tabs sit side-by-side in one horizontal row. + vlm_assert("structure_gate_tabstrip", + "Near the top of the screen, are the four tab labels FREE WORKOUT, " + "PROGRAM, GRAPHS and HISTORY arranged side by side in a single " + "horizontal row (not stacked vertically)?", + RESULTS_DIR, tag="position", depth=0, jump_kind="none") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2. In-place tree-SHAPE deltas — tab switches (depth 0, transition) +# The pager swaps its whole child fragment, so the widget population changes. +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("structure_tab_free_to_program",)) +def test_tab_free_to_program(): + restart_app(); wait_for_foreground() + home = ui() + before = _n_editext(home) # FREE WORKOUT == 4 input fields + if not tap_text(home, "PROGRAM"): + record("structure_tab_free_to_program", False, + "setup_failed: PROGRAM tab label not tappable", + depth=0, jump_kind="transition", + expect="EditText 4->0 on PROGRAM, restored to 4 on FREE WORKOUT") + return + prog = ui() + after = _n_editext(prog) + prog_ok = node_by_id(prog, "startStopProgram") is not None + # reverse + tap_text(ui(), "FREE WORKOUT") + restored = _n_editext(ui()) + ok = (before == 4 and after == 0 and prog_ok and restored == before) + record("structure_tab_free_to_program", ok, + "" if ok else ("behavior_wrong: input-field count did not collapse on " + f"PROGRAM ({before}->{after}, restored {restored}, " + f"programBtn={prog_ok})"), + depth=0, jump_kind="transition", + expect="EditText 4->0 on PROGRAM, restored to 4 on FREE WORKOUT") + + +@and_test(expects=("structure_tab_free_to_graphs", "structure_graphs_chart_vlm")) +def test_tab_free_to_graphs(): + restart_app(); wait_for_foreground() + home = ui() + before = _n_editext(home) + chart_before = node_by_id(home, "graphLineChart") is not None + if not tap_text(home, "GRAPHS"): + record("structure_tab_free_to_graphs", False, + "setup_failed: GRAPHS tab label not tappable", + depth=0, jump_kind="transition", + expect="EditText 4->0 and graphLineChart appears on GRAPHS") + else: + g = ui() + after = _n_editext(g) + chart_after = node_by_id(g, "graphLineChart") is not None + tap_text(ui(), "FREE WORKOUT") + restored = _n_editext(ui()) + ok = (before == 4 and after == 0 and chart_after and not chart_before + and restored == before) + record("structure_tab_free_to_graphs", ok, + "" if ok else ("behavior_wrong: GRAPHS did not swap input fields for " + f"a chart (EditText {before}->{after}, chart " + f"{chart_before}->{chart_after}, restored {restored})"), + depth=0, jump_kind="transition", + expect="EditText 4->0 and graphLineChart appears on GRAPHS") + # VLM (shape): on the GRAPHS surface a line chart is rendered (canvas — not in + # the dump), replacing the input form. + restart_app(); wait_for_foreground() + tap_text(ui(), "GRAPHS"); ui() + vlm_assert("structure_graphs_chart", + "Does the main area of this screen show a line/point chart plotted " + "on X and Y axes (a graph), rather than a form with text input " + "fields?", + RESULTS_DIR, tag="shape", depth=0, jump_kind="transition") + + +@and_test(expects=("structure_tab_free_to_history",)) +def test_tab_free_to_history(): + restart_app(); wait_for_foreground() + home = ui() + et_before = _n_editext(home) + sp_before = _n_spinner(home) # FREE WORKOUT == 1 unit spinner + if not tap_text(home, "HISTORY"): + record("structure_tab_free_to_history", False, + "setup_failed: HISTORY tab label not tappable", + depth=0, jump_kind="transition", + expect="Spinner 1->2 (2 filters) and listFilterRecord on HISTORY") + return + h = ui() + et_after = _n_editext(h) + sp_after = _n_spinner(h) # HISTORY == 2 filter spinners + list_ok = node_by_id(h, "listFilterRecord") is not None + tap_text(ui(), "FREE WORKOUT") + restored = _n_spinner(ui()) + ok = (et_before == 4 and et_after == 0 and sp_before == 1 and sp_after == 2 + and list_ok and restored == sp_before) + record("structure_tab_free_to_history", ok, + "" if ok else ("behavior_wrong: HISTORY shape delta wrong (EditText " + f"{et_before}->{et_after}, Spinner {sp_before}->{sp_after}" + f", filteredList={list_ok}, spinner restored {restored})"), + depth=0, jump_kind="transition", + expect="Spinner 1->2 (2 filters) and listFilterRecord on HISTORY") + + +@and_test(expects=("structure_tab_program_to_graphs",)) +def test_tab_program_to_graphs(): + restart_app(); wait_for_foreground() + tap_text(ui(), "PROGRAM") + prog = ui() + prog_showing = and_showing(prog) + prog_ok = node_by_id(prog, "startStopProgram") is not None + if not tap_text(prog, "GRAPHS"): + record("structure_tab_program_to_graphs", False, + "setup_failed: GRAPHS tab label not tappable from PROGRAM", + depth=0, jump_kind="transition", + expect="PROGRAM->GRAPHS: startStopProgram gone, graphLineChart present") + return + g = ui() + g_showing = and_showing(g) + chart_ok = node_by_id(g, "graphLineChart") is not None + prog_gone = node_by_id(g, "startStopProgram") is None + changed = surface_changed(prog_showing, g_showing) + # reverse + tap_text(ui(), "PROGRAM") + prog_back = node_by_id(ui(), "startStopProgram") is not None + ok = (prog_ok and changed and chart_ok and prog_gone and prog_back) + record("structure_tab_program_to_graphs", ok, + "" if ok else ("behavior_wrong: PROGRAM->GRAPHS surface did not swap " + f"(changed={changed}, chart={chart_ok}, " + f"programGone={prog_gone}, programRestored={prog_back})"), + depth=0, jump_kind="transition", + expect="PROGRAM->GRAPHS: startStopProgram gone, graphLineChart present") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3. In-place shape delta — details card expand/collapse (depth 0, transition) +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("structure_expand_arrow_toggles",)) +def test_expand_arrow_toggles(): + restart_app(); wait_for_foreground() + home = ui() + cb0 = _n_checkbox(home) + arrow = node_by_id(home, "buttonExpandArrow") + if not arrow or not tap_node(arrow): + record("structure_expand_arrow_toggles", False, + "setup_failed: buttonExpandArrow not found/tappable", + depth=0, jump_kind="transition", + expect="details card toggle flips CheckBox count by 1 and restores") + return + settle("tap") + ex = ui() + cb1 = _n_checkbox(ex) + arrow2 = node_by_id(ex, "buttonExpandArrow") + tap_node(arrow2); settle("tap") + cb2 = _n_checkbox(ui()) + ok = (abs(cb1 - cb0) == 1 and cb2 == cb0) + record("structure_expand_arrow_toggles", ok, + "" if ok else ("behavior_wrong: expand arrow did not add/remove exactly " + f"one CheckBox row ({cb0}->{cb1}->{cb2})"), + depth=0, jump_kind="transition", + expect="details card toggle flips CheckBox count by 1 and restores") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4. Layer/modal shape deltas — a new subtree/window layer is added. +# depth 1, backed by and_enter_* (a real surface entry). +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("structure_drawer_opens", "structure_drawer_position_vlm")) +def test_drawer_opens(): + # The DrawerLayout inflates its drawer subtree lazily on first open and then + # RETAINS it (uiautomator keeps reporting it on-screen even once closed), so + # the only dump-observable shape signal is the FORWARD delta: on a fresh + # launch left_drawer is absent, and opening the drawer adds the left_drawer + # ListView plus its 8 item labels. The close is not observable in the tree, + # so this asserts the forward addition only (BACK is still pressed to leave + # the surface cleanly). Verified on the original app. + restart_app(); wait_for_foreground() + home = ui() + before = and_showing(home) + drawer_before = node_by_id(home, "left_drawer") is not None # absent when fresh + if not and_enter_drawer(): + record("structure_drawer_opens", False, + "setup_failed: could not open the navigation drawer", + depth=1, jump_kind="transition", + expect="left_drawer ListView + >=6 item labels appear (absent on fresh launch)") + else: + d = ui() + after = and_showing(d) + drawer_after = node_by_id(d, "left_drawer") is not None + items = [n for n in d if n.get("resource-id", "").endswith("drawer_itemName")] + appeared = ("ListView|left_drawer" in after + and "ListView|left_drawer" not in before) + changed = surface_changed(before, after) + and_back() + ok = (not drawer_before and drawer_after and appeared and changed + and len(items) >= 6) + record("structure_drawer_opens", ok, + "" if ok else ("behavior_wrong: drawer subtree did not appear " + f"(before={drawer_before}, after={drawer_after}, " + f"appeared={appeared}, items={len(items)}, " + f"changed={changed})"), + depth=1, jump_kind="transition", + expect="left_drawer ListView + >=6 item labels appear (absent on fresh launch)") + # VLM (position): the drawer overlays the LEFT portion of the screen. + restart_app(); wait_for_foreground() + and_enter_drawer(); ui() + vlm_assert("structure_drawer_position", + "Is a navigation menu panel overlaying the LEFT side of the screen " + "(a vertical list of menu items anchored to the left edge, with the " + "right side dimmed)?", + RESULTS_DIR, tag="position", depth=1, jump_kind="transition") + + +@and_test(expects=("structure_add_opens_dialog", "structure_rest_donut_vlm")) +def test_add_opens_dialog(): + restart_app(); wait_for_foreground() + home = ui() + before = and_showing(home) + dlg = and_enter_rest_modal() + if dlg is None: + record("structure_add_opens_dialog", False, + "setup_failed: ADD button not found/tappable", + depth=1, jump_kind="transition", + expect="rest-time modal adds chronoValue+donut_progress, gone on BACK") + else: + after = and_showing(dlg) + chrono = node_by_id(dlg, "chronoValue") is not None + donut = node_by_id(dlg, "donut_progress") is not None + exit_ok = node_by_id(dlg, "btn_exit") is not None + changed = surface_changed(before, after) + and_back() + h2 = ui() + gone = node_by_id(h2, "chronoValue") is None and _on_free_workout(h2) + ok = (chrono and donut and exit_ok and changed and gone) + record("structure_add_opens_dialog", ok, + "" if ok else ("behavior_wrong: rest-time dialog layer not " + f"added/removed (chrono={chrono}, donut={donut}, " + f"exit={exit_ok}, changed={changed}, dismissed={gone})"), + depth=1, jump_kind="transition", + expect="rest-time modal adds chronoValue+donut_progress, gone on BACK") + # VLM (shape): the rest-timer dialog draws a circular progress ring/donut. + restart_app(); wait_for_foreground() + and_enter_rest_modal() + ui() + vlm_assert("structure_rest_donut", + "Is there a dialog showing a large circular progress ring (a " + "donut/circle shape) with a countdown time in its center?", + RESULTS_DIR, tag="shape", depth=1, jump_kind="transition") + + +@and_test(expects=("structure_editbutton_opens_editor", "structure_editor_dialog_vlm")) +def test_editbutton_opens_editor(): + restart_app(); wait_for_foreground() + home = ui() + before = and_showing(home) + edits = [n for n in home if n.get("resource-id", "").endswith("editButton")] + if not edits or not tap_node(edits[0]): + record("structure_editbutton_opens_editor", False, + "setup_failed: no record editButton found on the list", + depth=1, jump_kind="transition", + expect="Record Editor modal adds btn_update, removed on BACK") + else: + and_enter("editor") + dlg = ui() + after = and_showing(dlg) + update = node_by_id(dlg, "btn_update") is not None + cancel = node_by_id(dlg, "btn_cancel") is not None + et = _n_editext(dlg) # editor exposes Sets/Reps/Weight inputs + changed = surface_changed(before, after) + and_back() + gone = node_by_id(ui(), "btn_update") is None + ok = (update and cancel and et >= 3 and changed and gone) + record("structure_editbutton_opens_editor", ok, + "" if ok else ("behavior_wrong: Record Editor modal not added/removed " + f"(update={update}, cancel={cancel}, editText={et}, " + f"changed={changed}, dismissed={gone})"), + depth=1, jump_kind="transition", + expect="Record Editor modal adds btn_update, removed on BACK") + # VLM (position): the editor is a centered modal with CANCEL/UPDATE at bottom. + restart_app(); wait_for_foreground() + edits = [n for n in ui() if n.get("resource-id", "").endswith("editButton")] + if edits and tap_node(edits[0]): + ui() + vlm_assert("structure_editor_dialog", + "Is a dialog box open in the CENTER of the screen showing numeric " + "input fields, with CANCEL and UPDATE buttons in a row at the " + "BOTTOM of the dialog?", + RESULTS_DIR, tag="position", depth=1, jump_kind="transition") + + +@and_test(expects=("structure_machine_picker_dialog",)) +def test_machine_picker_dialog(): + restart_app(); wait_for_foreground() + home = ui() + before = and_showing(home) + dlg = and_enter_modal("buttonListMachine") + if dlg is None: + record("structure_machine_picker_dialog", False, + "setup_failed: buttonListMachine not found/tappable", + depth=1, jump_kind="transition", + expect="exercise-picker modal adds listMachine list, gone on BACK") + return + after = and_showing(dlg) + list_ok = node_by_id(dlg, "listMachine") is not None + rows = [n for n in dlg if n.get("resource-id", "").endswith("LIST_MACHINE_NAME")] + changed = surface_changed(before, after) + and_back() + h2 = ui() + gone = node_by_id(h2, "listMachine") is None and _on_free_workout(h2) + ok = (list_ok and len(rows) >= 1 and changed and gone) + record("structure_machine_picker_dialog", ok, + "" if ok else ("behavior_wrong: exercise-picker modal not added/removed " + f"(list={list_ok}, rows={len(rows)}, changed={changed}, " + f"dismissed={gone})"), + depth=1, jump_kind="transition", + expect="exercise-picker modal adds listMachine list, gone on BACK") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5. Fragment-replacement shape deltas via the drawer (depth 1, transition). +# Each replaces the whole content subtree with a differently-shaped screen. +# ══════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("structure_drawer_exercises_shape", "structure_exercises_rows_vlm")) +def test_drawer_exercises_shape(): + restart_app(); wait_for_foreground() + home = ui() + add_before = node_by_id(home, "addperff") is not None # workout ADD button + if not and_enter_drawer_item("Exercises"): + record("structure_drawer_exercises_shape", False, + "setup_failed: could not reach Exercises via the drawer", + depth=1, jump_kind="transition", + expect="content becomes listMachine + addExercise; workout ADD gone") + else: + ex = ui() + list_ok = node_by_id(ex, "listMachine") is not None + add_ex = node_by_id(ex, "addExercise") is not None + search = node_by_id(ex, "searchField") is not None + workout_gone = node_by_id(ex, "addperff") is None + ok = (add_before and list_ok and add_ex and search and workout_gone) + record("structure_drawer_exercises_shape", ok, + "" if ok else ("behavior_wrong: Exercises content shape wrong " + f"(list={list_ok}, addExercise={add_ex}, " + f"search={search}, workoutGone={workout_gone})"), + depth=1, jump_kind="transition", + expect="content becomes listMachine + addExercise; workout ADD gone") + # VLM (position): each exercise row has a thumbnail on the LEFT and a star on + # the RIGHT flanking the name. + restart_app(); wait_for_foreground() + and_enter_drawer_item("Exercises"); ui() + vlm_assert("structure_exercises_rows", + "In this list, does each row place a small image/thumbnail on the " + "LEFT edge and a star icon on the RIGHT edge, with the exercise " + "name between them?", + RESULTS_DIR, tag="position", depth=1, jump_kind="transition") + + +@and_test(expects=("structure_drawer_weight_track_shape", + "structure_weight_cards_vlm")) +def test_drawer_weight_track_shape(): + restart_app(); wait_for_foreground() + if not and_enter_drawer_item("Weight Track"): + record("structure_drawer_weight_track_shape", False, + "setup_failed: could not reach Weight Track via the drawer", + depth=1, jump_kind="transition", + expect="content shows 5 metric inputs + BMI index block; ADD FAB") + else: + wt = ui() + metrics = [i for i in ("weightInput", "fatInput", "musclesInput", + "waterInput", "sizeInput") if node_by_id(wt, i)] + idx = node_by_id(wt, "imcValue") is not None # BMI index block + fab = node_by_id(wt, "addAllWeightEntries") is not None + details = [n for n in wt if n.get("text", "").upper() == "DETAILS"] + workout_gone = node_by_id(wt, "addperff") is None + ok = (len(metrics) == 5 and idx and fab and len(details) >= 4 + and workout_gone) + record("structure_drawer_weight_track_shape", ok, + "" if ok else ("behavior_wrong: Weight Track shape wrong " + f"(metrics={len(metrics)}, bmi={idx}, fab={fab}, " + f"detailsBtns={len(details)}, workoutGone={workout_gone})"), + depth=1, jump_kind="transition", + expect="content shows 5 metric inputs + BMI index block; ADD FAB") + # VLM (layout): Weight Track presents its metrics as multiple stacked cards. + restart_app(); wait_for_foreground() + and_enter_drawer_item("Weight Track"); ui() + vlm_assert("structure_weight_cards", + "Does this screen present multiple separate rectangular metric " + "cards (for example Weight, Fat, Muscles, Water) stacked as panels?", + RESULTS_DIR, tag="layout", depth=1, jump_kind="transition") + + +@and_test(expects=("structure_drawer_settings_shape", "structure_settings_list_vlm")) +def test_drawer_settings_shape(): + restart_app(); wait_for_foreground() + if not and_enter_drawer_item("Settings"): + record("structure_drawer_settings_shape", False, + "setup_failed: could not reach Settings via the drawer", + depth=1, jump_kind="transition", + expect="content becomes a preference recycler_view; workout ADD gone") + else: + st = ui() + recycler = (node_by_id(st, "recycler_view") is not None + or len(find_by_class(st, "RecyclerView")) >= 1) + workout_gone = node_by_id(st, "addperff") is None + # a settings screen exposes toggle checkboxes among its rows + checks = _n_checkbox(st) + len(find_by_class(st, "Switch")) + ok = (recycler and workout_gone and checks >= 1) + record("structure_drawer_settings_shape", ok, + "" if ok else ("behavior_wrong: Settings shape wrong " + f"(recycler={recycler}, workoutGone={workout_gone}, " + f"toggles={checks})"), + depth=1, jump_kind="transition", + expect="content becomes a preference recycler_view; workout ADD gone") + # VLM (layout): Settings is a vertical list of preference rows (title+summary). + restart_app(); wait_for_foreground() + and_enter_drawer_item("Settings"); ui() + vlm_assert("structure_settings_list", + "Is this screen a vertically scrolling list of settings/preference " + "rows, each with a title and a smaller summary line beneath it?", + RESULTS_DIR, tag="layout", depth=1, jump_kind="transition") + + +@and_test(expects=("structure_drawer_body_track_shape",)) +def test_drawer_body_track_shape(): + restart_app(); wait_for_foreground() + if not and_enter_drawer_item("Body Track"): + record("structure_drawer_body_track_shape", False, + "setup_failed: could not reach Body Track via the drawer", + depth=1, jump_kind="transition", + expect="content becomes listBodyMeasures + ADD; workout ADD gone") + return + bt = ui() + list_ok = node_by_id(bt, "listBodyMeasures") is not None + add_ok = node_by_id(bt, "addBodyPart") is not None + rows = [n for n in bt if n.get("resource-id", "").endswith("LIST_BODYPART")] + workout_gone = node_by_id(bt, "addperff") is None + ok = (list_ok and add_ok and len(rows) >= 1 and workout_gone) + record("structure_drawer_body_track_shape", ok, + "" if ok else ("behavior_wrong: Body Track shape wrong " + f"(list={list_ok}, add={add_ok}, rows={len(rows)}, " + f"workoutGone={workout_gone})"), + depth=1, jump_kind="transition", + expect="content becomes listBodyMeasures + ADD; workout ADD gone") + + +TESTS = [ + test_gate_launch, + test_tab_free_to_program, + test_tab_free_to_graphs, + test_tab_free_to_history, + test_tab_program_to_graphs, + test_expand_arrow_toggles, + test_drawer_opens, + test_add_opens_dialog, + test_editbutton_opens_editor, + test_machine_picker_dialog, + test_drawer_exercises_shape, + test_drawer_weight_track_shape, + test_drawer_settings_shape, + test_drawer_body_track_shape, +] + +if __name__ == "__main__": + run_suite(TESTS, "structure") diff --git a/android/brodeurlv-fastnfitness/tests/test_android_text.py b/android/brodeurlv-fastnfitness/tests/test_android_text.py new file mode 100644 index 0000000000000000000000000000000000000000..b692d0787e21677bb7d65aa45f2fbcff2a965f82 --- /dev/null +++ b/android/brodeurlv-fastnfitness/tests/test_android_text.py @@ -0,0 +1,584 @@ +#!/usr/bin/env python3 +"""TEXT lane — CONTENT / OUTPUT strings for FastNFitness (com.easyfitness.debug). + +This lane owns exact-string equality on text an interaction PRODUCES and on +app-unique static content a faithful recreation must reproduce: toolbar titles +that change per screen (produced by a drawer navigation), the empty-program +message, Settings preference summaries, the Weight-Track BMI "no weight +available" string, About library rows / section labels, the new-record +MACHINE_CELL name an ADD produces, the Exercises search hint and the name the +filter produces, and the Free-Workout comment the selected exercise produces. + +It does NOT own: computed numbers (computation), checked/selected bits (states), +reachability (navigation). The two opaque cores — the MPAndroidChart canvas axis +label and the on-canvas date tick labels, which never reach the view tree — go to +vlm_assert (exactly 2, as delegated). +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ── helpers ───────────────────────────────────────────────────────────────────── + +def all_text(nodes): + """Every visible text joined — for ABSENT/PRESENT string checks.""" + return " | ".join(n.get("text", "") for n in nodes if n.get("text", "").strip()) + + +def texts_of(nodes, rid_suffix): + """All texts of nodes whose resource-id LAST segment == rid_suffix.""" + return [n.get("text", "") for n in nodes + if n.get("resource-id", "").rsplit("/", 1)[-1] == rid_suffix] + + +def open_nav(): + """Open the nav drawer via the toolbar button (the edge-swipe is flaky here); + the drawer OVERLAYS the toolbar, so this is the reliable trigger.""" + btn = find_node(ui(), content_desc="Open navigation drawer") + if not btn: + return False + return tap_node(btn) + + +def and_enter_drawer_screen(item): + """Cross ONE surface: open the drawer, tap a drawer item, land on its + fragment. Backs a depth>=1 title assertion. Returns (ok, nodes).""" + if not open_nav(): + return False, ui() + n = find_node(ui(), text=item) + if not n: + return False, ui() + if not tap_node(n): + return False, ui() + and_enter(item) + return True, ui() + + +def toolbar_title_present(nodes, title): + """A toolbar-area TextView (top of screen) whose text equals `title`, + case-insensitively. The title lives in the action bar, y near the top.""" + tl = title.strip().casefold() + for n in nodes: + if not n.get("class", "").endswith("TextView"): + continue + b = n.get("_bounds") + if not b or b[1] > 320: + continue + if n.get("text", "").strip().casefold() == tl: + return True + return False + + +def go_graphs(): + """Restart and switch to the GRAPHS tab (in-pager, depth 0).""" + restart_app() + wait_for_foreground() + tap_node(find_node(ui(), text="GRAPHS")) + settle("tap") + + +# ── 1. Toolbar titles per screen (each PRODUCED by a drawer navigation) ────────── +# Workout home title is on-arrival (depth 0). The other five are produced by +# crossing one surface via the drawer (depth 1, backed by and_enter_drawer_screen). + +@and_test(expects=("text_title_workout",)) +def test_title_workout_home(): + restart_app() + wait_for_foreground() + nodes = ui() + ok = toolbar_title_present(nodes, "Fast N Fitness Debug") + record("text_title_workout", ok, + "" if ok else "behavior_wrong: Workout toolbar title is not " + "'Fast N Fitness Debug'", + depth=0, jump_kind="none", expect="toolbar title 'Fast N Fitness Debug'") + + +@and_test(expects=("text_title_exercises",)) +def test_title_exercises(): + restart_app() + wait_for_foreground() + ok, nodes = and_enter_drawer_screen("Exercises") + if not ok: + record("text_title_exercises", False, + "setup_failed: could not reach Exercises via the drawer", + depth=1, jump_kind="transition", expect="toolbar title 'Exercises'") + return + present = toolbar_title_present(nodes, "Exercises") + record("text_title_exercises", present, + "" if present else "behavior_wrong: toolbar title after selecting " + "Exercises is not 'Exercises'", + depth=1, jump_kind="transition", expect="toolbar title 'Exercises'") + + +@and_test(expects=("text_title_weight_track",)) +def test_title_weight_track(): + restart_app() + wait_for_foreground() + absent = not toolbar_title_present(ui(), "Weight Track") + ok, nodes = and_enter_drawer_screen("Weight Track") + if not ok: + record("text_title_weight_track", False, + "setup_failed: could not reach Weight Track via the drawer", + depth=1, jump_kind="transition", expect="toolbar title 'Weight Track'") + return + present = toolbar_title_present(nodes, "Weight Track") + good = absent and present + record("text_title_weight_track", good, + "" if good else "behavior_wrong: toolbar title after selecting " + "Weight Track is not 'Weight Track'", + depth=1, jump_kind="transition", expect="toolbar title 'Weight Track'") + + +@and_test(expects=("text_title_body_track",)) +def test_title_body_track(): + restart_app() + wait_for_foreground() + absent = not toolbar_title_present(ui(), "Body Track") + ok, nodes = and_enter_drawer_screen("Body Track") + if not ok: + record("text_title_body_track", False, + "setup_failed: could not reach Body Track via the drawer", + depth=1, jump_kind="transition", expect="toolbar title 'Body Track'") + return + present = toolbar_title_present(nodes, "Body Track") + good = absent and present + record("text_title_body_track", good, + "" if good else "behavior_wrong: toolbar title after selecting " + "Body Track is not 'Body Track'", + depth=1, jump_kind="transition", expect="toolbar title 'Body Track'") + + +@and_test(expects=("text_title_settings",)) +def test_title_settings(): + restart_app() + wait_for_foreground() + absent = not toolbar_title_present(ui(), "Settings") + ok, nodes = and_enter_drawer_screen("Settings") + if not ok: + record("text_title_settings", False, + "setup_failed: could not reach Settings via the drawer", + depth=1, jump_kind="transition", expect="toolbar title 'Settings'") + return + present = toolbar_title_present(nodes, "Settings") + good = absent and present + record("text_title_settings", good, + "" if good else "behavior_wrong: toolbar title after selecting " + "Settings is not 'Settings'", + depth=1, jump_kind="transition", expect="toolbar title 'Settings'") + + +@and_test(expects=("text_title_about",)) +def test_title_about(): + restart_app() + wait_for_foreground() + absent = not toolbar_title_present(ui(), "About") + ok, nodes = and_enter_drawer_screen("About") + if not ok: + record("text_title_about", False, + "setup_failed: could not reach About via the drawer", + depth=1, jump_kind="transition", expect="toolbar title 'About'") + return + present = toolbar_title_present(nodes, "About") + good = absent and present + record("text_title_about", good, + "" if good else "behavior_wrong: toolbar title after selecting " + "About is not 'About'", + depth=1, jump_kind="transition", expect="toolbar title 'About'") + + +# ── 2. PROGRAM tab produced strings (empty-program message + preview title) ────── + +@and_test(expects=("text_program_empty",)) +def test_program_empty_message(): + restart_app() + wait_for_foreground() + absent = "This program is empty" not in all_text(ui()) + tab = find_node(ui(), text="PROGRAM") + if not tab or not tap_node(tab): + record("text_program_empty", False, + "setup_failed: PROGRAM tab not found", + depth=0, jump_kind="transition", + expect="listProgramEmpty 'This program is empty'") + return + settle("tap") + nodes = ui() + node = node_by_id(nodes, "listProgramEmpty") + val = (node or {}).get("text", "") + present = val.strip().casefold() == "this program is empty" + good = absent and present + record("text_program_empty", good, + "" if good else f"behavior_wrong: empty-program text is {val!r}, " + "expected 'This program is empty'", + depth=0, jump_kind="transition", + expect="listProgramEmpty 'This program is empty'") + + +@and_test(expects=("text_program_preview_title",)) +def test_program_preview_title(): + restart_app() + wait_for_foreground() + tab = find_node(ui(), text="PROGRAM") + if not tab or not tap_node(tab): + record("text_program_preview_title", False, + "setup_failed: PROGRAM tab not found", + depth=0, jump_kind="transition", + expect="programListTitle 'Program preview:'") + return + settle("tap") + node = node_by_id(ui(), "programListTitle") + val = (node or {}).get("text", "") + ok = val.strip().casefold() == "program preview:" + record("text_program_preview_title", ok, + "" if ok else f"behavior_wrong: preview title is {val!r}, " + "expected 'Program preview:'", + depth=0, jump_kind="transition", + expect="programListTitle 'Program preview:'") + + +# ── 3. Settings preference summary strings (produced under each pref title) ────── + +@and_test(expects=("text_settings_unit_summaries",)) +def test_settings_unit_summaries(): + restart_app() + wait_for_foreground() + absent = "Preferred unit: kg" not in all_text(ui()) + ok, nodes = and_enter_drawer_screen("Settings") + if not ok: + record("text_settings_unit_summaries", False, + "setup_failed: could not reach Settings via the drawer", + depth=1, jump_kind="transition", + expect="summary 'Preferred unit: kg' / 'km' / 'cm'") + return + blob = all_text(nodes) + have_kg = "Preferred unit: kg" in blob + have_km = "Preferred unit: km" in blob + have_cm = "Preferred unit: cm" in blob + good = absent and have_kg and have_km and have_cm + record("text_settings_unit_summaries", good, + "" if good else "behavior_wrong: Settings unit summaries missing " + f"(kg={have_kg} km={have_km} cm={have_cm})", + depth=1, jump_kind="transition", + expect="summaries 'Preferred unit: kg/km/cm'") + + +@and_test(expects=("text_settings_section_header",)) +def test_settings_section_header(): + restart_app() + wait_for_foreground() + absent = "Unit System" not in all_text(ui()) + ok, nodes = and_enter_drawer_screen("Settings") + if not ok: + record("text_settings_section_header", False, + "setup_failed: could not reach Settings via the drawer", + depth=1, jump_kind="transition", + expect="section header 'Unit System'") + return + blob = all_text(nodes) + present = ("Unit System" in blob) and ("UI Settings" in blob) + good = absent and present + record("text_settings_section_header", good, + "" if good else "behavior_wrong: Settings section headers " + "'Unit System'/'UI Settings' not found", + depth=1, jump_kind="transition", + expect="section headers 'Unit System' + 'UI Settings'") + + +# ── 4. Free-Workout comment produced from the selected exercise ───────────────── +# Numbers vary with recorded data (computation owns the numbers), so assert the +# STABLE produced shape: a Min:/Max: range carrying the exercise's unit. + +@and_test(expects=("text_workout_comment_range",)) +def test_workout_comment_range(): + restart_app() + wait_for_foreground() + node = node_by_id(ui(), "singlevalueinput_comment") + val = (node or {}).get("text", "") + if node is None: + record("text_workout_comment_range", False, + "feature_missing: no singlevalueinput_comment on Free Workout", + depth=0, jump_kind="none", expect="comment 'Min:...lb - Max:...lb'") + return + low = val.replace(" ", "").casefold() + ok = ("min:" in low) and ("max:" in low) and ("lb" in low) + record("text_workout_comment_range", ok, + "" if ok else f"behavior_wrong: comment {val!r} is not a " + "'Min:...lb - Max:...lb' range", + depth=0, jump_kind="none", + expect="comment reads 'Min:lb - Max:lb'") + + +# ── 5. Weight-Track BMI "no weight available" (produced by absent weight data) ── + +@and_test(expects=("text_weight_no_data",)) +def test_weight_no_data(): + restart_app() + wait_for_foreground() + absent = "no weight available" not in all_text(ui()) + ok, nodes = and_enter_drawer_screen("Weight Track") + if not ok: + record("text_weight_no_data", False, + "setup_failed: could not reach Weight Track via the drawer", + depth=1, jump_kind="transition", + expect="imcViewText 'no weight available'") + return + node = node_by_id(nodes, "imcViewText") + val = (node or {}).get("text", "") + present = val.strip().casefold() == "no weight available" + good = absent and present + record("text_weight_no_data", good, + "" if good else f"behavior_wrong: BMI text is {val!r}, " + "expected 'no weight available'", + depth=1, jump_kind="transition", + expect="imcViewText 'no weight available'") + + +# ── 6. About content a faithful recreation reproduces ─────────────────────────── +# Library rows + section label + the "Database version:" LABEL (NOT the number 26, +# which is source-derivable). Heading is the app name. + +@and_test(expects=("text_about_library_rows",)) +def test_about_library_rows(): + restart_app() + wait_for_foreground() + absent = "MPAndroidChart" not in all_text(ui()) + ok, nodes = and_enter_drawer_screen("About") + if not ok: + record("text_about_library_rows", False, + "setup_failed: could not reach About via the drawer", + depth=1, jump_kind="transition", + expect="library rows MPAndroidChart / SmartTabLayout / SweetAlertDialog") + return + blob = all_text(nodes) + have_chart = "MPAndroidChart" in blob + have_tab = "SmartTabLayout" in blob + have_sweet = "SweetAlertDialog" in blob + good = absent and have_chart and have_tab and have_sweet + record("text_about_library_rows", good, + "" if good else "behavior_wrong: About library rows missing " + f"(MPAndroidChart={have_chart} SmartTabLayout={have_tab} " + f"SweetAlertDialog={have_sweet})", + depth=1, jump_kind="transition", + expect="rows 'MPAndroidChart' + 'SmartTabLayout' + 'SweetAlertDialog'") + + +@and_test(expects=("text_about_db_label",)) +def test_about_db_version_label(): + restart_app() + wait_for_foreground() + absent = "Database version:" not in all_text(ui()) + ok, nodes = and_enter_drawer_screen("About") + if not ok: + record("text_about_db_label", False, + "setup_failed: could not reach About via the drawer", + depth=1, jump_kind="transition", + expect="label 'Database version:'") + return + blob = all_text(nodes) + have_label = "Database version:" in blob + have_libhdr = "Libraries used in this app:" in blob + good = absent and have_label and have_libhdr + record("text_about_db_label", good, + "" if good else "behavior_wrong: About labels 'Database version:' / " + f"'Libraries used in this app:' missing (db={have_label} " + f"libs={have_libhdr})", + depth=1, jump_kind="transition", + expect="labels 'Database version:' + 'Libraries used in this app:'") + + +@and_test(expects=("text_about_heading",)) +def test_about_heading(): + restart_app() + wait_for_foreground() + ok, nodes = and_enter_drawer_screen("About") + if not ok: + record("text_about_heading", False, + "setup_failed: could not reach About via the drawer", + depth=1, jump_kind="transition", + expect="About heading 'Fast N Fitness Debug'") + return + # The app-name heading is a body TextView (below the toolbar title), so match + # the string anywhere in About's content. + present = "Fast N Fitness Debug" in all_text(nodes) + record("text_about_heading", present, + "" if present else "behavior_wrong: About app-name heading " + "'Fast N Fitness Debug' not found", + depth=1, jump_kind="transition", + expect="About heading 'Fast N Fitness Debug'") + + +# ── 7. New-record MACHINE_CELL name PRODUCED by ADD ───────────────────────────── +# Uncheck restTimeCheckBox first to avoid the countdown dialog. Assert only the +# exercise NAME string the action produced — the reps/weight numbers belong to +# computation. + +@and_test(expects=("text_added_record_name",)) +def test_added_record_machine_name(): + restart_app() + wait_for_foreground() + nodes = ui() + machine = node_by_id(nodes, "editMachine") + exercise = (machine or {}).get("text", "").strip() + if not exercise: + record("text_added_record_name", False, + "setup_failed: no editMachine / selected exercise on Free Workout", + depth=0, jump_kind="transition", expect="MACHINE_CELL == selected exercise") + return + cb = node_by_id(nodes, "restTimeCheckBox") + if cb is not None and cb.get("checked") == "true": + tap_node(cb) + settle("tap") + nodes = ui() + add = node_by_id(nodes, "addperff") or find_node_ci(nodes, "ADD") + if not add or not tap_node(add): + record("text_added_record_name", False, + "setup_failed: ADD button not found/tappable", + depth=0, jump_kind="transition", expect="MACHINE_CELL == selected exercise") + return + settle("tap") + settle("tap") + cells = texts_of(ui(), "MACHINE_CELL") + present = bool(cells) and cells[0].strip().casefold() == exercise.casefold() + record("text_added_record_name", present, + "" if present else f"behavior_wrong: new record MACHINE_CELL is " + f"{cells[0] if cells else None!r}, expected {exercise!r}", + depth=0, jump_kind="transition", + expect=f"new record MACHINE_CELL reads {exercise!r}") + + +# ── 8. Exercises search: hint string + the name the filter PRODUCES ───────────── + +@and_test(expects=("text_exercises_hint",)) +def test_exercises_search_hint(): + restart_app() + wait_for_foreground() + ok, nodes = and_enter_drawer_screen("Exercises") + if not ok: + record("text_exercises_hint", False, + "setup_failed: could not reach Exercises via the drawer", + depth=1, jump_kind="transition", + expect="searchField hint 'Filter by exercise name'") + return + node = node_by_id(nodes, "searchField") + val = (node or {}).get("text", "") + present = val.strip().casefold() == "filter by exercise name" + record("text_exercises_hint", present, + "" if present else f"behavior_wrong: search hint is {val!r}, " + "expected 'Filter by exercise name'", + depth=1, jump_kind="transition", + expect="searchField hint 'Filter by exercise name'") + + +@and_test(expects=("text_exercises_filter_result",)) +def test_exercises_filter_result(): + restart_app() + wait_for_foreground() + ok, nodes = and_enter_drawer_screen("Exercises") + if not ok: + record("text_exercises_filter_result", False, + "setup_failed: could not reach Exercises via the drawer", + depth=1, jump_kind="transition", + expect="filtered list shows only 'Example 1'") + return + before = texts_of(nodes, "LIST_MACHINE_NAME") + if "Example 1" not in before or "Example 2" not in before: + record("text_exercises_filter_result", False, + f"setup_failed: exercise list did not start with both examples ({before})", + depth=1, jump_kind="transition", + expect="filtered list shows only 'Example 1'") + return + field = node_by_id(nodes, "searchField") + type_text(field, "Example 1") + hide_keyboard() + after = texts_of(ui(), "LIST_MACHINE_NAME") + produced = [t for t in after if t.strip()] + good = produced == ["Example 1"] + record("text_exercises_filter_result", good, + "" if good else f"behavior_wrong: after filtering by 'Example 1' the " + f"list shows {produced}, expected only ['Example 1']", + depth=1, jump_kind="transition", + expect="filtered LIST_MACHINE_NAME == ['Example 1']") + + +# ── 9. Tab strip labels (asserted as CONTENT — one such test only) ────────────── + +@and_test(expects=("text_tab_labels",)) +def test_tab_strip_labels(): + restart_app() + wait_for_foreground() + blob = all_text(ui()) + labels = ["FREE WORKOUT", "PROGRAM", "GRAPHS", "HISTORY"] + missing = [t for t in labels if t not in blob] + ok = not missing + record("text_tab_labels", ok, + "" if ok else f"behavior_wrong: tab strip missing labels {missing}", + depth=0, jump_kind="none", + expect="tabs 'FREE WORKOUT' 'PROGRAM' 'GRAPHS' 'HISTORY'") + + +# ── 10. VLM (exactly 2) — opaque on-canvas chart text absent from the view tree ── +# The MPAndroidChart is a rendered canvas; its axis label and date ticks never +# reach the dump (verified: none of these strings appear in ui()). These are the +# two legitimate opaque-text cores for this lane. + +@and_test(expects=("text_chart_axis_label_vlm",)) +def test_chart_axis_label_vlm(): + go_graphs() + # Confirm the target text really is dump-invisible before delegating to VLM. + dump_absent = "Weight Sum(" not in all_text(ui()) + if not dump_absent: + # If it DID reach the tree it is a rule assertion, not VLM — record it so. + record("text_chart_axis_label_vlm", False, + "behavior_wrong: axis label unexpectedly reached the view tree " + "(should be canvas-rendered)", + depth=0, jump_kind="none", tag="content", + expect="on-canvas axis label 'Example 2/Weight Sum(kg)'") + return + vlm_assert("text_chart_axis_label", + "In the line-chart area, is the label text 'Example 2/Weight " + "Sum(kg)' drawn near the bottom-right corner of the chart, just " + "above the axis?", + RESULTS_DIR, depth=0, jump_kind="none", tag="content") + + +@and_test(expects=("text_chart_date_ticks_vlm",)) +def test_chart_date_ticks_vlm(): + go_graphs() + # These month tick labels are canvas-drawn (verified absent from ui()). + vlm_assert("text_chart_date_ticks", + "Along the horizontal axis at the BOTTOM of the line chart, are " + "abbreviated calendar date labels shown (for example '18-May', " + "'22-Jun', '27-Jul')?", + RESULTS_DIR, depth=0, jump_kind="none", tag="position") + + +# ── suite ─────────────────────────────────────────────────────────────────────── + +TESTS = [ + test_title_workout_home, + test_title_exercises, + test_title_weight_track, + test_title_body_track, + test_title_settings, + test_title_about, + test_program_empty_message, + test_program_preview_title, + test_settings_unit_summaries, + test_settings_section_header, + test_workout_comment_range, + test_weight_no_data, + test_about_library_rows, + test_about_db_version_label, + test_about_heading, + test_added_record_machine_name, + test_exercises_search_hint, + test_exercises_filter_result, + test_tab_strip_labels, + test_chart_axis_label_vlm, + test_chart_date_ticks_vlm, +] + +if __name__ == "__main__": + run_suite(TESTS, "text") diff --git a/android/brodeurlv-fastnfitness/tests/test_manifest.json b/android/brodeurlv-fastnfitness/tests/test_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..25ba6ede93f62dcae6ba6c2e7781af29ce635fac --- /dev/null +++ b/android/brodeurlv-fastnfitness/tests/test_manifest.json @@ -0,0 +1,827 @@ +{ + "manifest_version": 1, + "kit_api_version": 1, + "task_id": "fastnfitness", + "baseline_model": "claude-opus-4-8", + "baseline_package": "", + "total": 131, + "manifest_sha": "e53e223d6b35", + "tests": [ + { + "name": "computation::computation_add_reps_12", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_add_reps_15", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_add_reps_3", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_add_reps_7", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_add_sets_2", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_add_sets_4", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_add_sets_5", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_add_weight_125", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_add_weight_80", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_add_weight_88", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_editor_reps_9", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_card_action_icons_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_create_count_grows", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_create_reps", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_create_reps_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_create_sets", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_create_then_edit_sequence", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_exercise_search_filter", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_history_filter_machine", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_history_filter_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_multi_edit_middle_keeps_others", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_multi_stack_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_multi_two_records", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_persist_across_kill", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_persist_second_record", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_record_in_history", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_record_in_history_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_seq_machine_then_reps", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_two_identical_adds", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_update_cancel_unchanged", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_update_reps", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_update_reps_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_update_weight", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_bodypart_back", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_bodypart_detail", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_exercise_detail", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_exercise_detail_affordance_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_exercise_detail_back", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_exercise_history_subtab", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_profile_page", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_program_editor", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_program_editor_back", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_about_credits_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_about_drawer", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_about_overflow", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_body_track", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_exercises", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_program_list", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_progress_images", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_settings", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_weight_track", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_weight_widgets_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_workout_from_drawer", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_tab_back_to_free_workout", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_tab_graphs", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_tab_graphs_chart_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_tab_history", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_tab_program", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_tab_program_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_weight_metric_back", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_weight_metric_detail", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "states::states_activity_level_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_activity_spinner_change", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_activity_spinner_change_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_checkbox_checked_visual", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_checkbox_checked_visual_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_countdown_decreases", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_countdown_decreases_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_favorite_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_focus_reps_field", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_graph_function_spinner", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_graph_function_spinner_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_history_filter_spinner", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_resttime_checkbox_dialog", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_resttime_checkbox_dialog_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_resttime_unchecked_no_dialog", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_settings_audio_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_settings_beep_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_settings_beep_toggle_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_settings_vibration_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_settings_vibration_toggle_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_tab_history_selected", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_tab_history_selected_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_tab_selected", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_tab_selected_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_unit_spinner_label", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_weight_unit_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_weight_unit_persists_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "structure::structure_add_opens_dialog", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_drawer_body_track_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_drawer_exercises_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_drawer_opens", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_drawer_position_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_drawer_settings_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_drawer_weight_track_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_editbutton_opens_editor", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_editor_dialog_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_exercises_rows_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_expand_arrow_toggles", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_launch", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_tabstrip_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_graphs_chart_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_machine_picker_dialog", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_rest_donut_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_list_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_tab_free_to_graphs", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_tab_free_to_history", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_tab_free_to_program", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_tab_program_to_graphs", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_weight_cards_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "text::text_about_db_label", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_about_heading", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_about_library_rows", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_added_record_name", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_chart_axis_label_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_chart_date_ticks_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_exercises_filter_result", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_exercises_hint", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_program_empty", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_program_preview_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_section_header", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_unit_summaries", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_tab_labels", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_title_about", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_title_body_track", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_title_exercises", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_title_settings", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_title_weight_track", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_title_workout", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_weight_no_data", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_workout_comment_range", + "module": "text", + "baseline_status": "passed" + } + ], + "ignored": [], + "vlm_assertions": [ + { + "name": "interaction::interaction_create_reps_vlm", + "module": "interaction", + "tag": "position" + }, + { + "name": "interaction::interaction_update_reps_vlm", + "module": "interaction", + "tag": "shape" + }, + { + "name": "interaction::interaction_multi_stack_vlm", + "module": "interaction", + "tag": "layout" + }, + { + "name": "interaction::interaction_record_in_history_vlm", + "module": "interaction", + "tag": "position" + }, + { + "name": "interaction::interaction_history_filter_vlm", + "module": "interaction", + "tag": "content" + }, + { + "name": "interaction::interaction_card_action_icons_vlm", + "module": "interaction", + "tag": "position" + }, + { + "name": "navigation::nav_reach_weight_widgets_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_reach_about_credits_vlm", + "module": "navigation", + "tag": "layout" + }, + { + "name": "navigation::nav_tab_program_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_tab_graphs_chart_vlm", + "module": "navigation", + "tag": "shape" + }, + { + "name": "navigation::nav_exercise_detail_affordance_vlm", + "module": "navigation", + "tag": "shape" + }, + { + "name": "states::states_resttime_checkbox_dialog_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_countdown_decreases_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_settings_beep_toggle_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_weight_unit_persists_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_graph_function_spinner_vlm", + "module": "states", + "tag": "position" + }, + { + "name": "states::states_tab_selected_vlm", + "module": "states", + "tag": "position" + }, + { + "name": "states::states_tab_history_selected_vlm", + "module": "states", + "tag": "position" + }, + { + "name": "states::states_checkbox_checked_visual_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_settings_vibration_toggle_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_activity_spinner_change_vlm", + "module": "states", + "tag": "layout" + }, + { + "name": "structure::structure_gate_tabstrip_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_graphs_chart_vlm", + "module": "structure", + "tag": "shape" + }, + { + "name": "structure::structure_drawer_position_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_rest_donut_vlm", + "module": "structure", + "tag": "shape" + }, + { + "name": "structure::structure_editor_dialog_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_exercises_rows_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_weight_cards_vlm", + "module": "structure", + "tag": "layout" + }, + { + "name": "structure::structure_settings_list_vlm", + "module": "structure", + "tag": "layout" + }, + { + "name": "text::text_chart_axis_label_vlm", + "module": "text", + "tag": "content" + }, + { + "name": "text::text_chart_date_ticks_vlm", + "module": "text", + "tag": "position" + } + ], + "vlm_total": 31, + "n_vlm_unverified": 0, + "vlm_log_found": true +} \ No newline at end of file diff --git a/android/brodeurlv-fastnfitness/vlm_assertions.json b/android/brodeurlv-fastnfitness/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..4efef0a264640c389502f973ed59b6277382d363 --- /dev/null +++ b/android/brodeurlv-fastnfitness/vlm_assertions.json @@ -0,0 +1,643 @@ +{ + "schema_version": 2, + "instance_id": "android/brodeurlv-fastnfitness", + "grading": { + "mode": "inline", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 31, + "with_verdict": 31, + "calibrated": 0, + "usable": null, + "scored_records": 31, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "states_resttime_checkbox_dialog_vlm", + "screenshot": "states_resttime_checkbox_dialog_vlm.png", + "assertion": "Is a large circular progress ring (a grey circle with a coloured arc segment) drawn around a mm:ss countdown time in the centre of the screen?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_resttime_checkbox_dialog", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_countdown_decreases_vlm", + "screenshot": "states_countdown_decreases_vlm.png", + "assertion": "Is the coloured progress arc a BLUE segment sitting on a grey circular ring near the top of the donut?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_countdown_decreases", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_settings_beep_toggle_vlm", + "screenshot": "states_settings_beep_toggle_vlm.png", + "assertion": "In this Settings list, is the 'Beep' row's control a small square checkbox (checked ones show a filled square with a white tick)?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_settings_beep_toggle", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_weight_unit_persists_vlm", + "screenshot": "states_weight_unit_persists_vlm.png", + "assertion": "In this pop-up unit chooser (options kg, lb, st), is exactly ONE option marked with a filled/solid coloured radio button while the others show empty circular outlines?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_weight_unit_persists", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_graph_function_spinner_vlm", + "screenshot": "states_graph_function_spinner_vlm.png", + "assertion": "Is a line/point chart with visible axes rendered in the main area of this GRAPHS screen, positioned below the two dropdown filters?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "states_graph_function_spinner", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_tab_selected_vlm", + "screenshot": "states_tab_selected_vlm.png", + "assertion": "In the tab strip (FREE WORKOUT / PROGRAM / GRAPHS / HISTORY), is a coloured underline indicator positioned directly beneath the GRAPHS tab (and not under FREE WORKOUT)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "states_tab_selected", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_tab_history_selected_vlm", + "screenshot": "states_tab_history_selected_vlm.png", + "assertion": "Is the coloured underline indicator in the tab strip positioned beneath the HISTORY tab?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "states_tab_history_selected", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_checkbox_checked_visual_vlm", + "screenshot": "states_checkbox_checked_visual_vlm.png", + "assertion": "Next to the 'Activate rest countdown' label, is the checkbox a filled coloured (teal/green) square containing a white check-mark?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_checkbox_checked_visual", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_settings_vibration_toggle_vlm", + "screenshot": "states_settings_vibration_toggle_vlm.png", + "assertion": "In this Settings list, does the 'Rest Timer Settings' section show small square checkbox controls on the right of the Beep and Vibration rows?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_settings_vibration_toggle", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_activity_spinner_change_vlm", + "screenshot": "states_activity_spinner_change_vlm.png", + "assertion": "Is an open dropdown/list of selectable text options (such as sedentary, moderate, active) currently displayed on top of the screen?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "states_activity_spinner_change", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_chart_axis_label_vlm", + "screenshot": "text_chart_axis_label_vlm.png", + "assertion": "In the line-chart area, is the label text 'Example 2/Weight Sum(kg)' drawn near the bottom-right corner of the chart, just above the axis?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "text_chart_axis_label", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_chart_date_ticks_vlm", + "screenshot": "text_chart_date_ticks_vlm.png", + "assertion": "Along the horizontal axis at the BOTTOM of the line chart, are abbreviated calendar date labels shown (for example '18-May', '22-Jun', '27-Jul')?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "text_chart_date_ticks", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_create_reps_vlm", + "screenshot": "interaction_create_reps_vlm.png", + "assertion": "In the list of workout records under the date header, is the very first (top) record row showing the repetitions value 731?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "interaction_create_reps", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_update_reps_vlm", + "screenshot": "interaction_update_reps_vlm.png", + "assertion": "Is a modal editor dialog (a card titled 'Record Editor' with input fields and UPDATE / CANCEL buttons) shown centered on top of the screen, overlaying the record list behind it?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "interaction_update_reps", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_multi_stack_vlm", + "screenshot": "interaction_multi_stack_vlm.png", + "assertion": "In the workout record list, are there at least three record rows stacked vertically one below another, each showing a sets / reps / weight value block on its right side?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "interaction_multi_stack", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_record_in_history_vlm", + "screenshot": "interaction_record_in_history_vlm.png", + "assertion": "Is the HISTORY tab currently selected and showing a vertical list of workout record cards (each with an exercise name and sets/reps/weight values)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "interaction_record_in_history", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_history_filter_vlm", + "screenshot": "interaction_history_filter_vlm.png", + "assertion": "In this filtered history list, does every visible record row show the SAME exercise name ('Example 1'), with no other exercise names present?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "interaction_history_filter", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_card_action_icons_vlm", + "screenshot": "interaction_card_action_icons_vlm.png", + "assertion": "Does each workout record row show a row of small action icons (copy, edit and delete) on its right-hand side?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "interaction_card_action_icons", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_gate_tabstrip_vlm", + "screenshot": "structure_gate_tabstrip_vlm.png", + "assertion": "Near the top of the screen, are the four tab labels FREE WORKOUT, PROGRAM, GRAPHS and HISTORY arranged side by side in a single horizontal row (not stacked vertically)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_gate_tabstrip", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_graphs_chart_vlm", + "screenshot": "structure_graphs_chart_vlm.png", + "assertion": "Does the main area of this screen show a line/point chart plotted on X and Y axes (a graph), rather than a form with text input fields?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "structure_graphs_chart", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_drawer_position_vlm", + "screenshot": "structure_drawer_position_vlm.png", + "assertion": "Is a navigation menu panel overlaying the LEFT side of the screen (a vertical list of menu items anchored to the left edge, with the right side dimmed)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_drawer_position", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_rest_donut_vlm", + "screenshot": "structure_rest_donut_vlm.png", + "assertion": "Is there a dialog showing a large circular progress ring (a donut/circle shape) with a countdown time in its center?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "structure_rest_donut", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_editor_dialog_vlm", + "screenshot": "structure_editor_dialog_vlm.png", + "assertion": "Is a dialog box open in the CENTER of the screen showing numeric input fields, with CANCEL and UPDATE buttons in a row at the BOTTOM of the dialog?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_editor_dialog", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_exercises_rows_vlm", + "screenshot": "structure_exercises_rows_vlm.png", + "assertion": "In this list, does each row place a small image/thumbnail on the LEFT edge and a star icon on the RIGHT edge, with the exercise name between them?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_exercises_rows", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_weight_cards_vlm", + "screenshot": "structure_weight_cards_vlm.png", + "assertion": "Does this screen present multiple separate rectangular metric cards (for example Weight, Fat, Muscles, Water) stacked as panels?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "structure_weight_cards", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_settings_list_vlm", + "screenshot": "structure_settings_list_vlm.png", + "assertion": "Is this screen a vertically scrolling list of settings/preference rows, each with a title and a smaller summary line beneath it?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "structure_settings_list", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_weight_widgets_vlm", + "screenshot": "nav_reach_weight_widgets_vlm.png", + "assertion": "Are there four cards arranged in a two-by-two grid, labelled 'Weight', 'Fat', 'Muscles' and 'Water', each with a 'DETAILS' button at its bottom?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_reach_weight_widgets", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_about_credits_vlm", + "screenshot": "nav_reach_about_credits_vlm.png", + "assertion": "Does this screen show a scrollable list of library/credit rows, each a library name followed by its licence in parentheses (e.g. 'Apache 2.0')?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "nav_reach_about_credits", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_tab_program_vlm", + "screenshot": "nav_tab_program_vlm.png", + "assertion": "Is a wide 'START PROGRAM' button shown in the content area below a row of tabs, with the 'PROGRAM' tab highlighted?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_tab_program", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_tab_graphs_chart_vlm", + "screenshot": "nav_tab_graphs_chart_vlm.png", + "assertion": "Is a line chart with plotted data points/lines rendered in the content area of this screen?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "nav_tab_graphs_chart", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_exercise_detail_affordance_vlm", + "screenshot": "nav_exercise_detail_affordance_vlm.png", + "assertion": "Does the top toolbar of this screen show a star (favourite) icon and a trash/delete (bin) icon?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "nav_exercise_detail_affordance", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + } + ], + "merged_from_files": 1, + "source_shapes": { + "list": 1 + } +} \ No newline at end of file diff --git a/android/chrisboyle-sgtpuzzles/LICENCE b/android/chrisboyle-sgtpuzzles/LICENCE new file mode 100644 index 0000000000000000000000000000000000000000..b455f53907c16567fad5ca0ff1f007bfad8bcf90 --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/LICENCE @@ -0,0 +1,32 @@ +This software is copyright (c) 2004-2024 Simon Tatham. + +Portions copyright Richard Boulton, James Harvey, Mike Pinna, Jonas +Kölker, Dariusz Olszewski, Michael Schierl, Lambros Lambrou, Bernd +Schmidt, Steffen Bauer, Lennard Sprong, Rogier Goossens, Michael +Quevillon, Asher Gordon, Didi Kohen, Ben Harris, Chris Boyle and +Phil Tunstall. + +The notice below applies to the source as distributed at +https://github.com/chrisboyle/sgtpuzzles and does not apply to +the additional graphics distributed in the Google Play Store +version. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation files +(the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of the Software, +and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/android/chrisboyle-sgtpuzzles/instance.json b/android/chrisboyle-sgtpuzzles/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..7dd083b95b0ce1d44ff726fd01de9410676dddb6 --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "android/chrisboyle-sgtpuzzles", + "platform": "android", + "repo": "https://github.com/chrisboyle/sgtpuzzles", + "commit": "d1e10eb57dd80af4999e698a9ab31f546e9a0b9d", + "patches": [], + "package": "name.boyle.chris.sgtpuzzles", + "license": null +} diff --git a/android/chrisboyle-sgtpuzzles/reference/launch.sh b/android/chrisboyle-sgtpuzzles/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8 --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/reference/launch.sh @@ -0,0 +1,9 @@ +#!/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 1 diff --git a/android/chrisboyle-sgtpuzzles/tests/android_computation_eval.json b/android/chrisboyle-sgtpuzzles/tests/android_computation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..d46f196c2a4a5d7c4de41c4e60b4e07c329de17c --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/tests/android_computation_eval.json @@ -0,0 +1,258 @@ +{ + "module": "computation", + "total": 24, + "passed": 24, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 14, + "passed": 14, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 10, + "passed": 10, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.7143, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 24, + "depth_ge1": 24, + "depth_ge2": 18, + "value": 24, + "vlm_fine": 7 + }, + "results": [ + { + "test": "computation_net_denominator_5x5", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "status denominator 25 (Active: N/25)" + }, + { + "test": "computation_net_grid_5x5_vlm", + "passed": true, + "message": "VLM: Q='Is the puzzle board a square grid of exactly 5 columns by 5 rows (25 cells), outlined by a red border?' A=YES expect=YES", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Is the puzzle board a square grid of exactly 5 columns by 5 rows (25 cells), outlined by a red border?", + "tag": "size" + }, + { + "test": "computation_net_denominator_7x7", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "status denominator 49 (Active: N/49)" + }, + { + "test": "computation_net_grid_7x7_vlm", + "passed": true, + "message": "VLM: Q='Is the puzzle board a square grid that is clearly finer than a 5x5 grid, having noticeably MORE than 5 columns and more than 5 rows of small cells?' A=YES expect=YES", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Is the puzzle board a square grid that is clearly finer than a 5x5 grid, having noticeably MORE than 5 columns and more than 5 rows of small cells?", + "tag": "size" + }, + { + "test": "computation_net_denominator_9x9", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "status denominator 81 (Active: N/81)" + }, + { + "test": "computation_net_grid_9x9_vlm", + "passed": true, + "message": "VLM: Q='Is the puzzle board a large dense square grid of about 9 columns by 9 rows (roughly 80 small cells), clearly finer than a simple 5x5 grid?' A=YES expect=YES", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Is the puzzle board a large dense square grid of about 9 columns by 9 rows (roughly 80 small cells), clearly finer than a simple 5x5 grid?", + "tag": "size" + }, + { + "test": "computation_net_denominator_11x11", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "status denominator 121 (Active: N/121)" + }, + { + "test": "computation_net_denominator_5x5_wrapping", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "status denominator 25 (Active: N/25) for 5x5 wrapping" + }, + { + "test": "computation_net_denominator_distinct", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "5x5 -> denominator 25 and 7x7 -> denominator 49 (distinct)" + }, + { + "test": "computation_show_solution_autosolved", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "status_bar == 'Auto-solved.' after Show solution" + }, + { + "test": "computation_solved_render_vlm", + "passed": true, + "message": "VLM: Q='In the puzzle grid, are the small square endpoint tiles lit up bright CYAN/turquoise and joined together by cyan lines (a solved, fully-connected network), rather than dark blue and disconnected?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In the puzzle grid, are the small square endpoint tiles lit up bright CYAN/turquoise and joined together by cyan lines (a solved, fully-connected network), rather than dark blue and disconnected?", + "tag": "color" + }, + { + "test": "computation_restart_after_solve", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "status_bar: 'Auto-solved.' -> Restart -> matches 'Active: N/T'" + }, + { + "test": "computation_unsolved_render_vlm", + "passed": true, + "message": "VLM: Q='In the puzzle grid, are most of the small square endpoint tiles a dark BLUE colour (unlit / not connected), rather than all lit bright cyan?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In the puzzle grid, are most of the small square endpoint tiles a dark BLUE colour (unlit / not connected), rather than all lit bright cyan?", + "tag": "color" + }, + { + "test": "computation_new_game_denominator", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "status denominator == 25 after New game at 5x5" + }, + { + "test": "computation_new_game_layout_vlm", + "passed": true, + "message": "VLM: Q='Does the 5x5 grid show blue endpoint tiles and short black wire/line segments arranged across the cells (a freshly generated network puzzle), rather than an empty featureless grid?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Does the 5x5 grid show blue endpoint tiles and short black wire/line segments arranged across the cells (a freshly generated network puzzle), rather than an empty featureless grid?", + "tag": "content" + }, + { + "test": "computation_gameid_deterministic", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "same id both opens (5x5:82d815475cdee4129ed3299e1) and identical status both loads (Active: 3/25)" + }, + { + "test": "computation_gameid_encodes_size", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "game id size-prefix == '7x7' (and denominator 49) for the 7x7 board" + }, + { + "test": "computation_keen_digits_4x4", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Keen 4x4 digit buttons exactly {1,2,3,4}" + }, + { + "test": "computation_keen_grid_4x4_vlm", + "passed": true, + "message": "VLM: Q='Is the Keen board a square grid of exactly 4 columns by 4 rows (16 cells), with small arithmetic clues like '7+' or '2÷' printed in the top-left of some cages?' A=YES expect=YES", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Is the Keen board a square grid of exactly 4 columns by 4 rows (16 cells), with small arithmetic clues like '7+' or '2÷' printed in the top-left of some cages?", + "tag": "size" + }, + { + "test": "computation_keen_digits_6x6", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Keen 6x6 digit buttons exactly {1,2,3,4,5,6}" + }, + { + "test": "computation_keen_grid_6x6_vlm", + "passed": true, + "message": "VLM: Q='Is the Keen board a square grid of exactly 6 columns by 6 rows (36 cells), clearly finer/denser than a 4x4 grid?' A=YES expect=YES", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Is the Keen board a square grid of exactly 6 columns by 6 rows (36 cells), clearly finer/denser than a 4x4 grid?", + "tag": "size" + }, + { + "test": "computation_keen_digit_count_scales", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "digit-button count 4 for 4x4 and 6 for 6x6 (scales with N)" + }, + { + "test": "computation_keen_digit_entry_vlm", + "passed": true, + "message": "VLM: Q='Is the digit '3' displayed as a large coloured number inside one of the grid cells (an entered value in a cell), not merely on the number buttons along the bottom of the screen?' A=YES expect=YES", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Is the digit '3' displayed as a large coloured number inside one of the grid cells (an entered value in a cell), not merely on the number buttons along the bottom of the screen?", + "tag": "content" + }, + { + "test": "computation_keen_clue_render_vlm", + "passed": true, + "message": "VLM: Q='In the top-left corner of some cages, are there small arithmetic clues made of a number and an operator (like '5+', '2÷', '30×' or '3-')?' A=YES expect=YES", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In the top-left corner of some cages, are there small arithmetic clues made of a number and an operator (like '5+', '2÷', '30×' or '3-')?", + "tag": "content" + } + ] +} \ No newline at end of file diff --git a/android/chrisboyle-sgtpuzzles/tests/android_interaction_eval.json b/android/chrisboyle-sgtpuzzles/tests/android_interaction_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..ed1815c024ad57e1a7d7a35ceacc789db068e9d9 --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/tests/android_interaction_eval.json @@ -0,0 +1,203 @@ +{ + "module": "interaction", + "total": 18, + "passed": 18, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 9, + "passed": 9, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 9, + "passed": 9, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 1.0, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 18, + "depth_ge1": 9, + "depth_ge2": 0, + "value": 13, + "vlm_fine": 7 + }, + "results": [ + { + "test": "interaction_star_toggle_to_starred", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Black Box: section Others -> Starred after one long-press" + }, + { + "test": "interaction_star_toggle_to_starred_vlm", + "passed": true, + "message": "VLM: Q='In the 'Starred' section near the top, is there a puzzle row that shows a small STAR icon/badge next to its thumbnail?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In the 'Starred' section near the top, is there a puzzle row that shows a small STAR icon/badge next to its thumbnail?", + "tag": "shape" + }, + { + "test": "interaction_star_toggle_to_others", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Net: section Starred -> Others after one long-press" + }, + { + "test": "interaction_star_toggle_to_others_vlm", + "passed": true, + "message": "VLM: Q='Directly under the 'Starred' heading at the very top, do the puzzle rows there show a small star badge on their thumbnails?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Directly under the 'Starred' heading at the very top, do the puzzle rows there show a small star badge on their thumbnails?", + "tag": "position" + }, + { + "test": "interaction_star_toggle_round_trip", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Cube section others -> starred -> others across two long-presses" + }, + { + "test": "interaction_star_multi_record", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "Bridges=Starred, Dominosa=Starred, Cube=Others (control intact) after starring two rows" + }, + { + "test": "interaction_star_multi_record_vlm", + "passed": true, + "message": "VLM: Q='Directly under the 'Starred' heading at the top, are there several puzzle rows each showing a star badge on its thumbnail (more than one starred row)?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Directly under the 'Starred' heading at the top, are there several puzzle rows each showing a star badge on its thumbnail (more than one starred row)?", + "tag": "position" + }, + { + "test": "interaction_star_persists_death", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "Dominosa in Starred both after the long-press AND after force-stop + relaunch" + }, + { + "test": "interaction_star_persists_death_vlm", + "passed": true, + "message": "VLM: Q='Under the 'Starred' heading at the top of the list, is there a puzzle row with a star badge on its thumbnail?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Under the 'Starred' heading at the top of the list, is there a puzzle row with a star badge on its thumbnail?", + "tag": "position" + }, + { + "test": "interaction_game_resume_after_death", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "GamePlay resumed with toolbar title 'Net' after force-stop + relaunch (same in-progress puzzle)" + }, + { + "test": "interaction_net_solution_undo_redo", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "status_bar: 'Auto-solved. ' -> Undo -> 'Active: N/25' -> Redo -> 'Auto-solved. '" + }, + { + "test": "interaction_net_solution_undo_redo_solved_vlm", + "passed": true, + "message": "VLM: Q='In the puzzle grid, are the small square endpoint tiles lit up bright CYAN/turquoise and joined by cyan lines (a solved, fully-connected look)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In the puzzle grid, are the small square endpoint tiles lit up bright CYAN/turquoise and joined by cyan lines (a solved, fully-connected look)?", + "tag": "color" + }, + { + "test": "interaction_net_solution_undo_redo_unsolved_vlm", + "passed": true, + "message": "VLM: Q='In the puzzle grid, are most of the small square endpoint tiles a dark BLUE colour (unlit / not connected), rather than all lit bright cyan?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In the puzzle grid, are most of the small square endpoint tiles a dark BLUE colour (unlit / not connected), rather than all lit bright cyan?", + "tag": "color" + }, + { + "test": "interaction_net_solution_restart", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "status_bar: 'Auto-solved. ' -> Restart -> 'Active: N/25' form" + }, + { + "test": "interaction_net_tile_tap_vlm", + "passed": true, + "message": "VLM: Q='Does the grid show puzzle tiles with short wire/line segments drawn on them pointing in various directions (an in-progress network puzzle), rather than a blank featureless grid?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Does the grid show puzzle tiles with short wire/line segments drawn on them pointing in various directions (an in-progress network puzzle), rather than a blank featureless grid?", + "tag": "shape" + }, + { + "test": "interaction_keen_digit_entry", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Keen: tapped a cell, then digit '3', then Backspace (controls present and each tap dispatched)" + }, + { + "test": "interaction_keen_digit_shown_vlm", + "passed": true, + "message": "VLM: Q='Is the digit '3' displayed inside one of the grid cells (a large coloured number entered in a cell), not only on the number buttons along the bottom of the screen?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Is the digit '3' displayed inside one of the grid cells (a large coloured number entered in a cell), not only on the number buttons along the bottom of the screen?", + "tag": "content" + }, + { + "test": "interaction_keen_digit_cleared_vlm", + "passed": true, + "message": "VLM: Q='After clearing, is the previously selected grid cell now EMPTY (no large entered digit inside it, showing at most a small arithmetic clue)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: After clearing, is the previously selected grid cell now EMPTY (no large entered digit inside it, showing at most a small arithmetic clue)?", + "tag": "content" + } + ] +} \ No newline at end of file diff --git a/android/chrisboyle-sgtpuzzles/tests/android_navigation_eval.json b/android/chrisboyle-sgtpuzzles/tests/android_navigation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..212d5aaa58b98ae9d1b92d5dfdb616d91fd8d6bd --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/tests/android_navigation_eval.json @@ -0,0 +1,273 @@ +{ + "module": "navigation", + "total": 26, + "passed": 26, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 19, + "passed": 19, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 7, + "passed": 7, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.3684, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 26, + "depth_ge1": 26, + "depth_ge2": 11, + "value": 0, + "vlm_fine": 3 + }, + "results": [ + { + "test": "nav_reach_gameplay", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "GamePlay: game_view + status_bar + Navigate up present; chooser table no longer showing" + }, + { + "test": "nav_reach_gameplay_vlm", + "passed": true, + "message": "VLM: Q='Is a single square puzzle grid drawn in the center of the screen (a game board), rather than a vertical list of text rows?' A=YES expect=YES", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is a single square puzzle grid drawn in the center of the screen (a game board), rather than a vertical list of text rows?", + "tag": "content" + }, + { + "test": "nav_gameplay_back_chooser", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "chooser table present and game_view gone after one BACK" + }, + { + "test": "nav_reach_settings_chooser", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Settings: recycler_view with >=2 Switch rows present; chooser scrollView no longer showing" + }, + { + "test": "nav_reach_settings_chooser_vlm", + "passed": true, + "message": "VLM: Q='Is this a settings screen showing a vertical scrollable list of labelled rows, at least two of which have an ON/OFF toggle switch?' A=YES expect=YES", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is this a settings screen showing a vertical scrollable list of labelled rows, at least two of which have an ON/OFF toggle switch?", + "tag": "layout" + }, + { + "test": "nav_settings_back_chooser", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "chooser scrollView present and recycler_view gone after one BACK" + }, + { + "test": "nav_reach_settings_from_game", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Game menu -> Settings: recycler_view present; 'New game' menu item gone" + }, + { + "test": "nav_reach_help", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "HelpActivity: 'Help: Contents' title + WebView present; popup 'Send feedback' item gone" + }, + { + "test": "nav_reach_help_vlm", + "passed": true, + "message": "VLM: Q='Does the screen show a page of readable help/documentation text (paragraphs or a list of topic links), like a web help page?' A=YES expect=YES", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Does the screen show a page of readable help/documentation text (paragraphs or a list of topic links), like a web help page?", + "tag": "content" + }, + { + "test": "nav_help_back_chooser", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "chooser table present and 'Help: Contents' gone after BACK" + }, + { + "test": "nav_reach_custom_dialog", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "'Net configuration' dialog with OK + GAME ID… buttons present; type-menu radio list no longer showing" + }, + { + "test": "nav_reach_custom_dialog_vlm", + "passed": true, + "message": "VLM: Q='Is a configuration dialog box shown centered on the screen, overlaying the game behind it, with an 'OK' button inside it?' A=YES expect=YES", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is a configuration dialog box shown centered on the screen, overlaying the game behind it, with an 'OK' button inside it?", + "tag": "position" + }, + { + "test": "nav_reach_gameid_dialog", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "'Net game selection' dialog (alertTitle + EditText) present; 'Net configuration' title no longer showing" + }, + { + "test": "nav_type_menu_open", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "RadioButton group + '5x5' preset appear over the game" + }, + { + "test": "nav_type_menu_open_vlm", + "passed": true, + "message": "VLM: Q='Is a vertical list of size options (like '5x5', '7x7', '9x9') shown in a popup, with radio-button circles down the right-hand side and exactly one circle selected?' A=YES expect=YES", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is a vertical list of size options (like '5x5', '7x7', '9x9') shown in a popup, with radio-button circles down the right-hand side and exactly one circle selected?", + "tag": "position" + }, + { + "test": "nav_type_menu_back_closes", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "RadioButton list gone and game_view present after one BACK" + }, + { + "test": "nav_game_menu_open", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "'New game' + 'Settings' + 'Show solution' items appear over the game" + }, + { + "test": "nav_game_menu_back_closes", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "'New game' item gone and game_view present after one BACK" + }, + { + "test": "nav_custom_back_to_game", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "'Net configuration' title gone and game_view present after BACK" + }, + { + "test": "nav_backstack_2hop_unwinds", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "BACK #1 -> game_view (config gone); BACK #2 -> chooser table (game_view gone)" + }, + { + "test": "nav_backstack_deepest_to_home", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "chooser table present, game_view + 'game selection' gone after unwinding every layer with BACK" + }, + { + "test": "nav_reach_settings_subscreen", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "'Long-press timeout (ms)' row present; top-level 'About this app' row no longer showing" + }, + { + "test": "nav_switch_puzzle_title", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "GamePlay title 'Keen' present and 'Net' gone after opening Keen" + }, + { + "test": "nav_reach_load_picker", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "a non-app-package activity (system picker) is resumed on Load…; BACK returns to the app" + }, + { + "test": "nav_gameplay_toolbar_back_vlm", + "passed": true, + "message": "VLM: Q='At the very top-left of the screen, is there a left-pointing arrow (a back/up navigation arrow) in the toolbar?' A=YES expect=YES", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: At the very top-left of the screen, is there a left-pointing arrow (a back/up navigation arrow) in the toolbar?", + "tag": "shape" + }, + { + "test": "nav_back_to_chooser_list_vlm", + "passed": true, + "message": "VLM: Q='Is a vertical list/grid of puzzle rows shown (each row a small icon beside a line of text), rather than a single centered game board?' A=YES expect=YES", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "VLM YES: Is a vertical list/grid of puzzle rows shown (each row a small icon beside a line of text), rather than a single centered game board?", + "tag": "layout" + } + ] +} \ No newline at end of file diff --git a/android/chrisboyle-sgtpuzzles/tests/android_states_eval.json b/android/chrisboyle-sgtpuzzles/tests/android_states_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..8fd4a853417673dbd1cda2d512219fdbe13456b9 --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/tests/android_states_eval.json @@ -0,0 +1,137 @@ +{ + "module": "states", + "total": 11, + "passed": 11, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 5, + "passed": 5, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 6, + "passed": 6, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 1.2, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 11, + "depth_ge1": 11, + "depth_ge2": 4, + "value": 0, + "vlm_fine": 6 + }, + "results": [ + { + "test": "states_net_radio_select", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "9x9 radio checked=true, prior preset now checked=false; status_bar denominator -> '/81' (puzzle reloaded)" + }, + { + "test": "states_net_radio_dot_vlm", + "passed": true, + "message": "VLM: Q='In this vertical list of size presets, does exactly ONE row have a filled/solid radio-button dot on its right side while all the other rows show empty (hollow) radio circles?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In this vertical list of size presets, does exactly ONE row have a filled/solid radio-button dot on its right side while all the other rows show empty (hollow) radio circles?", + "tag": "shape" + }, + { + "test": "states_net_radio_gridsize_vlm", + "passed": true, + "message": "VLM: Q='Is the puzzle grid a fairly dense square grid of many small cells (about 9 by 9), rather than a coarse grid of only a few large cells?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is the puzzle grid a fairly dense square grid of many small cells (about 9 by 9), rather than a coarse grid of only a few large cells?", + "tag": "size" + }, + { + "test": "states_net_radio_switch_back", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "7x7 checked & 5x5 unchecked (status '/49'), then 5x5 checked & 7x7 unchecked (status '/25')" + }, + { + "test": "states_type_menu_selected_vlm", + "passed": true, + "message": "VLM: Q='In this list of puzzle sizes, is the single selected size marked by a filled radio dot positioned at the far RIGHT of its row (in line with that size's text label)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In this list of puzzle sizes, is the single selected size marked by a filled radio dot positioned at the far RIGHT of its row (in line with that size's text label)?", + "tag": "position" + }, + { + "test": "states_keen_radio_select", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "'4x4 Easy' radio checked=true (prior unchecked); on-screen digit buttons shrink from {1..6} to {1..4}" + }, + { + "test": "states_keen_radio_dot_vlm", + "passed": true, + "message": "VLM: Q='In this list of Keen difficulty presets, does exactly ONE row show a filled/solid radio dot while the other rows show empty circles?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In this list of Keen difficulty presets, does exactly ONE row show a filled/solid radio dot while the other rows show empty circles?", + "tag": "shape" + }, + { + "test": "states_switch_arrow_keys", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "'Show arrow keys' switch checked false -> true after one tap" + }, + { + "test": "states_switch_arrow_on_vlm", + "passed": true, + "message": "VLM: Q='For the 'Show arrow keys' row, is its toggle switch in the ON position, with the round thumb slid to the RIGHT end of the track?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: For the 'Show arrow keys' row, is its toggle switch in the ON position, with the round thumb slid to the RIGHT end of the track?", + "tag": "position" + }, + { + "test": "states_switch_highlight", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "'Highlight loops' switch checked true -> false after one tap" + }, + { + "test": "states_switch_highlight_off_vlm", + "passed": true, + "message": "VLM: Q='For the 'Highlight loops involving unlocked squares' row, is its toggle switch in the OFF position, with the round thumb at the LEFT end of a grey track?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: For the 'Highlight loops involving unlocked squares' row, is its toggle switch in the OFF position, with the round thumb at the LEFT end of a grey track?", + "tag": "position" + } + ] +} \ No newline at end of file diff --git a/android/chrisboyle-sgtpuzzles/tests/android_structure_eval.json b/android/chrisboyle-sgtpuzzles/tests/android_structure_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..ef4a31e0ee78c8fc0dae653e797a33e654b9ebe3 --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/tests/android_structure_eval.json @@ -0,0 +1,193 @@ +{ + "module": "structure", + "total": 17, + "passed": 17, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 9, + "passed": 9, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 8, + "passed": 8, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.8889, + "audit": { + "kit_api_version": 1, + "existence": 4, + "liveness": 0, + "interactive": 13, + "depth_ge1": 13, + "depth_ge2": 2, + "value": 0, + "vlm_fine": 7 + }, + "results": [ + { + "test": "structure_gate_launch", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_gate_launch_vlm", + "passed": true, + "message": "VLM: Q='Is this a vertical list of entries where each row shows a small square icon/thumbnail on the LEFT and a block of descriptive text to its RIGHT?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is this a vertical list of entries where each row shows a small square icon/thumbnail on the LEFT and a block of descriptive text to its RIGHT?", + "tag": "position" + }, + { + "test": "structure_chooser_sections", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_chooser_sections_vlm", + "passed": true, + "message": "VLM: Q='Are there two section headings, one reading 'Starred' and one reading 'Others', with the 'Starred' heading positioned ABOVE the 'Others' heading?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Are there two section headings, one reading 'Starred' and one reading 'Others', with the 'Starred' heading positioned ABOVE the 'Others' heading?", + "tag": "position" + }, + { + "test": "structure_gameplay_surface", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "chooser table -> GamePlay adds game_view+status_bar+buttons; BACK restores the chooser table" + }, + { + "test": "structure_gameplay_surface_vlm", + "passed": true, + "message": "VLM: Q='Is there a single square puzzle grid outlined by a RED border, occupying the center of the screen?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is there a single square puzzle grid outlined by a RED border, occupying the center of the screen?", + "tag": "shape" + }, + { + "test": "structure_gameplay_toolbar", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "GamePlay adds a toolbar with Navigate up + 3 action buttons (Game/Type/Help)" + }, + { + "test": "structure_type_menu_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "RadioButton count 0->9->0 on Type menu open/close; items include 5x5" + }, + { + "test": "structure_type_menu_shape_vlm", + "passed": true, + "message": "VLM: Q='Is a vertical list of radio-button options shown where exactly ONE circle is filled/selected and the rest are empty circles?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is a vertical list of radio-button options shown where exactly ONE circle is filled/selected and the rest are empty circles?", + "tag": "shape" + }, + { + "test": "structure_game_menu_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Game menu adds 7 item TextViews (New game/Restart/Show solution/Load/Save/Share/Settings); text count restores on close" + }, + { + "test": "structure_game_menu_shape_vlm", + "passed": true, + "message": "VLM: Q='Is a popup menu shown as a vertical list of items where each item has a small icon positioned to the LEFT of its text label?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is a popup menu shown as a vertical list of items where each item has a small icon positioned to the LEFT of its text label?", + "tag": "position" + }, + { + "test": "structure_keen_digit_buttons", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "digit-keypad keys (content-desc 1..6): 0 on Net -> 6 on Keen -> 0 back on Net" + }, + { + "test": "structure_keen_digit_buttons_vlm", + "passed": true, + "message": "VLM: Q='Along the bottom of the screen, is there a horizontal row of number buttons showing the digits 1, 2, 3, 4, 5 and 6?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Along the bottom of the screen, is there a horizontal row of number buttons showing the digits 1, 2, 3, 4, 5 and 6?", + "tag": "layout" + }, + { + "test": "structure_custom_dialog_shape", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "Custom dialog (' configuration') adds 1 EditText + 1 CheckBox (0->1->0), dismissed restores 0" + }, + { + "test": "structure_custom_dialog_shape_vlm", + "passed": true, + "message": "VLM: Q='Is a configuration dialog box shown that contains a single-line text input field with a short number in it, next to a label?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is a configuration dialog box shown that contains a single-line text input field with a short number in it, next to a label?", + "tag": "shape" + }, + { + "test": "structure_settings_surface", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "chooser -> Settings adds recycler_view with >=2 Switch rows; BACK restores the chooser table" + }, + { + "test": "structure_settings_surface_vlm", + "passed": true, + "message": "VLM: Q='Is this a settings screen where at least two rows have an ON/OFF toggle switch positioned at the RIGHT edge of the row?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is this a settings screen where at least two rows have an ON/OFF toggle switch positioned at the RIGHT edge of the row?", + "tag": "position" + } + ] +} \ No newline at end of file diff --git a/android/chrisboyle-sgtpuzzles/tests/android_testgen_kit.py b/android/chrisboyle-sgtpuzzles/tests/android_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6 --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/tests/android_testgen_kit.py @@ -0,0 +1,1910 @@ +#!/usr/bin/env python3 +"""Android TestGen Kit — the single source of every test helper, so a test's +NAVIGATION 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 package +name differs): always use the module-level PACKAGE (argv[1]). Never write a package +name, an .apk path, a /data/data path, or a pixel coordinate as a literal. + python3 android_testgen_kit.py lint_sources # flags all of those + +SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery): + python3 android_testgen_kit.py audit + python3 android_testgen_kit.py lint + python3 android_testgen_kit.py lint_sources + python3 android_testgen_kit.py audit_depth [results_dir] +""" +from __future__ import annotations + +import ast +import base64 +import functools +import glob +import hashlib +import json +import math +import os +import re +import shlex +import subprocess +import sys +import time +import urllib.error +import 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.0 +SETTLE = { + "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 /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 " list[dict]: + """XML -> list of attribute dicts, each with _bounds and _center.""" + nodes = [] + for m in re.finditer(r"]+?)/?>", 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} \n" + " android_testgen_kit.py audit_depth [results_dir]\n" + " android_testgen_kit.py score [manifest_dir]") diff --git a/android/chrisboyle-sgtpuzzles/tests/android_text_eval.json b/android/chrisboyle-sgtpuzzles/tests/android_text_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..4c1c2dcf64dccccc67c09287f67d5498e080c4a8 --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/tests/android_text_eval.json @@ -0,0 +1,205 @@ +{ + "module": "text", + "total": 19, + "passed": 19, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 17, + "passed": 17, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 2, + "passed": 2, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.1176, + "audit": { + "kit_api_version": 1, + "existence": 18, + "liveness": 0, + "interactive": 1, + "depth_ge1": 1, + "depth_ge2": 1, + "value": 0, + "vlm_fine": 0 + }, + "results": [ + { + "test": "text_chooser_starred_header", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "games_starred header == 'Starred (long press to toggle)'" + }, + { + "test": "text_chooser_others_header", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "games_others header == 'Others'" + }, + { + "test": "text_chooser_toolbar_title", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "chooser toolbar title == 'Puzzles'" + }, + { + "test": "text_gameplay_title_net", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "toolbar title 'Net' after tapping the Net row (was 'Puzzles')" + }, + { + "test": "text_gameplay_title_keen", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "toolbar title 'Keen' after tapping the Keen row (was 'Puzzles')" + }, + { + "test": "text_status_active_denominator_5x5", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "status_bar matches '^Active: N/25$' (Net 5x5)" + }, + { + "test": "text_status_autosolved", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "status_bar becomes 'Auto-solved.' after Show solution (was an 'Active: N/T' form)" + }, + { + "test": "text_game_menu_labels", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "Game menu shows exactly 'New game','Restart','Show solution','Settings'" + }, + { + "test": "text_game_menu_share_label", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "Game menu contains an item reading 'Share…'" + }, + { + "test": "text_type_menu_net_presets", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "Net Type menu lists '5x5','7x7','9x9','11x11','5x5 wrapping','Custom…'" + }, + { + "test": "text_type_menu_keen_presets", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "Keen Type menu lists '4x4 Easy','6x6 Easy','6x6 Normal','9x9 Normal','Custom…'" + }, + { + "test": "text_custom_dialog_title_net", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "none", + "tier": 0, + "expect": "Custom dialog alertTitle == 'Net configuration'" + }, + { + "test": "text_custom_dialog_title_keen", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "none", + "tier": 0, + "expect": "Custom dialog alertTitle == 'Keen configuration'" + }, + { + "test": "text_gameid_dialog_title_net", + "passed": true, + "message": "", + "depth": 4, + "jump_kind": "none", + "tier": 0, + "expect": "GAME ID dialog alertTitle == 'Net game selection'" + }, + { + "test": "text_settings_reminders_summary", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "'Show reminders of controls' summary == 'E.g. explain long-press when starting a game'" + }, + { + "test": "text_settings_night_mode_summary", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "'Night mode' summary == 'Follow system dark theme'" + }, + { + "test": "text_settings_display_input_summary", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "'Display and input' summary == 'Less frequently changed settings'" + }, + { + "test": "text_help_webview_vlm", + "passed": true, + "message": "VLM: Q='This is a Help page rendered in a WebView. Near the TOP of the page, is there a row of blue underlined navigation links that includes the words 'Contents', 'Index' and 'Next', above a large heading that contains the puzzle name 'Net'?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: This is a Help page rendered in a WebView. Near the TOP of the page, is there a row of blue underlined navigation links that includes the words 'Contents', 'Index' and 'Next', above a large heading that contains the puzzle name 'Net'?", + "tag": "content" + }, + { + "test": "text_keen_canvas_clues_vlm", + "passed": true, + "message": "VLM: Q='Inside the square Keen puzzle grid, are there small arithmetic clue labels printed in the top-left corners of some cells — each a number immediately followed by an operator such as '+', '×' (multiply), '÷' (divide) or '−' (minus), for example '30×', '2÷' or '6+'?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Inside the square Keen puzzle grid, are there small arithmetic clue labels printed in the top-left corners of some cells — each a number immediately followed by an operator such as '+', '×' (multiply), '÷' (divide) or '−' (minus), for example '30×', '2÷' or '6+'?", + "tag": "content" + } + ] +} \ No newline at end of file diff --git a/android/chrisboyle-sgtpuzzles/tests/conftest.py b/android/chrisboyle-sgtpuzzles/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27 --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/tests/conftest.py @@ -0,0 +1 @@ +pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"] diff --git a/android/chrisboyle-sgtpuzzles/tests/requirements.txt b/android/chrisboyle-sgtpuzzles/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/tests/requirements.txt @@ -0,0 +1,2 @@ +pytest +pillow diff --git a/android/chrisboyle-sgtpuzzles/tests/test_android_computation.py b/android/chrisboyle-sgtpuzzles/tests/test_android_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..3531c4582695a07484e2eed0675e913ae6819dbd --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/tests/test_android_computation.py @@ -0,0 +1,724 @@ +#!/usr/bin/env python3 +"""Computation lane — Simon Tatham's Puzzles (name.boyle.chris.sgtpuzzles). + +CORE-FUNCTION lane: input -> OUTPUT. Sole owner of jump_kind="value". Every test +drives an INPUT (select a size preset, Show solution, load a game id, New game, +enter a digit) and asserts the specific computed OUTPUT the running original +produced. The puzzle engine's derived state surfaces two ways: + (a) the GamePlay status_bar TextView (id=status_bar), which is RULE-READABLE, and + (b) the count of on-screen digit buttons (Keen), also RULE-READABLE, and + (c) the CANVAS grid render (game_view), which is VLM territory. + +Ground truth — EVERY value below was observed live on the running original during +recon + dedicated probes before this file was written: + - Net status_bar = "Active: N/T" where T = gridW*gridH (total tiles). Selecting a + size preset via the Type menu RECOMPUTES T and reloads: + 5x5 -> "Active: N/25" 7x7 -> "Active: N/49" + 9x9 -> "Active: N/81" 11x11 -> "Active: N/121" + 5x5 wrapping -> "Active: N/25" + (VERIFIED denominators 25 / 49 / 81 / 121 / 25 on device.) N (the connected + count) varies per generated puzzle; only the DENOMINATOR T is a function of the + chosen preset, so tests assert T and treat N as free. + - Net Game menu -> "Show solution" sets status_bar to "Auto-solved. " (with a + trailing space — VERIFIED). Robust check: status.strip() == "Auto-solved.". + - Net Restart after Show solution reverts status to an "Active: N/T" form. + - Net Game menu -> "New game" regenerates; the denominator T stays consistent + with the current preset (25 at 5x5), N changes. (VERIFIED "Active: 4/25" -> + "Active: 5/25".) + - GAME ID determinism: the Custom… -> GAME ID… dialog EditText holds the full + deterministic id; loading it and re-reading it yields the SAME id, and the + engine computes the SAME status from it. (VERIFIED the EditText id is byte-for- + byte identical across two opens: "5x5w:6b2875a9bc4456937b281a762".) + - Keen has NO status_bar. Its computed input->output surface: selecting an NxN + preset yields exactly N digit-entry buttons (content-desc "1".."N). + VERIFIED: 4x4 Easy -> digit buttons {1,2,3,4}; 6x6 Easy -> {1,2,3,4,5,6}. + - Canvas renders (VERIFIED on screenshots): unsolved Net endpoint tiles are dark + BLUE with black wires; after Show solution they are bright CYAN, all connected + by cyan wires. Net 9x9 draws visibly more cells than 5x5. Keen renders + arithmetic clues ("7+","2÷","30×",…) in cages and an entered digit as a large + GREEN number in the selected cell. + +Depth: every value that lives inside GamePlay (behind a puzzle-row tap) declares +depth>=1, backed by and_enter_game(); values behind the Type menu / a dialog +declare depth 2 (backed by and_enter_type_menu / and_reach_gameid_dialog). An +unbacked depth would be reported as fake depth. +""" + +import os +import re +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ══════════════════════════════════════════════════════════════════════════════ +# Local helpers — depth-family NAMES (and_enter_*/and_reach_*) back every declared +# depth>=1. All package-agnostic: id LAST-segment, content-desc, text; coordinates +# only ever come from node bounds via the kit, never a literal. +# ══════════════════════════════════════════════════════════════════════════════ + +def _reach_chooser(): + """Land on GameChooser. The app is singleTask and RESUMES the last game on a + fresh launch, so pop GamePlay with BACK when we land there (recon-verified).""" + restart_app() + wait_for_foreground(10) + if "GamePlay" in get_current_activity(): + back() + wait_for_foreground(5) + return ui() + + +def _find_row(nodes, name): + """The chooser row TextView whose text is ': '.""" + for n in nodes: + if (n.get("resource-id", "").endswith("/text") + and n.get("text", "").startswith(name + ":")): + return n + return None + + +def _scroll_to_row(name, max_swipes=10): + """Scroll the chooser until puzzle 's row is on screen; return it.""" + row = _find_row(ui(), name) + for _ in range(max_swipes): + if row: + return row + scroll_down(0.5) + row = _find_row(ui(), name) + return row + + +def and_enter_game(name): + """Chooser -> tap puzzle row -> GamePlay. Counts one surface so a + depth>=1 assertion made inside GamePlay is backed by a real navigation call. + Returns the GamePlay node tree, or [] if the row was never reachable.""" + _reach_chooser() + row = _scroll_to_row(name) + if not row or not safe_tap(row): + return [] + wait_for_foreground(5) + and_enter(name) + return ui() + + +def and_enter_type_menu(gp): + """Open the GamePlay Type-menu popup (the size/difficulty presets). Counts one + surface (a popup layer). Returns True on success.""" + trig = find_node(gp, content_desc="Type") + if not trig or not tap_node(trig): + return False + and_enter("type_menu") + return True + + +def and_enter_game_menu(gp): + """Open the GamePlay Game-menu popup. Counts one surface (a popup layer).""" + trig = find_node(gp, content_desc="Game") + if not trig or not tap_node(trig): + return False + and_enter("game_menu") + return True + + +def _radio_title(nodes, label): + """A type-menu preset row (id=title) whose text equals `label`.""" + for n in nodes: + if (n.get("resource-id", "").endswith("/title") + and n.get("text", "") == label): + return n + return None + + +def _menu_item(nodes, label): + """A popup/menu item TextView whose visible text equals `label`.""" + for n in nodes: + if "TextView" in n.get("class", "") and n.get("text", "") == label: + return n + return None + + +def _status_text(): + """The GamePlay status_bar text ('' if the bar is absent). Read from a FRESH + dump — the status recomputes as the puzzle reloads.""" + n = node_by_id(ui(), "status_bar") + return n.get("text", "") if n else "" + + +def _status_denominator(txt): + """Parse T from an 'Active: N/T' status string; None if it doesn't match.""" + m = re.search(r"Active:\s*\d+\s*/\s*(\d+)", txt or "") + return int(m.group(1)) if m else None + + +def and_enter_net_preset(preset): + """Open Net -> Type menu -> select the `preset` radio -> wait for the reload. + Two forward surfaces (game + type menu). Returns the recomputed status_bar + string, or "" if the preset row was never reachable. This is the INPUT path + for the denominator value tests.""" + gp = and_enter_game("Net") + if not gp or not and_enter_type_menu(gp): + return "" + r = _radio_title(ui(), preset) + if not r or not tap_node(r): + return "" + wait_for_foreground(5) + settle("tap") # let the puzzle regenerate + status recompute + return _status_text() + + +def and_reach_gameid_dialog(name="Net"): + """Net -> Type menu -> Custom… -> GAME ID… dialog. Three forward surfaces. + Returns (ok, dialog_nodes). The dialog's EditText holds the deterministic id — + the substrate for the determinism value test.""" + gp = and_enter_game(name) + if not gp or not and_enter_type_menu(gp): + return False, [] + cust = _radio_title(ui(), "Custom…") + if not cust or not tap_node(cust): + return False, [] + settle("tap") + and_enter("custom_dialog") + gid_btn = node_by_id(ui(), "button2") # "GAME ID…" + if not gid_btn or not tap_node(gid_btn): + return False, [] + settle("tap") + and_enter("gameid_dialog") + return True, ui() + + +def _gameid_edittext_text(nodes): + """The (single) EditText's text in the GAME ID dialog, or ''.""" + for e in find_by_class(nodes, "EditText"): + if e.get("text"): + return e.get("text", "") + return "" + + +def _keen_digit_buttons(): + """The set of digit-entry button labels currently on screen (Keen). A digit + button is a node whose content-desc is a single digit string.""" + out = set() + for n in ui(): + cd = n.get("content-desc", "") + if cd.isdigit() and len(cd) <= 2: + out.add(cd) + return out + + +def _keen_cell_center(gv, col, row, n=6): + """Center pixel of Keen grid cell (col,row) for an n x n grid, derived from the + game_view bounds — never a hardcoded coordinate. The grid is a centered square + ~0.85 of the smaller game_view dimension.""" + x1, y1, x2, y2 = gv["_bounds"] + gw, gh = x2 - x1, y2 - y1 + grid = int(min(gw, gh) * 0.85) + gx1 = x1 + (gw - grid) // 2 + gy1 = y1 + (gh - grid) // 2 + cell = grid // n + return (gx1 + col * cell + cell // 2, gy1 + row * cell + cell // 2) + + +def and_enter_keen_preset(preset): + """Open Keen -> Type menu -> select `preset` -> wait for reload. Returns the + GamePlay node tree after reload, or [] on failure.""" + gp = and_enter_game("Keen") + if not gp or not and_enter_type_menu(gp): + return [] + r = _radio_title(ui(), preset) + if not r or not tap_node(r): + return [] + wait_for_foreground(5) + settle("tap") + return ui() + + +# ══════════════════════════════════════════════════════════════════════════════ +# (1) Net preset -> denominator T (the value backbone: input=preset, output=T) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_net_denominator_5x5", "computation_net_grid_5x5_vlm")) +def test_net_denominator_5x5(): + """INPUT: select the 5x5 preset in the Type menu. OUTPUT: status_bar denominator + T == 25 (= 5*5). Absent-before/present-after is inherent: a non-5x5 board shows + a different T; only the 5x5 board computes /25.""" + status = and_enter_net_preset("5x5") + t = _status_denominator(status) + ok = (t == 25) + record("computation_net_denominator_5x5", ok, + "" if ok else f"behavior_wrong: 5x5 preset gave status {status!r} " + f"(denominator {t}, expected 25)", + depth=2, jump_kind="value", expect="status denominator 25 (Active: N/25)") + # VLM (size): the fresh 5x5 board renders a 5-by-5 grid of cells. + vlm_assert("computation_net_grid_5x5", + "Is the puzzle board a square grid of exactly 5 columns by 5 rows " + "(25 cells), outlined by a red border?", + RESULTS_DIR, tag="size", depth=2, jump_kind="value") + + +@and_test(expects=("computation_net_denominator_7x7", "computation_net_grid_7x7_vlm")) +def test_net_denominator_7x7(): + """INPUT: select 7x7. OUTPUT: denominator T == 49 (= 7*7).""" + status = and_enter_net_preset("7x7") + t = _status_denominator(status) + ok = (t == 49) + record("computation_net_denominator_7x7", ok, + "" if ok else f"behavior_wrong: 7x7 preset gave status {status!r} " + f"(denominator {t}, expected 49)", + depth=2, jump_kind="value", expect="status denominator 49 (Active: N/49)") + # VLM (size): the 7x7 board renders a grid VISIBLY FINER than a 5x5 (more than 5 + # columns and rows). Exact column-counting at 7 is unreliable for a VLM, but the + # "finer than 5x5" comparative is robust and discriminating: it returns NO on the + # 5x5 board and YES on the 7x7/9x9 boards (verified against the captured shots). + # Paired with the actual 7x7 preset change above. + vlm_assert("computation_net_grid_7x7", + "Is the puzzle board a square grid that is clearly finer than a 5x5 " + "grid, having noticeably MORE than 5 columns and more than 5 rows of " + "small cells?", + RESULTS_DIR, tag="size", depth=2, jump_kind="value") + + +@and_test(expects=("computation_net_denominator_9x9", "computation_net_grid_9x9_vlm")) +def test_net_denominator_9x9(): + """INPUT: select 9x9. OUTPUT: denominator T == 81 (= 9*9).""" + status = and_enter_net_preset("9x9") + t = _status_denominator(status) + ok = (t == 81) + record("computation_net_denominator_9x9", ok, + "" if ok else f"behavior_wrong: 9x9 preset gave status {status!r} " + f"(denominator {t}, expected 81)", + depth=2, jump_kind="value", expect="status denominator 81 (Active: N/81)") + # VLM (size): the 9x9 board renders MANY more cells than the 5x5 — a visibly + # denser 9-by-9 grid. Paired with the actual 9x9 preset change above. + vlm_assert("computation_net_grid_9x9", + "Is the puzzle board a large dense square grid of about 9 columns by " + "9 rows (roughly 80 small cells), clearly finer than a simple 5x5 " + "grid?", + RESULTS_DIR, tag="size", depth=2, jump_kind="value") + + +@and_test(expects=("computation_net_denominator_11x11",)) +def test_net_denominator_11x11(): + """INPUT: select 11x11. OUTPUT: denominator T == 121 (= 11*11).""" + status = and_enter_net_preset("11x11") + t = _status_denominator(status) + ok = (t == 121) + record("computation_net_denominator_11x11", ok, + "" if ok else f"behavior_wrong: 11x11 preset gave status {status!r} " + f"(denominator {t}, expected 121)", + depth=2, jump_kind="value", + expect="status denominator 121 (Active: N/121)") + + +@and_test(expects=("computation_net_denominator_5x5_wrapping",)) +def test_net_denominator_5x5_wrapping(): + """INPUT: select the '5x5 wrapping' preset (same grid size, torus topology). + OUTPUT: denominator T == 25 — the total-tile count depends only on gridW*gridH, + not on wrapping. VERIFIED /25 on device. This discriminates a recreation that + mis-derives T from the wrapping flag.""" + status = and_enter_net_preset("5x5 wrapping") + t = _status_denominator(status) + ok = (t == 25) + record("computation_net_denominator_5x5_wrapping", ok, + "" if ok else f"behavior_wrong: '5x5 wrapping' gave status {status!r} " + f"(denominator {t}, expected 25)", + depth=2, jump_kind="value", + expect="status denominator 25 (Active: N/25) for 5x5 wrapping") + + +@and_test(expects=("computation_net_denominator_distinct",)) +def test_net_denominator_distinct(): + """Cross-preset consistency: 5x5 and 7x7 compute DIFFERENT denominators + (25 != 49), each equal to gridW*gridH. A recreation that ignores the preset and + always shows one fixed denominator fails this even if a single-preset test + happens to pass. Two independent INPUT paths, each read back.""" + s5 = and_enter_net_preset("5x5") + t5 = _status_denominator(s5) + s7 = and_enter_net_preset("7x7") + t7 = _status_denominator(s7) + ok = (t5 == 25 and t7 == 49 and t5 != t7) + record("computation_net_denominator_distinct", ok, + "" if ok else f"behavior_wrong: denominators did not track the preset " + f"(5x5->{t5} expected 25, 7x7->{t7} expected 49)", + depth=2, jump_kind="value", + expect="5x5 -> denominator 25 and 7x7 -> denominator 49 (distinct)") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (2) Show solution / Restart / New game — deterministic status outputs +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_show_solution_autosolved", + "computation_solved_render_vlm")) +def test_show_solution_autosolved(): + """INPUT: Game menu -> 'Show solution' on Net. OUTPUT: status_bar becomes + exactly 'Auto-solved.' (the original renders a trailing space, so compare on + .strip()). This is the app's deterministic completion output.""" + gp = and_enter_game("Net") + if not gp: + record("computation_show_solution_autosolved", False, + "setup_failed: could not open Net to run Show solution", + depth=1, jump_kind="value", expect="status 'Auto-solved.'") + elif not and_enter_game_menu(gp): + record("computation_show_solution_autosolved", False, + "setup_failed: could not open the Game menu", + depth=1, jump_kind="value", expect="status 'Auto-solved.'") + else: + ss = _menu_item(ui(), "Show solution") + if not ss or not safe_tap(ss): + record("computation_show_solution_autosolved", False, + "feature_missing: Game menu has no working 'Show solution'", + depth=1, jump_kind="value", expect="status 'Auto-solved.'") + else: + wait_for_foreground(5) + settle("tap") + status = _status_text() + ok = (status.strip() == "Auto-solved.") + record("computation_show_solution_autosolved", ok, + "" if ok else f"behavior_wrong: Show solution gave status " + f"{status!r}, expected 'Auto-solved.'", + depth=1, jump_kind="value", + expect="status_bar == 'Auto-solved.' after Show solution") + # VLM (color): a solved Net renders every endpoint tile bright CYAN, joined by + # cyan wires — the fully-connected look. Set up a fresh solved board for the + # shot (this test's own board is already solved above, but re-establish it to be + # robust to any recording ordering). + gp2 = and_enter_game("Net") + if gp2 and and_enter_game_menu(gp2): + ss2 = _menu_item(ui(), "Show solution") + if ss2: + safe_tap(ss2) + wait_for_foreground(5) + settle("tap") + vlm_assert("computation_solved_render", + "In the puzzle grid, are the small square endpoint tiles lit up " + "bright CYAN/turquoise and joined together by cyan lines (a solved, " + "fully-connected network), rather than dark blue and disconnected?", + RESULTS_DIR, tag="color", depth=1, jump_kind="value") + + +@and_test(expects=("computation_restart_after_solve", + "computation_unsolved_render_vlm")) +def test_restart_after_solve(): + """INPUT sequence: Show solution -> 'Auto-solved.', then Game menu -> Restart. + OUTPUT: status reverts to an 'Active: N/T' form (Restart returns the current + game to its start; it is a non-destructive game action). Two dependent computed + outputs read back from the status_bar.""" + gp = and_enter_game("Net") + if not gp or not and_enter_game_menu(gp): + record("computation_restart_after_solve", False, + "setup_failed: could not open Net / Game menu for the Restart flow", + depth=1, jump_kind="value", + expect="status: Auto-solved. -> Restart -> Active:N/T") + else: + ss = _menu_item(ui(), "Show solution") + if not ss or not safe_tap(ss): + record("computation_restart_after_solve", False, + "feature_missing: no working 'Show solution' to set up Restart", + depth=1, jump_kind="value", + expect="status: Auto-solved. -> Restart -> Active:N/T") + else: + wait_for_foreground(5) + settle("tap") + s_solved = _status_text() + gp2 = ui() + restarted = False + if and_enter_game_menu(gp2): + rs = _menu_item(ui(), "Restart") + restarted = bool(rs and safe_tap(rs)) + if restarted: + wait_for_foreground(5) + settle("tap") + s_after = _status_text() + ok = (s_solved.strip() == "Auto-solved." + and restarted + and _status_denominator(s_after) is not None + and s_after.strip() != "Auto-solved.") + record("computation_restart_after_solve", ok, + "" if ok else f"behavior_wrong: Restart did not revert " + f"'Auto-solved.' to an 'Active: N/T' form (solved={s_solved!r} " + f"afterRestart={s_after!r})", + depth=1, jump_kind="value", + expect="status_bar: 'Auto-solved.' -> Restart -> matches " + "'Active: N/T'") + # VLM (color): a freshly-restarted / fresh Net renders most endpoint tiles dark + # BLUE and disconnected — the opposite colour state from the solved grid. + gp3 = and_enter_game("Net") + if gp3 and and_enter_game_menu(gp3): + ng = _menu_item(ui(), "New game") + if ng: + safe_tap(ng) + wait_for_foreground(5) + settle("tap") + vlm_assert("computation_unsolved_render", + "In the puzzle grid, are most of the small square endpoint tiles a " + "dark BLUE colour (unlit / not connected), rather than all lit " + "bright cyan?", + RESULTS_DIR, tag="color", depth=1, jump_kind="value") + + +@and_test(expects=("computation_new_game_denominator", + "computation_new_game_layout_vlm")) +def test_new_game_denominator(): + """INPUT: Game menu -> 'New game' on a 5x5 Net. OUTPUT: the status_bar + denominator T stays 25 (the total-tile count is fixed by the preset), even + though the connected count N is regenerated. Asserts the computed T is + preset-consistent after regeneration.""" + # ensure the 5x5 preset first (independent of any earlier test's leftover) + s_pre = and_enter_net_preset("5x5") + t_pre = _status_denominator(s_pre) + gp = and_enter_game("Net") # reopen so 5x5 is the active preset + if not gp or not and_enter_game_menu(gp): + record("computation_new_game_denominator", False, + "setup_failed: could not open Net / Game menu for New game", + depth=1, jump_kind="value", + expect="denominator 25 after New game at 5x5") + else: + ng = _menu_item(ui(), "New game") + if not ng or not safe_tap(ng): + record("computation_new_game_denominator", False, + "feature_missing: Game menu has no working 'New game'", + depth=1, jump_kind="value", + expect="denominator 25 after New game at 5x5") + else: + wait_for_foreground(5) + settle("tap") + s_new = _status_text() + t_new = _status_denominator(s_new) + ok = (t_pre == 25 and t_new == 25) + record("computation_new_game_denominator", ok, + "" if ok else f"behavior_wrong: denominator not preset-consistent " + f"after New game (before={s_pre!r} T={t_pre}; after={s_new!r} " + f"T={t_new}; expected 25 both)", + depth=1, jump_kind="value", + expect="status denominator == 25 after New game at 5x5") + # VLM (content): after New game a DIFFERENT puzzle layout is drawn — a 5x5 grid + # with wire segments in various positions (an in-progress network), not a blank + # board. + vlm_assert("computation_new_game_layout", + "Does the 5x5 grid show blue endpoint tiles and short black " + "wire/line segments arranged across the cells (a freshly generated " + "network puzzle), rather than an empty featureless grid?", + RESULTS_DIR, tag="content", depth=1, jump_kind="value") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (3) GAME ID deterministic load (input=id, output=identical computed state) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_gameid_deterministic",)) +def test_gameid_deterministic(): + """Determinism of the engine: read the current game id ID0 from the GAME ID… + EditText, OK to load it, read the status V0; then reopen GAME ID… and confirm + the EditText still holds the SAME id (byte-for-byte), OK again, read V1. + OUTPUT: ID stable across opens AND V1 == V0 — same id => same computed state. + A recreation whose loading is non-deterministic (or that regenerates a fresh id) + fails this.""" + ok_dlg, gid = and_reach_gameid_dialog("Net") + if not ok_dlg: + record("computation_gameid_deterministic", False, + "setup_failed: could not reach the GAME ID… dialog", + depth=2, jump_kind="value", + expect="same game id both opens => same status") + return + id0 = _gameid_edittext_text(gid) + if not id0: + record("computation_gameid_deterministic", False, + "feature_missing: GAME ID… dialog EditText held no game id", + depth=2, jump_kind="value", + expect="same game id both opens => same status") + return + ok_btn = node_by_id(gid, "button1") # OK + if not ok_btn or not tap_node(ok_btn): + record("computation_gameid_deterministic", False, + "setup_failed: GAME ID… dialog has no working OK button", + depth=2, jump_kind="value", + expect="same game id both opens => same status") + return + wait_for_foreground(5) + settle("tap") + v0 = _status_text() + # reopen the GAME ID… dialog and re-read the id, then OK again + ok_dlg2, gid2 = and_reach_gameid_dialog("Net") + id1 = _gameid_edittext_text(gid2) if ok_dlg2 else "" + v1 = "" + if ok_dlg2: + ok_btn2 = node_by_id(gid2, "button1") + if ok_btn2 and tap_node(ok_btn2): + wait_for_foreground(5) + settle("tap") + v1 = _status_text() + id_stable = bool(id0) and (id1 == id0) + status_stable = bool(v0) and (v1 == v0) + ok = id_stable and status_stable + record("computation_gameid_deterministic", ok, + "" if ok else f"behavior_wrong: game id / computed state not " + f"deterministic (ID0={id0!r} ID1={id1!r}; V0={v0!r} V1={v1!r})", + depth=2, jump_kind="value", + expect=f"same id both opens ({id0}) and identical status both loads ({v0})") + + +@and_test(expects=("computation_gameid_encodes_size",)) +def test_gameid_encodes_size(): + """The game id deterministically ENCODES the grid size: after selecting the 7x7 + preset, the Net game id begins with '7x7' (the size prefix the engine writes + before the ':'), which recomputes to a /49 denominator. INPUT: pick 7x7 then + open GAME ID…; OUTPUT: the id's size prefix == '7x7'. Ties the id string to the + computed board size — a clean input->output on the serialized state.""" + # select 7x7 first + s7 = and_enter_net_preset("7x7") + t7 = _status_denominator(s7) + ok_dlg, gid = and_reach_gameid_dialog("Net") + if not ok_dlg: + record("computation_gameid_encodes_size", False, + "setup_failed: could not reach GAME ID… after selecting 7x7", + depth=2, jump_kind="value", + expect="game id begins '7x7' for the 7x7 board") + return + gid_str = _gameid_edittext_text(gid) + # the id is ":"; the size prefix is before the first ':' + prefix = gid_str.split(":", 1)[0] if ":" in gid_str else gid_str + ok = (t7 == 49 and prefix == "7x7") + record("computation_gameid_encodes_size", ok, + "" if ok else f"behavior_wrong: 7x7 board did not yield a '7x7'-prefixed " + f"game id (denominator {t7}, id={gid_str!r}, prefix={prefix!r})", + depth=2, jump_kind="value", + expect="game id size-prefix == '7x7' (and denominator 49) for the 7x7 " + "board") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (4) Keen preset -> digit-button count (input=NxN preset, output=N buttons) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_keen_digits_4x4", "computation_keen_grid_4x4_vlm")) +def test_keen_digits_4x4(): + """INPUT: select Keen '4x4 Easy'. OUTPUT: the digit-entry pad holds exactly the + digits {1,2,3,4} — the alphabet is 1..N for an NxN Keen board (VERIFIED). Keen + has no status_bar, so the digit-button set IS its rule-readable computed + surface. A recreation that always shows 1..6 fails on the 4x4 board.""" + gp = and_enter_keen_preset("4x4 Easy") + if not gp: + record("computation_keen_digits_4x4", False, + "setup_failed: could not select the Keen 4x4 Easy preset", + depth=2, jump_kind="value", expect="digit buttons == {1,2,3,4}") + else: + digits = _keen_digit_buttons() + ok = (digits == {"1", "2", "3", "4"}) + record("computation_keen_digits_4x4", ok, + "" if ok else f"behavior_wrong: 4x4 Easy Keen showed digit buttons " + f"{sorted(digits)}, expected exactly 1..4", + depth=2, jump_kind="value", + expect="Keen 4x4 digit buttons exactly {1,2,3,4}") + # VLM (size): the 4x4 board renders a 4-by-4 grid — fewer, larger cells than a + # 6x6 board. Paired with the actual 4x4 preset change. + vlm_assert("computation_keen_grid_4x4", + "Is the Keen board a square grid of exactly 4 columns by 4 rows " + "(16 cells), with small arithmetic clues like '7+' or '2÷' printed " + "in the top-left of some cages?", + RESULTS_DIR, tag="size", depth=2, jump_kind="value") + + +@and_test(expects=("computation_keen_digits_6x6", "computation_keen_grid_6x6_vlm")) +def test_keen_digits_6x6(): + """INPUT: select Keen '6x6 Easy'. OUTPUT: the digit-entry pad holds exactly + {1,2,3,4,5,6}. Together with the 4x4 test this proves the digit alphabet is + computed from the chosen grid size N (4 vs 6), not fixed.""" + gp = and_enter_keen_preset("6x6 Easy") + if not gp: + record("computation_keen_digits_6x6", False, + "setup_failed: could not select the Keen 6x6 Easy preset", + depth=2, jump_kind="value", + expect="digit buttons == {1,2,3,4,5,6}") + else: + digits = _keen_digit_buttons() + ok = (digits == {"1", "2", "3", "4", "5", "6"}) + record("computation_keen_digits_6x6", ok, + "" if ok else f"behavior_wrong: 6x6 Easy Keen showed digit buttons " + f"{sorted(digits)}, expected exactly 1..6", + depth=2, jump_kind="value", + expect="Keen 6x6 digit buttons exactly {1,2,3,4,5,6}") + # VLM (size): the 6x6 board renders a 6-by-6 grid — a finer grid than the 4x4. + vlm_assert("computation_keen_grid_6x6", + "Is the Keen board a square grid of exactly 6 columns by 6 rows " + "(36 cells), clearly finer/denser than a 4x4 grid?", + RESULTS_DIR, tag="size", depth=2, jump_kind="value") + + +@and_test(expects=("computation_keen_digit_count_scales",)) +def test_keen_digit_count_scales(): + """Cross-preset scaling: the number of digit buttons EQUALS the grid dimension — + 4 buttons on 4x4, 6 buttons on 6x6, and 4 != 6. A single derived integer + (len of the digit alphabet) read off two INPUT paths; the strongest single- + number discriminator for Keen's engine.""" + gp4 = and_enter_keen_preset("4x4 Easy") + n4 = len(_keen_digit_buttons()) if gp4 else -1 + gp6 = and_enter_keen_preset("6x6 Easy") + n6 = len(_keen_digit_buttons()) if gp6 else -1 + ok = (n4 == 4 and n6 == 6 and n4 != n6) + record("computation_keen_digit_count_scales", ok, + "" if ok else f"behavior_wrong: digit-button count did not scale with " + f"grid size (4x4 -> {n4} buttons expected 4; 6x6 -> {n6} expected 6)", + depth=2, jump_kind="value", + expect="digit-button count 4 for 4x4 and 6 for 6x6 (scales with N)") + + +@and_test(expects=("computation_keen_digit_entry_vlm", + "computation_keen_clue_render_vlm")) +def test_keen_digit_entry_render(): + """VLM value on the CANVAS: on a 6x6 Keen board, tap an interior cell then the + '3' digit button; the engine writes '3' into that cell, rendered as a large + GREEN number (VERIFIED on screenshot). The digit render and the arithmetic-clue + render both live on the canvas (not the view tree), so they are genuine VLM + value checks. depth=2 (edit made after the preset selection surface).""" + gp = and_enter_keen_preset("6x6 Easy") + if gp: + gv = node_by_id(ui(), "game_view") + if gv: + cx, cy = _keen_cell_center(gv, 2, 3, n=6) + tap(cx, cy) + d3 = find_node(ui(), content_desc="3") + if d3: + tap_node(d3) + settle("tap") + # VLM #1 (content): the entered digit '3' is rendered inside a grid cell. + vlm_assert("computation_keen_digit_entry", + "Is the digit '3' displayed as a large coloured number inside one of " + "the grid cells (an entered value in a cell), not merely on the " + "number buttons along the bottom of the screen?", + RESULTS_DIR, tag="content", depth=2, jump_kind="value") + # VLM #2 (content): an arithmetic cage clue (a number followed by + - x or the + # division sign) is rendered in the corner of a cage — the computed target the + # cell entry must satisfy. + vlm_assert("computation_keen_clue_render", + "In the top-left corner of some cages, are there small arithmetic " + "clues made of a number and an operator (like '5+', '2÷', '30×' or " + "'3-')?", + RESULTS_DIR, tag="content", depth=2, jump_kind="value") + + +TESTS = [ + # (1) Net preset -> denominator T (value backbone) + test_net_denominator_5x5, + test_net_denominator_7x7, + test_net_denominator_9x9, + test_net_denominator_11x11, + test_net_denominator_5x5_wrapping, + test_net_denominator_distinct, + # (2) Show solution / Restart / New game -> status outputs + test_show_solution_autosolved, + test_restart_after_solve, + test_new_game_denominator, + # (3) GAME ID deterministic load + test_gameid_deterministic, + test_gameid_encodes_size, + # (4) Keen preset -> digit-button count + canvas digit render + test_keen_digits_4x4, + test_keen_digits_6x6, + test_keen_digit_count_scales, + test_keen_digit_entry_render, +] + + +if __name__ == "__main__": + run_suite(TESTS, "computation") diff --git a/android/chrisboyle-sgtpuzzles/tests/test_android_interaction.py b/android/chrisboyle-sgtpuzzles/tests/test_android_interaction.py new file mode 100644 index 0000000000000000000000000000000000000000..072664231e7f0a2bae1718f4ae56ac4708ad87e7 --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/tests/test_android_interaction.py @@ -0,0 +1,758 @@ +#!/usr/bin/env python3 +"""Interaction lane — Simon Tatham's Puzzles (name.boyle.chris.sgtpuzzles). + +This lane owns EFFECT-BY-CONSEQUENCE on user DATA. The persistent user DATA in +this app is (a) which puzzles are STARRED and (b) the in-progress game STATE +(moves / auto-solve / restart). There is no note/list CRUD; the "records" are +stars and game moves. This lane is the SOLE owner of long-press / context menus. + +What is exercised (ALL behaviors verified live on the running original): + - LONG-PRESS star toggle: long-pressing a chooser puzzle row MOVES it between + the "Others" and "Starred" sections. Section membership is the OBSERVATION + (a row's y vs. the "Others"/"Starred" header y). VERIFIED it PERSISTS across a + process kill. Every toggled star is toggled BACK so the suite leaves the + chooser in its default state and tests stay independent. + - Multi-record star integrity: star two different games, assert BOTH moved and + a control game stayed put; then restore both. + - DATA persistence across process death (this lane's marquee): + * star state survives force_stop_and_relaunch(). + * the resumed-puzzle identity (GamePlay title) survives the kill (singleTask + RESUMES the last game). The recon-verified fact is that the "Auto-solved." + status itself does NOT reproducibly persist on resume, but the resumed + puzzle TITLE does — so that is what is asserted. + - Multi-step (3+) game-state sequences, deterministic: + * Net: Show solution -> status "Auto-solved. " -> Undo -> status back to an + "Active: N/25" form (NOT auto-solved) -> Redo -> back to "Auto-solved. ". + VERIFIED exact strings on device (trailing space on "Auto-solved. "). + * Net: Show solution -> "Auto-solved. " -> Restart -> reverts to an + "Active: N/25" form. (Restart is a non-destructive game action — it + reverts the CURRENT game to its start, it deletes no records.) + - Canvas DATA edit (Keen): tap a grid cell -> tap a digit -> the digit renders + in the cell (green) -> Backspace -> the cell is empty again. The result lives + on the CANVAS (not the view tree), so it is asserted on the VLM track. + +Ground-truth sections/renders observed on the original: + - Default STARRED = {Guess, Keen, Net, Solo, Towers, Signpost, Light Up}; + default OTHERS includes {Black Box, Bridges, Cube, Dominosa}. + - Net status: "Active: N/25" (5x5); "Auto-solved. " after Show solution. + - Net endpoint tiles render bright CYAN when connected (solved), dark BLUE when + disconnected (unsolved); a red grid border is drawn in BOTH states. +""" + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ══════════════════════════════════════════════════════════════════════════════ +# Local helpers — the depth-family NAMES (and_enter_*/and_reach_*) back every +# declared depth>=1. Everything is package-agnostic (id LAST-segment, content-desc, +# text) and derives coordinates from node bounds, never a literal. +# ══════════════════════════════════════════════════════════════════════════════ + +def _reach_chooser(): + """Land on GameChooser. The app is singleTask and RESUMES the last game on a + fresh launch, so pop GamePlay with BACK when we land there (recon-verified).""" + restart_app() + wait_for_foreground(10) + if "GamePlay" in get_current_activity(): + back() + wait_for_foreground(5) + return ui() + + +def _reach_chooser_clean(): + """Like _reach_chooser but starts from a virgin database (default star set), + so a test that must know the exact default membership is not perturbed by an + earlier test that left a star toggled (belt-and-braces on top of each test's + own restore).""" + clear_data() + launch_app() + wait_for_foreground(10) + if "GamePlay" in get_current_activity(): + back() + wait_for_foreground(5) + return ui() + + +def section_of(nodes, name_prefix): + """FAST single-dump classifier of the GIVEN dump: 'starred' | 'others' | None + (row not present in this dump). + + Geometry: a row below the 'Others' header y is Others; a row below the + 'Starred' header y (and above Others) is Starred. Reliable ONLY when the row + AND a header both appear in `nodes`, which holds for games near the + Starred/Others boundary in the default top-of-list dump (Keen/Net at the top of + Starred; Black Box/Bridges/Cube/Dominosa at the top of Others). For a game that + may have scrolled off (e.g. one demoted to the bottom of the long Others list), + use membership(). name_prefix is the puzzle name WITHOUT ':'.""" + starred_y = others_y = game_y = None + for n in nodes: + t = n.get("text", "") or "" + b = n.get("_bounds") + if not b: + continue + if t.startswith("Starred"): + starred_y = b[1] + elif t == "Others": + others_y = b[1] + elif n.get("resource-id", "").endswith("/text") and t.startswith(name_prefix + ":"): + game_y = b[1] + if game_y is None: + return None + if others_y is not None and game_y > others_y: + return "others" + if starred_y is not None and game_y > starred_y: + return "starred" + return None + + +def membership(name, max_swipes=12): + """ROBUST classifier: 'starred' | 'others' | None, valid even when the row and + the section headers are on DIFFERENT screens (e.g. a game demoted to the bottom + of the long Others list). + + Scrolls to the top, then walks DOWN screen by screen, tracking the section of + the most-recently-seen header. On the screen where the row appears, it is + classified by the last header at-or-above it (falling back to the carried + section when no header shares the row's screen). Verified 100% correct on the + original for both toggle directions. Slower than section_of() (it scrolls the + whole list), so it is reserved for the demoted-game case.""" + for _ in range(8): + scroll_up(0.8) # go to the top of the list + last_section = None + for _ in range(max_swipes + 1): + marks = [] # (y, "starred"|"others"|"__row__") + for n in ui(): + t = n.get("text", "") or "" + b = n.get("_bounds") + if not b: + continue + if t.startswith("Starred"): + marks.append((b[1], "starred")) + elif t == "Others": + marks.append((b[1], "others")) + elif (n.get("resource-id", "").endswith("/text") + and t.startswith(name + ":")): + marks.append((b[1], "__row__")) + marks.sort() + cur = last_section + for _y, tag in marks: + if tag == "__row__": + return cur + cur = tag + if marks: + last_section = cur + scroll_down(0.5) + return None + + +def section_now(name): + """Section of right now: try the FAST top dump first (0 scrolls — works + for boundary games), and only fall back to the walk-down membership() when the + row is not classifiable in that dump (e.g. it was demoted far down Others).""" + _reach_top() + s = section_of(ui(), name) + if s is not None: + return s + return membership(name) + + +def _reach_top(): + """Scroll the chooser back to the top (cheap; a handful of up-swipes).""" + for _ in range(6): + scroll_up(0.8) + + +def _find_row(nodes, name): + """The chooser row TextView whose text is ': '.""" + for n in nodes: + if (n.get("resource-id", "").endswith("/text") + and n.get("text", "").startswith(name + ":")): + return n + return None + + +def _scroll_to_row(name, max_swipes=10): + """Scroll the chooser until puzzle 's row is on screen; return it.""" + row = _find_row(ui(), name) + for _ in range(max_swipes): + if row: + return row + scroll_down(0.5) + row = _find_row(ui(), name) + return row + + +def _toggle_star(name): + """Long-press puzzle 's row to toggle its star. Re-finds the row first + (the grid re-lays out after every toggle, so old coords are stale). Returns + True if the long-press was dispatched.""" + row = _scroll_to_row(name) + if not row: + return False + return long_press(row) + + +def _restore_to_others(name): + """If is currently starred, toggle it back to Others (cleanup).""" + if section_now(name) == "starred": + _toggle_star(name) + + +def _restore_to_starred(name): + """If is currently in Others, toggle it back to Starred (cleanup).""" + if section_now(name) == "others": + _toggle_star(name) + + +def _status_text(): + """The GamePlay status_bar text ('' if the bar is absent).""" + n = node_by_id(ui(), "status_bar") + return n.get("text", "") if n else "" + + +def _toolbar_title(nodes=None): + """The GamePlay toolbar title (the puzzle name), read generically: the + shortest-bounded TextView sitting inside the toolbar's bounds. Never keyed on a + hardcoded puzzle name.""" + nodes = ui() if nodes is None else nodes + tb = node_by_id(nodes, "toolbar") + if not tb or "_bounds" not in tb: + return "" + x1, y1, x2, y2 = tb["_bounds"] + best = None + for n in nodes: + if "TextView" not in n.get("class", ""): + continue + t = n.get("text", "") + b = n.get("_bounds") + if not t or not b: + continue + if b[1] >= y1 and b[3] <= y2 and b[0] >= x1 and b[2] <= x2: + if best is None or (b[2] - b[0]) < (best["_bounds"][2] - best["_bounds"][0]): + best = n + return best.get("text", "") if best else "" + + +def and_enter_game(name): + """Chooser -> tap puzzle row -> GamePlay. Counts one surface, so a + depth>=1 assertion made inside GamePlay is backed by a real navigation call. + Returns the GamePlay node tree, or [] if the row was never reachable.""" + _reach_chooser() + row = _scroll_to_row(name) + if not row or not safe_tap(row): + return [] + wait_for_foreground(5) + and_enter(name) + return ui() + + +def _menu_item(nodes, label): + """A popup/menu item TextView whose visible text equals `label`.""" + for n in nodes: + if "TextView" in n.get("class", "") and n.get("text", "") == label: + return n + return None + + +def and_reach_game_menu_item(gp, label): + """Open the GamePlay Game menu and tap the item `label` (e.g. 'Show solution', + 'New game', 'Restart'). Opening the popup is a surface; returns True on tap.""" + trig = find_node(gp, content_desc="Game") + if not trig or not tap_node(trig): + return False + and_enter("game_menu") + item = _menu_item(ui(), label) + if not item or not safe_tap(item): + return False + wait_for_foreground(5) + return True + + +def _keen_cell_center(gv, col, row): + """Center pixel of grid cell (col,row), derived from the game_view bounds. The + grid is a centered square ~0.85 of the smaller game_view dimension, 6x6 (Keen) + / 5x5 (Net) — a corner/interior cell is safe either way. Returns (x, y) — + never a hardcoded coordinate.""" + x1, y1, x2, y2 = gv["_bounds"] + gw, gh = x2 - x1, y2 - y1 + grid = int(min(gw, gh) * 0.85) + gx1 = x1 + (gw - grid) // 2 + gy1 = y1 + (gh - grid) // 2 + cell = grid // 6 + return (gx1 + col * cell + cell // 2, gy1 + row * cell + cell // 2) + + +# ══════════════════════════════════════════════════════════════════════════════ +# (1) LONG-PRESS star toggle — this lane's marquee, sole owner of long-press +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_star_toggle_to_starred", + "interaction_star_toggle_to_starred_vlm")) +def test_star_toggle_to_starred(): + """Long-press an Others puzzle ('Black Box') -> it MOVES to the Starred + section. Absent-before / present-after on section membership, both read from the + top-of-list dump (Black Box is a top Others row and lands as a Starred row, so + both states are visible without scrolling). Restored by a second long-press so + the chooser is left in its default state.""" + nodes = _reach_chooser() + before = section_of(nodes, "Black Box") + if before != "others": + record("interaction_star_toggle_to_starred", False, + f"setup_failed: 'Black Box' not in Others to begin with (was {before})", + depth=0, jump_kind="transition", + expect="Black Box moves Others->Starred on long-press") + elif not _toggle_star("Black Box"): + record("interaction_star_toggle_to_starred", False, + "feature_missing: could not long-press the 'Black Box' row", + depth=0, jump_kind="transition", + expect="Black Box moves Others->Starred on long-press") + else: + after = section_of(ui(), "Black Box") + ok = (before == "others" and after == "starred") + record("interaction_star_toggle_to_starred", ok, + "" if ok else f"behavior_wrong: long-press did not move Black Box " + f"to Starred (before={before} after={after})", + depth=0, jump_kind="transition", + expect="Black Box: section Others -> Starred after one long-press") + # VLM: a star badge is now drawn on a row in the Starred section (starred rows + # add a star icon; the badge itself is rendered art, not plain text). + vlm_assert("interaction_star_toggle_to_starred", + "In the 'Starred' section near the top, is there a puzzle row that " + "shows a small STAR icon/badge next to its thumbnail?", + RESULTS_DIR, tag="shape", depth=0, jump_kind="transition") + # restore: toggle Black Box back to Others so the suite stays independent + _reach_chooser() + _restore_to_others("Black Box") + + +@and_test(expects=("interaction_star_toggle_to_others", + "interaction_star_toggle_to_others_vlm")) +def test_star_toggle_to_others(): + """The REVERSE direction: long-press a default-Starred puzzle ('Net') -> it + MOVES to the Others section. Net starts as a top Starred row (visible), and + demotion sends it to the bottom of the long Others list (off-screen), so + membership() (the walk-down classifier) is used for the read-back. Net is + re-opened fresh by other tests, so demoting+restoring it here is independent. + Restored afterwards.""" + _reach_chooser() + before = membership("Net") + if before != "starred": + record("interaction_star_toggle_to_others", False, + f"setup_failed: 'Net' not in Starred to begin with (was {before})", + depth=0, jump_kind="transition", + expect="Net moves Starred->Others on long-press") + elif not _toggle_star("Net"): + record("interaction_star_toggle_to_others", False, + "feature_missing: could not long-press the 'Net' row", + depth=0, jump_kind="transition", + expect="Net moves Starred->Others on long-press") + else: + after = membership("Net") + ok = (before == "starred" and after == "others") + record("interaction_star_toggle_to_others", ok, + "" if ok else f"behavior_wrong: long-press did not move Net to " + f"Others (before={before} after={after})", + depth=0, jump_kind="transition", + expect="Net: section Starred -> Others after one long-press") + # VLM: with the list at the top and Net demoted, the top Starred rows still + # show star badges — a rendered position/shape property a dead shell lacks. + _reach_chooser() + vlm_assert("interaction_star_toggle_to_others", + "Directly under the 'Starred' heading at the very top, do the puzzle " + "rows there show a small star badge on their thumbnails?", + RESULTS_DIR, tag="position", depth=0, jump_kind="transition") + # restore Net to Starred + _reach_chooser() + _restore_to_starred("Net") + + +@and_test(expects=("interaction_star_toggle_round_trip",)) +def test_star_toggle_round_trip(): + """Toggle-and-restore round trip on 'Cube': Others -> (long-press) Starred -> + (long-press) Others. Cube is a top Others row and lands as a Starred row, so + all three states are read from the top-of-list dump with section_of() (no + scroll). Proves the toggle is its own inverse and leaves no residue — a dead + shell that only ever adds to one section fails the return leg.""" + nodes = _reach_chooser() + s0 = section_of(nodes, "Cube") + if s0 != "others": + record("interaction_star_toggle_round_trip", False, + f"setup_failed: 'Cube' not in Others to begin with (was {s0})", + depth=0, jump_kind="transition", + expect="Cube: Others -> Starred -> Others across two long-presses") + return + _toggle_star("Cube") + s1 = section_of(ui(), "Cube") + _toggle_star("Cube") + s2 = section_of(ui(), "Cube") + ok = (s0 == "others" and s1 == "starred" and s2 == "others") + record("interaction_star_toggle_round_trip", ok, + "" if ok else f"behavior_wrong: toggle round trip Cube {s0}->{s1}->{s2} " + f"(expected others->starred->others)", + depth=0, jump_kind="transition", + expect="Cube section others -> starred -> others across two long-presses") + + +@and_test(expects=("interaction_star_multi_record", + "interaction_star_multi_record_vlm")) +def test_star_multi_record(): + """Multi-record integrity: star TWO different Others puzzles ('Bridges' and + 'Dominosa'), then assert BOTH moved to Starred AND a control puzzle ('Cube') + stayed in Others. All three are top-boundary rows read with section_of() (no + scroll). Catches a recreation that keeps only one starred row. Both are + restored afterwards.""" + nodes = _reach_chooser() + b0 = section_of(nodes, "Bridges") + d0 = section_of(nodes, "Dominosa") + c0 = section_of(nodes, "Cube") + if not (b0 == "others" and d0 == "others" and c0 == "others"): + record("interaction_star_multi_record", False, + f"setup_failed: starting sections not all Others " + f"(Bridges={b0} Dominosa={d0} Cube={c0})", + depth=0, jump_kind="value", + expect="Bridges & Dominosa -> Starred; Cube stays Others") + else: + _toggle_star("Bridges") + _toggle_star("Dominosa") + after = ui() + b1 = section_of(after, "Bridges") + d1 = section_of(after, "Dominosa") + c1 = section_of(after, "Cube") + ok = (b1 == "starred" and d1 == "starred" and c1 == "others") + record("interaction_star_multi_record", ok, + "" if ok else f"behavior_wrong: multi-star integrity failed " + f"(Bridges={b1} Dominosa={d1} Cube(control)={c1}; expected " + f"starred/starred/others)", + depth=0, jump_kind="value", + expect="Bridges=Starred, Dominosa=Starred, Cube=Others (control " + "intact) after starring two rows") + # VLM: the Starred section now visibly contains MORE than the default number of + # star-badged rows near the top. + _reach_chooser() + if section_of(ui(), "Bridges") == "others": + _toggle_star("Bridges") + if section_of(ui(), "Dominosa") == "others": + _toggle_star("Dominosa") + vlm_assert("interaction_star_multi_record", + "Directly under the 'Starred' heading at the top, are there several " + "puzzle rows each showing a star badge on its thumbnail (more than " + "one starred row)?", + RESULTS_DIR, tag="position", depth=0, jump_kind="value") + # restore after the VLM shot + _reach_chooser() + _restore_to_others("Bridges") + _restore_to_others("Dominosa") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (2) DATA persistence across PROCESS DEATH — this lane's highest-value tests +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_star_persists_death", + "interaction_star_persists_death_vlm")) +def test_star_persists_process_death(): + """Star state survives a full process kill. Long-press 'Dominosa' (a top Others + row -> Starred), then force_stop_and_relaunch(), then re-open the chooser and + assert it is STILL in Starred (read from the top dump — a promoted game shows + as a top Starred row). An in-memory-only recreation cannot pass this. Restored + afterwards so later tests start from the default set.""" + nodes = _reach_chooser() + before = section_of(nodes, "Dominosa") + if before != "others": + record("interaction_star_persists_death", False, + f"setup_failed: 'Dominosa' not in Others to begin with (was {before})", + depth=0, jump_kind="value", + expect="Dominosa still Starred after force-stop + relaunch") + elif not _toggle_star("Dominosa"): + record("interaction_star_persists_death", False, + "feature_missing: could not long-press 'Dominosa' to star it", + depth=0, jump_kind="value", + expect="Dominosa still Starred after force-stop + relaunch") + else: + moved = section_of(ui(), "Dominosa") == "starred" + # kill the process and relaunch, then recover the chooser + force_stop_and_relaunch() + wait_for_foreground(10) + if "GamePlay" in get_current_activity(): + back() + wait_for_foreground(5) + persisted = section_of(ui(), "Dominosa") == "starred" + ok = moved and persisted + record("interaction_star_persists_death", ok, + "" if ok else "behavior_wrong: 'Dominosa' star did not survive " + "force-stop + relaunch (not in Starred after process death)", + depth=0, jump_kind="value", + expect="Dominosa in Starred both after the long-press AND after " + "force-stop + relaunch") + # VLM: after the relaunch, the Starred section still visibly holds a star-badged + # row (the persisted record is drawn). + vlm_assert("interaction_star_persists_death", + "Under the 'Starred' heading at the top of the list, is there a " + "puzzle row with a star badge on its thumbnail?", + RESULTS_DIR, tag="position", depth=0, jump_kind="value") + # restore Dominosa to Others + _reach_chooser() + _restore_to_others("Dominosa") + + +@and_test(expects=("interaction_game_resume_after_death",)) +def test_game_resume_after_death(): + """Game-STATE persistence across process death (singleTask RESUMES the last + game). Open 'Net', make an observable change (Show solution -> 'Auto-solved. '), + then force_stop_and_relaunch(); the app RESUMES GamePlay for the SAME puzzle — + assert the resumed toolbar title is still 'Net' (the reproducibly-persistent + identity). depth=1 because the record lives on the resumed GamePlay surface we + navigated to.""" + gp = and_enter_game("Net") + if not gp: + record("interaction_game_resume_after_death", False, + "setup_failed: could not open the Net puzzle to test resume", + depth=1, jump_kind="value", + expect="GamePlay resumes with title 'Net' after force-stop + relaunch") + return + title_before = _toolbar_title(gp) + # drive an observable game-state change so the state is non-trivial + and_reach_game_menu_item(gp, "Show solution") + solved = _status_text() + # kill and relaunch — singleTask should resume the same GamePlay + force_stop_and_relaunch() + wait_for_foreground(10) + act = get_current_activity() + resumed_gameplay = "GamePlay" in act + title_after = _toolbar_title() + ok = (title_before == "Net" and resumed_gameplay and title_after == "Net") + record("interaction_game_resume_after_death", ok, + "" if ok else f"behavior_wrong: app did not resume the same puzzle after " + f"process death (title_before={title_before!r} activity={act!r} " + f"title_after={title_after!r}, pre-kill status={solved!r})", + depth=1, jump_kind="value", + expect="GamePlay resumed with toolbar title 'Net' after force-stop + " + "relaunch (same in-progress puzzle)") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (3) Multi-step (3+) game-state sequences — deterministic, rule-readable +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_net_solution_undo_redo", + "interaction_net_solution_undo_redo_solved_vlm", + "interaction_net_solution_undo_redo_unsolved_vlm")) +def test_net_solution_undo_redo(): + """A 3+ step DATA-state sequence where each action depends on the last, all + deterministic and rule-readable via status_bar: + Show solution -> status 'Auto-solved. ' + -> Undo -> status back to an 'Active: N/25' form (NOT auto-solved) + -> Redo -> status back to 'Auto-solved. ' + A dead shell that echoes only the first input cannot reproduce all three.""" + gp = and_enter_game("Net") + if not gp: + record("interaction_net_solution_undo_redo", False, + "setup_failed: could not open Net to run the Undo/Redo sequence", + depth=1, jump_kind="value", + expect="status: Auto-solved. -> Active:N/25 -> Auto-solved.") + elif not and_reach_game_menu_item(gp, "Show solution"): + record("interaction_net_solution_undo_redo", False, + "feature_missing: Game menu has no working 'Show solution'", + depth=1, jump_kind="value", + expect="status: Auto-solved. -> Active:N/25 -> Auto-solved.") + else: + s_solved = _status_text() + undo = find_node(ui(), content_desc="Undo") + tapped_undo = bool(undo and tap_node(undo)) + s_undo = _status_text() + redo = find_node(ui(), content_desc="Redo") + tapped_redo = bool(redo and tap_node(redo)) + s_redo = _status_text() + solved_ok = s_solved.strip() == "Auto-solved." + undo_ok = (tapped_undo and s_undo.strip() != "Auto-solved." + and s_undo.startswith("Active:")) + redo_ok = (tapped_redo and s_redo.strip() == "Auto-solved.") + ok = solved_ok and undo_ok and redo_ok + record("interaction_net_solution_undo_redo", ok, + "" if ok else f"behavior_wrong: Undo/Redo not inverse of Show " + f"solution (solved={s_solved!r} afterUndo={s_undo!r} " + f"afterRedo={s_redo!r})", + depth=1, jump_kind="value", + expect="status_bar: 'Auto-solved. ' -> Undo -> 'Active: N/25' " + "-> Redo -> 'Auto-solved. '") + # VLM #1 (solved look): after Show solution the endpoint tiles render bright + # CYAN, connected by cyan wires (the solved rendering). A dark/blue-endpoint + # grid would fail this — genuine colour discrimination on the canvas. + gp2 = and_enter_game("Net") + if gp2: + and_reach_game_menu_item(gp2, "Show solution") + vlm_assert("interaction_net_solution_undo_redo_solved", + "In the puzzle grid, are the small square endpoint tiles lit up " + "bright CYAN/turquoise and joined by cyan lines (a solved, " + "fully-connected look)?", + RESULTS_DIR, tag="color", depth=1, jump_kind="value") + # VLM #2 (unsolved look): a fresh Net (not solved) renders most endpoint tiles + # as dark BLUE (disconnected) with mostly black connecting lines — the opposite + # colour state from the solved grid above. + and_enter_game("Net") + vlm_assert("interaction_net_solution_undo_redo_unsolved", + "In the puzzle grid, are most of the small square endpoint tiles a " + "dark BLUE colour (unlit / not connected), rather than all lit " + "bright cyan?", + RESULTS_DIR, tag="color", depth=1, jump_kind="value") + + +@and_test(expects=("interaction_net_solution_restart",)) +def test_net_solution_restart(): + """Another multi-step sequence: Show solution -> status 'Auto-solved. ' -> + Game menu -> Restart -> status reverts to an 'Active: N/25' form (Restart + reverts the current game to its start; it is a non-destructive game action). + Two dependent state changes read back out of the status_bar.""" + gp = and_enter_game("Net") + if not gp: + record("interaction_net_solution_restart", False, + "setup_failed: could not open Net to run the Restart sequence", + depth=1, jump_kind="value", + expect="status: Auto-solved. -> Restart -> Active:N/25") + return + if not and_reach_game_menu_item(gp, "Show solution"): + record("interaction_net_solution_restart", False, + "feature_missing: Game menu has no working 'Show solution'", + depth=1, jump_kind="value", + expect="status: Auto-solved. -> Restart -> Active:N/25") + return + s_solved = _status_text() + if not and_reach_game_menu_item(ui(), "Restart"): + record("interaction_net_solution_restart", False, + "feature_missing: Game menu has no working 'Restart'", + depth=1, jump_kind="value", + expect="status: Auto-solved. -> Restart -> Active:N/25") + return + s_restart = _status_text() + ok = (s_solved.strip() == "Auto-solved." + and s_restart.strip() != "Auto-solved." + and s_restart.startswith("Active:")) + record("interaction_net_solution_restart", ok, + "" if ok else f"behavior_wrong: Restart did not revert 'Auto-solved.' to " + f"an 'Active: N/25' form (solved={s_solved!r} afterRestart={s_restart!r})", + depth=1, jump_kind="value", + expect="status_bar: 'Auto-solved. ' -> Restart -> 'Active: N/25' form") + + +@and_test(expects=("interaction_net_tile_tap_vlm",)) +def test_net_tile_tap_rotate(): + """VLM-only canvas edit: on a fresh Net game, the grid draws puzzle tiles with + short wire segments at various orientations (the state a tap operates on). The + tile art is on the canvas (not the tree), so this is a genuine VLM question + about a rendered property. depth=1 (edit surface reached via navigation).""" + gp = and_enter_game("Net") + if gp: + # fresh game so the board is reproducible, then tap a corner tile + and_reach_game_menu_item(gp, "New game") + gv = node_by_id(ui(), "game_view") + if gv: + tx, ty = _keen_cell_center(gv, 0, 0) # square-grid math works for Net + tap(tx, ty) + vlm_assert("interaction_net_tile_tap", + "Does the grid show puzzle tiles with short wire/line segments " + "drawn on them pointing in various directions (an in-progress " + "network puzzle), rather than a blank featureless grid?", + RESULTS_DIR, tag="shape", depth=1, jump_kind="value") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (4) Canvas DATA edit on Keen — tap cell -> digit renders -> backspace clears +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_keen_digit_entry", + "interaction_keen_digit_shown_vlm", + "interaction_keen_digit_cleared_vlm")) +def test_keen_digit_entry(): + """A canvas DATA-edit sequence on Keen: tap a grid cell -> tap digit '3' -> + the digit is written into the cell (rendered green) -> Backspace -> the cell is + empty again. The rule half asserts the digit controls exist and the taps land; + the two VLM halves assert the rendered digit (canvas, genuine VLM). depth=1 + (edit made on the GamePlay surface). Uses a fresh 'New game' for reproducibility + and taps a cell derived from game_view bounds (no hardcoded pixels).""" + gp = and_enter_game("Keen") + if not gp: + record("interaction_keen_digit_entry", False, + "setup_failed: could not open Keen to run the digit-entry sequence", + depth=1, jump_kind="value", + expect="digit '3' written into a cell then cleared by Backspace") + else: + and_reach_game_menu_item(gp, "New game") + nodes = ui() + gv = node_by_id(nodes, "game_view") + d3 = find_node(nodes, content_desc="3") + bs = find_node(nodes, content_desc="Backspace") + controls_ok = bool(gv and d3 and bs) + if not controls_ok: + record("interaction_keen_digit_entry", False, + "feature_missing: Keen lacks game_view / digit '3' / Backspace " + "controls for digit entry", + depth=1, jump_kind="value", + expect="digit '3' written into a cell then cleared by Backspace") + else: + # tap an interior cell (col2,row3 is a plain entry cell), then digit 3 + tx, ty = _keen_cell_center(gv, 2, 3) + tap(tx, ty) + d3b = find_node(ui(), content_desc="3") + tapped_digit = bool(d3b and tap_node(d3b)) + # (the rendered digit is asserted on the VLM track below) + bsb = find_node(ui(), content_desc="Backspace") + tapped_bs = bool(bsb and tap_node(bsb)) + ok = controls_ok and tapped_digit and tapped_bs + record("interaction_keen_digit_entry", ok, + "" if ok else "behavior_wrong: could not drive the tap-cell -> " + "digit -> Backspace edit sequence on Keen", + depth=1, jump_kind="value", + expect="Keen: tapped a cell, then digit '3', then Backspace " + "(controls present and each tap dispatched)") + # VLM #1: after tapping a cell + '3', a green digit '3' is rendered inside a + # grid cell (the write result — canvas, not in the tree). + gp2 = and_enter_game("Keen") + if gp2: + and_reach_game_menu_item(gp2, "New game") + gv2 = node_by_id(ui(), "game_view") + if gv2: + cx, cy = _keen_cell_center(gv2, 2, 3) + tap(cx, cy) + d = find_node(ui(), content_desc="3") + if d: + tap_node(d) + vlm_assert("interaction_keen_digit_shown", + "Is the digit '3' displayed inside one of the grid cells (a large " + "coloured number entered in a cell), not only on the number buttons " + "along the bottom of the screen?", + RESULTS_DIR, tag="content", depth=1, jump_kind="value") + # VLM #2: after Backspace, that cell is empty again (the digit was removed). + bs2 = find_node(ui(), content_desc="Backspace") + if bs2: + tap_node(bs2) + vlm_assert("interaction_keen_digit_cleared", + "After clearing, is the previously selected grid cell now EMPTY " + "(no large entered digit inside it, showing at most a small " + "arithmetic clue)?", + RESULTS_DIR, tag="content", depth=1, jump_kind="value") + + +TESTS = [ + # long-press star toggle (sole owner of long-press) + test_star_toggle_to_starred, + test_star_toggle_to_others, + test_star_toggle_round_trip, + test_star_multi_record, + # DATA persistence across process death (marquee) + test_star_persists_process_death, + test_game_resume_after_death, + # multi-step (3+) game-state sequences + test_net_solution_undo_redo, + test_net_solution_restart, + test_net_tile_tap_rotate, + # canvas DATA edit + test_keen_digit_entry, +] + + +if __name__ == "__main__": + run_suite(TESTS, "interaction") diff --git a/android/chrisboyle-sgtpuzzles/tests/test_android_navigation.py b/android/chrisboyle-sgtpuzzles/tests/test_android_navigation.py new file mode 100644 index 0000000000000000000000000000000000000000..a1795d18768f4e5c3071e28562bd39cfd11a2618 --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/tests/test_android_navigation.py @@ -0,0 +1,875 @@ +#!/usr/bin/env python3 +"""Navigation lane — Simon Tatham's Puzzles (name.boyle.chris.sgtpuzzles). + +This lane owns SURFACE REACHABILITY and BACK-STACK INTEGRITY: tapping a nav +trigger (puzzle row, toolbar action, menu item, dialog button) lands on the +intended surface, and BACK unwinds the stack hop by hop. It is the SOLE owner of +jump_kind="reach" and of the depth>=2 chains — the other lanes stay shallow so +real navigation depth is measured here. + +Every jump is proven with and_reach(before, after, target, source): the TARGET +surface's discriminating element APPEARED *and* the SOURCE surface's DISAPPEARED. +A screen that was in the dump all along was never reached. + +Ground truth (ALL observed on the running original during recon + live probes): + - GameChooser (LAUNCHER): toolbar with content-desc Settings / Load… / Help; + scrollView>table (GridLayout) of puzzle rows (id=text = ": "), + section header TextView "Others", title "Puzzles". NOTE (probe-verified): + uiautomator keeps the chooser's `table` node in the dump even under + PrefsActivity, so the chooser's `scrollView` (which DOES leave) is the honest + source discriminator for a chooser->Settings jump. + - GamePlay (.GamePlay, singleTask -> RESUMES last game): toolbar (Navigate up + + Game/Type/Help), game_view (Canvas), status_bar, buttons. Title TextView = + the puzzle name ("Net"/"Keen"). Reached by tapping a puzzle row. Opening the + Game/Type popup DROPS game_view out of the dump while the popup is up, so the + source discriminator when jumping FROM an open popup is a menu item, not + game_view. + - PrefsActivity (.PrefsActivity): recycler_view of Switch/category rows. + Reached from the chooser "Settings" button OR from the GamePlay Game-menu -> + Settings (depth 2). Tapping "Display and input" opens a deeper preferences + surface (Long-press timeout / SeekBar / Keyboard rows) — depth 3 from chooser. + - HelpActivity (.HelpActivity): title "Help: Contents" + WebView. Reached from + the chooser Help popup ("Help" + "Send feedback" items) -> "Help" item + (depth 2: popup then activity). Source discriminator = "Send feedback" (only + in the popup, gone in HelpActivity). + - type_menu popup (overlay): RADIO list of presets + "Custom…". + - game_menu popup (overlay): New game / Restart / Show solution / Load… / Save… / + Share… / Settings. + - Custom… dialog (AlertDialog, depth 2 via type_menu->Custom…): alertTitle + " configuration"; buttons OK (button1) / GAME ID… (button2) / + SEED… (button3). + - GAME ID… dialog (depth 3 from game): alertTitle " game selection", + an EditText + OK. + - Load… opens the EXTERNAL system file picker (com.android.documentsui) — leaves + the app package; a single reach test, then BACK out immediately. +""" + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ── Local navigation helpers (NAMED in the depth family and_enter*/and_reach* so +# every declared depth>=1 / jump_kind="reach" is backed by a real nav call) ── + +def _reach_chooser(): + """Land on GameChooser. The app is singleTask and RESUMES the last game on a + fresh launch, so pop GamePlay with BACK when we land there (recon-verified). + Returns the chooser node tree.""" + restart_app() + wait_for_foreground(10) + if "GamePlay" in get_current_activity(): + back() + wait_for_foreground(5) + return ui() + + +def _find_puzzle_row(nodes, name): + """The chooser row whose text is ': '.""" + for n in nodes: + if (n.get("resource-id", "").endswith("/text") + and n.get("text", "").startswith(name + ":")): + return n + return None + + +def and_reach_gameplay(name="Net"): + """Chooser -> tap puzzle row -> GamePlay. PROVES the jump (game_view appears, + chooser table disappears) and counts one surface. Returns (ok, gp_nodes).""" + nodes = _reach_chooser() + row = _find_puzzle_row(nodes, name) + for _ in range(7): + if row: + break + scroll_down(0.5) + row = _find_puzzle_row(ui(), name) + if not row: + return False, [] + before = and_showing() + if not safe_tap(row): + return False, [] + wait_for_foreground(5) + after = and_showing() + ok = and_reach(before, after, "game_view", "table") + if ok: + and_enter(name) + return ok, ui() + + +def and_reach_settings_from_chooser(): + """Chooser toolbar 'Settings' -> PrefsActivity. PROVES recycler_view appears + and the chooser's scrollView disappears. (uiautomator keeps the chooser's + 'table' node in the dump under PrefsActivity, so the chooser's scrollView — + which does leave — is the honest source discriminator.) Returns (ok, prefs).""" + nodes = _reach_chooser() + st = find_node(nodes, content_desc="Settings") + if not st: + return False, [] + before = and_showing() + if not tap_node(st): + return False, [] + wait_for_foreground(5) + after = and_showing() + ok = and_reach(before, after, "recycler_view", "scrollView") + if ok: + and_enter("Settings") + return ok, ui() + + +def and_enter_game_menu(gp): + """Open the GamePlay Game-menu popup. Counts one surface (a popup layer).""" + trig = find_node(gp, content_desc="Game") + if not trig or not tap_node(trig): + return False + and_enter("game_menu") + return True + + +def and_enter_type_menu(gp): + """Open the GamePlay Type-menu popup. Counts one surface (a popup layer).""" + trig = find_node(gp, content_desc="Type") + if not trig or not tap_node(trig): + return False + and_enter("type_menu") + return True + + +def _find_menu_item(nodes, label): + """A popup/menu item TextView whose visible text equals `label`.""" + for n in nodes: + if "TextView" in n.get("class", "") and n.get("text", "") == label: + return n + return None + + +def _find_radio_title(nodes, label): + """A type-menu preset row (id=title) whose text equals `label` (e.g. Custom…).""" + for n in nodes: + if (n.get("resource-id", "").endswith("/title") + and n.get("text", "") == label): + return n + return None + + +def and_reach_help_activity(): + """Chooser -> Help popup -> 'Help' item -> HelpActivity. PROVES the + 'Help: Contents' title appears and the popup's 'Send feedback' item disappears. + Counts the popup + the activity as two surfaces. Returns (ok, help_nodes).""" + nodes = _reach_chooser() + help_btn = find_node(nodes, content_desc="Help") + if not help_btn or not tap_node(help_btn): + return False, [] + and_enter("help_popup") # popup layer = surface 1 + help_item = _find_menu_item(ui(), "Help") + if not help_item: + return False, [] + before = and_showing() # the popup (Help + Send feedback) + if not tap_node(help_item): + return False, [] + wait_for_foreground(5) + after = and_showing() + ok = and_reach(before, after, "Help: Contents", "Send feedback") + if ok: + and_enter("HelpActivity") # activity = surface 2 + return ok, ui() + + +def and_reach_file_picker(): + """Chooser 'Load…' -> EXTERNAL system file picker. PROVES the foreground + activity is no longer in the app package (a different app is on top). Counts + one surface. Returns (ok, resumed_activity).""" + nodes = _reach_chooser() + load_btn = (find_node(nodes, content_desc="Load…") + or find_node(nodes, content_desc="Load")) + if not load_btn or not is_app_foreground(): + return False, "" + if not tap_node(load_btn): + return False, "" + settle("launch") + settle("tap") + act = get_current_activity() + ok = bool(act) and (PACKAGE not in act) + if ok: + and_enter("file_picker") + return ok, act + + +def and_reach_custom_dialog(name="Net"): + """Chooser -> GamePlay -> Type menu -> Custom… -> config AlertDialog. Deep + chain (depth 3 forward): PROVES the ' configuration' title appears and + the type-menu radio list disappears. Returns (ok, dialog_nodes).""" + ok_game, gp = and_reach_gameplay(name) + if not ok_game: + return False, [] + if not and_enter_type_menu(gp): + return False, [] + tm = ui() + cust = _find_radio_title(tm, "Custom…") + if not cust: + return False, [] + before = and_showing() + if not tap_node(cust): + return False, [] + after = and_showing() + # target: the " configuration" title; source: a type-menu preset radio + ok = and_reach(before, after, f"{name} configuration", "radio") + if ok: + and_enter("custom_dialog") + return ok, ui() + + +def and_reach_gameid_dialog(name="Net"): + """DEEPEST chain (depth 4 forward hops): chooser -> GamePlay -> Type menu -> + Custom… dialog -> GAME ID… dialog. PROVES the ' game selection' title + appears and the config title disappears. Returns (ok, gameid_nodes).""" + ok_cust, dlg = and_reach_custom_dialog(name) + if not ok_cust: + return False, [] + gid_btn = node_by_id(dlg, "button2") # "GAME ID…" + if not gid_btn: + return False, [] + before = and_showing() + if not tap_node(gid_btn): + return False, [] + after = and_showing() + ok = and_reach(before, after, f"{name} game selection", f"{name} configuration") + if ok: + and_enter("gameid_dialog") + return ok, ui() + + +# ══════════════════════════════════════════════════════════════════════════════ +# (1) Top-level destinations — each a single-hop reach +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_gameplay", "nav_reach_gameplay_vlm")) +def test_reach_gameplay(): + """Chooser -> tap a puzzle row -> GamePlay: the game_view canvas surface + appears and the chooser puzzle table disappears.""" + ok, gp = and_reach_gameplay("Net") + # corroborate the destination shape we observed + shape_ok = bool(gp and node_by_id(gp, "game_view") + and node_by_id(gp, "status_bar") + and find_node(gp, content_desc="Navigate up")) + passed = ok and shape_ok + record("nav_reach_gameplay", passed, + "" if passed else "feature_missing: tapping a puzzle row did not reach " + "the GamePlay game_view surface (chooser table did not give way)", + depth=1, jump_kind="reach", + expect="GamePlay: game_view + status_bar + Navigate up present; chooser " + "table no longer showing") + # Rendered content: a puzzle grid is now drawn on the canvas — proves we are on + # the game, not still looking at the list. + vlm_assert("nav_reach_gameplay", + "Is a single square puzzle grid drawn in the center of the screen " + "(a game board), rather than a vertical list of text rows?", + RESULTS_DIR, tag="content", depth=1, jump_kind="reach") + + +@and_test(expects=("nav_gameplay_back_chooser",)) +def test_gameplay_back_chooser(): + """Back-stack integrity: from GamePlay, BACK pops to the chooser — the puzzle + table reappears and the game_view canvas disappears.""" + ok, gp = and_reach_gameplay("Net") + if not ok: + record("nav_gameplay_back_chooser", False, + "setup_failed: could not reach GamePlay to test BACK", + depth=1, jump_kind="reach", + expect="chooser table restored after one BACK from GamePlay") + return + before = and_showing(gp) + and_back() # pop GamePlay + wait_for_foreground(5) + after = and_showing() + # going back: the chooser table is present, and the game_view that was showing + # has now left the surface + passed = (any("table" in k.lower() for k in after) + and any("game_view" in k.lower() for k in before) + and not any("game_view" in k.lower() for k in after)) + record("nav_gameplay_back_chooser", passed, + "" if passed else "behavior_wrong: BACK from GamePlay did not restore " + "the chooser table / did not dismiss the game_view", + depth=1, jump_kind="reach", + expect="chooser table present and game_view gone after one BACK") + + +@and_test(expects=("nav_reach_settings_chooser", "nav_reach_settings_chooser_vlm")) +def test_reach_settings_chooser(): + """Chooser toolbar 'Settings' -> PrefsActivity: the settings recycler_view + surface appears and the chooser's scrollView disappears.""" + ok, prefs = and_reach_settings_from_chooser() + shape_ok = bool(prefs and node_by_id(prefs, "recycler_view") + and len(find_by_class(prefs, "Switch")) >= 2) + passed = ok and shape_ok + record("nav_reach_settings_chooser", passed, + "" if passed else "feature_missing: chooser 'Settings' did not reach a " + "PrefsActivity recycler_view with >=2 Switch rows", + depth=1, jump_kind="reach", + expect="Settings: recycler_view with >=2 Switch rows present; chooser " + "scrollView no longer showing") + # Rendered layout: a scrollable settings list with ON/OFF toggle rows. + vlm_assert("nav_reach_settings_chooser", + "Is this a settings screen showing a vertical scrollable list of " + "labelled rows, at least two of which have an ON/OFF toggle switch?", + RESULTS_DIR, tag="layout", depth=1, jump_kind="reach") + + +@and_test(expects=("nav_settings_back_chooser",)) +def test_settings_back_chooser(): + """Back-stack integrity: from PrefsActivity, BACK pops to the chooser — the + chooser's scrollView reappears and the settings recycler_view disappears.""" + ok, prefs = and_reach_settings_from_chooser() + if not ok: + record("nav_settings_back_chooser", False, + "setup_failed: could not reach Settings to test BACK", + depth=1, jump_kind="reach", + expect="chooser restored after one BACK from Settings") + return + before = and_showing(prefs) + and_back() # pop PrefsActivity + wait_for_foreground(5) + after = and_showing() + passed = (any("scrollview" in k.lower() for k in after) + and any("recycler_view" in k.lower() for k in before) + and not any("recycler_view" in k.lower() for k in after)) + record("nav_settings_back_chooser", passed, + "" if passed else "behavior_wrong: BACK from Settings did not restore " + "the chooser (scrollView) / did not dismiss the recycler_view", + depth=1, jump_kind="reach", + expect="chooser scrollView present and recycler_view gone after one BACK") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (2) depth>=2 chains — this lane's exclusive territory +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_settings_from_game",)) +def test_reach_settings_from_game(): + """2-hop chain: chooser -> GamePlay -> Game menu -> 'Settings' -> PrefsActivity. + Opening the Game menu drops game_view out of the dump, so the source + discriminator is the menu's own 'New game' item: the recycler_view appears and + the 'New game' menu item disappears.""" + ok, gp = and_reach_gameplay("Net") + if not ok or not and_enter_game_menu(gp): + record("nav_reach_settings_from_game", False, + "setup_failed: could not open the Game menu from GamePlay", + depth=2, jump_kind="reach", + expect="PrefsActivity recycler_view via game menu; 'New game' gone") + return + menu = ui() + setn = _find_menu_item(menu, "Settings") + if not setn: + record("nav_reach_settings_from_game", False, + "feature_missing: Game menu has no 'Settings' item", + depth=2, jump_kind="reach", + expect="PrefsActivity recycler_view via game menu; 'New game' gone") + return + before = and_showing() # captured while the popup is up + tap_node(setn) + wait_for_foreground(5) + after = and_showing() + ok_reach = and_reach(before, after, "recycler_view", "New game") + if ok_reach: + and_enter("Settings") + passed = ok_reach and bool(node_by_id(ui(), "recycler_view")) + record("nav_reach_settings_from_game", passed, + "" if passed else "behavior_wrong: Game menu -> Settings did not reach " + "the recycler_view surface (the 'New game' menu item did not give way)", + depth=2, jump_kind="reach", + expect="Game menu -> Settings: recycler_view present; 'New game' menu " + "item gone") + + +@and_test(expects=("nav_reach_help", "nav_reach_help_vlm")) +def test_reach_help(): + """2-surface chain: chooser -> Help popup (surface 1) -> 'Help' item -> + HelpActivity (surface 2). The 'Help: Contents' title + WebView appear and the + popup's 'Send feedback' item disappears.""" + nodes = _reach_chooser() + help_btn = find_node(nodes, content_desc="Help") + if not help_btn or not tap_node(help_btn): + record("nav_reach_help", False, + "setup_failed: chooser Help button not found/tappable", + depth=2, jump_kind="reach", + expect="HelpActivity 'Help: Contents' + WebView; 'Send feedback' gone") + else: + and_enter("help_popup") # popup layer = surface 1 + popup = ui() + help_item = _find_menu_item(popup, "Help") + if not help_item: + record("nav_reach_help", False, + "feature_missing: Help popup has no 'Help' item", + depth=2, jump_kind="reach", + expect="HelpActivity 'Help: Contents' + WebView; 'Send feedback' gone") + else: + before = and_showing() # the popup (Help + Send feedback) + tap_node(help_item) + wait_for_foreground(5) + after = and_showing() + reached = and_reach(before, after, "Help: Contents", "Send feedback") + if reached: + and_enter("HelpActivity") # activity = surface 2 + webview_ok = bool(find_by_class(ui(), "WebView")) + title_ok = bool(find_node_ci(ui(), "Help: Contents")) + passed = reached and webview_ok and title_ok + record("nav_reach_help", passed, + "" if passed else "behavior_wrong: chooser Help -> 'Help' did not " + "reach the HelpActivity ('Help: Contents' title + WebView)", + depth=2, jump_kind="reach", + expect="HelpActivity: 'Help: Contents' title + WebView present; " + "popup 'Send feedback' item gone") + # Rendered content: help/documentation text (a WebView, NOT in the view tree) — + # a genuine VLM question. + vlm_assert("nav_reach_help", + "Does the screen show a page of readable help/documentation text " + "(paragraphs or a list of topic links), like a web help page?", + RESULTS_DIR, tag="content", depth=2, jump_kind="reach") + + +@and_test(expects=("nav_help_back_chooser",)) +def test_help_back_chooser(): + """Back-stack integrity across a 2-surface chain: from HelpActivity, BACK pops + to the chooser — the puzzle table reappears and the 'Help: Contents' title + disappears.""" + ok, help_nodes = and_reach_help_activity() + if not ok: + record("nav_help_back_chooser", False, + "setup_failed: could not open HelpActivity to test BACK", + depth=2, jump_kind="reach", + expect="chooser table restored after BACK from HelpActivity") + return + before = and_showing(help_nodes) + and_back() # pop HelpActivity + wait_for_foreground(5) + after = and_showing() + passed = (any("table" in k.lower() for k in after) + and any("help: contents" in k.lower() for k in before) + and not any("help: contents" in k.lower() for k in after)) + record("nav_help_back_chooser", passed, + "" if passed else "behavior_wrong: BACK from HelpActivity did not restore " + "the chooser table / did not dismiss the 'Help: Contents' surface", + depth=2, jump_kind="reach", + expect="chooser table present and 'Help: Contents' gone after BACK") + + +@and_test(expects=("nav_reach_custom_dialog", "nav_reach_custom_dialog_vlm")) +def test_reach_custom_dialog(): + """2-hop chain: chooser -> GamePlay -> Type menu -> 'Custom…' -> the ' + configuration' AlertDialog. The config title appears and the type-menu radio + list disappears.""" + ok, dlg = and_reach_custom_dialog("Net") + shape_ok = bool(dlg and node_by_id(dlg, "button1") # OK + and node_by_id(dlg, "button2") # GAME ID… + and node_by_id(dlg, "alertTitle")) + passed = ok and shape_ok + record("nav_reach_custom_dialog", passed, + "" if passed else "feature_missing: Type menu -> Custom… did not reach " + "the ' configuration' dialog (alertTitle + OK/GAME ID buttons)", + depth=2, jump_kind="reach", + expect="'Net configuration' dialog with OK + GAME ID… buttons present; " + "type-menu radio list no longer showing") + # Rendered position: a dialog box centered over the (dimmed) game, with an OK + # button in it. + vlm_assert("nav_reach_custom_dialog", + "Is a configuration dialog box shown centered on the screen, " + "overlaying the game behind it, with an 'OK' button inside it?", + RESULTS_DIR, tag="position", depth=2, jump_kind="reach") + + +@and_test(expects=("nav_reach_gameid_dialog",)) +def test_reach_gameid_dialog(): + """DEEP chain (chooser -> GamePlay -> Type menu -> Custom… -> GAME ID…): from + the config dialog, 'GAME ID…' opens the ' game selection' dialog. Its + title appears and the 'configuration' title disappears.""" + ok, gid = and_reach_gameid_dialog("Net") + shape_ok = bool(gid and node_by_id(gid, "alertTitle") + and find_by_class(gid, "EditText")) + passed = ok and shape_ok + record("nav_reach_gameid_dialog", passed, + "" if passed else "feature_missing: Custom… -> GAME ID… did not reach " + "the ' game selection' dialog (title + EditText)", + depth=3, jump_kind="reach", + expect="'Net game selection' dialog (alertTitle + EditText) present; " + "'Net configuration' title no longer showing") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (3) Popup overlays open + BACK closes (back-stack of transient layers) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_type_menu_open", "nav_type_menu_open_vlm")) +def test_type_menu_open(): + """GamePlay -> tap Type: the preset RADIO list popup appears over the game (the + radio group + '5x5' preset show up, which the plain game surface lacked).""" + ok, gp = and_reach_gameplay("Net") + if not ok: + record("nav_type_menu_open", False, + "setup_failed: could not reach GamePlay to open the Type menu", + depth=1, jump_kind="reach", + expect="Type-menu radio list appears over the game_view") + else: + before = and_showing(gp) + trig = find_node(gp, content_desc="Type") + tapped = bool(trig and tap_node(trig)) + if tapped: + and_enter("type_menu") + after = and_showing() + radio_appeared = and_reach(before, after, "radiobutton") + has_preset = bool(_find_radio_title(ui(), "5x5")) + passed = tapped and radio_appeared and has_preset + record("nav_type_menu_open", passed, + "" if passed else "behavior_wrong: tapping Type did not open the " + "preset radio list popup (no RadioButton / no 5x5 preset appeared)", + depth=1, jump_kind="reach", + expect="RadioButton group + '5x5' preset appear over the game") + # Rendered position: a vertical list of size presets shown as a popup, with the + # radio-button circles down the RIGHT side and exactly one selected (verified + # against the actual screenshot). + ok2, gp2 = and_reach_gameplay("Net") + if ok2: + tap_node(find_node(gp2, content_desc="Type")) + vlm_assert("nav_type_menu_open", + "Is a vertical list of size options (like '5x5', '7x7', '9x9') shown " + "in a popup, with radio-button circles down the right-hand side and " + "exactly one circle selected?", + RESULTS_DIR, tag="position", depth=1, jump_kind="reach") + + +@and_test(expects=("nav_type_menu_back_closes",)) +def test_type_menu_back_closes(): + """Back-stack of the transient layer: BACK dismisses the Type-menu popup — the + radio list disappears and the game_view is showing again.""" + ok, gp = and_reach_gameplay("Net") + if not ok or not and_enter_type_menu(gp): + record("nav_type_menu_back_closes", False, + "setup_failed: could not open the Type menu to test BACK", + depth=1, jump_kind="reach", + expect="radio list gone and game_view showing after BACK") + return + before = and_showing() + open_ok = any("radiobutton" in k.lower() for k in before) + and_back() # dismiss popup + after = and_showing() + passed = (open_ok + and not any("radiobutton" in k.lower() for k in after) + and any("game_view" in k.lower() for k in after)) + record("nav_type_menu_back_closes", passed, + "" if passed else "behavior_wrong: BACK did not dismiss the Type-menu " + "popup back to the game_view", + depth=1, jump_kind="reach", + expect="RadioButton list gone and game_view present after one BACK") + + +@and_test(expects=("nav_game_menu_open",)) +def test_game_menu_open(): + """GamePlay -> tap Game: the action popup appears (its 'New game' + 'Settings' + items show up, which the plain game surface lacked).""" + ok, gp = and_reach_gameplay("Net") + if not ok: + record("nav_game_menu_open", False, + "setup_failed: could not reach GamePlay to open the Game menu", + depth=1, jump_kind="reach", + expect="Game-menu items ('New game'/'Settings') appear over the game") + return + before = and_showing(gp) + trig = find_node(gp, content_desc="Game") + tapped = bool(trig and tap_node(trig)) + if tapped: + and_enter("game_menu") + after = and_showing() + menu = ui() + appeared = and_reach(before, after, "TextView|New game") + has_items = bool(_find_menu_item(menu, "New game") + and _find_menu_item(menu, "Settings") + and _find_menu_item(menu, "Show solution")) + passed = tapped and appeared and has_items + record("nav_game_menu_open", passed, + "" if passed else "behavior_wrong: tapping Game did not open the action " + "popup (New game / Settings / Show solution items did not appear)", + depth=1, jump_kind="reach", + expect="'New game' + 'Settings' + 'Show solution' items appear over the game") + + +@and_test(expects=("nav_game_menu_back_closes",)) +def test_game_menu_back_closes(): + """Back-stack of the transient layer: BACK dismisses the Game-menu popup — the + 'New game' item disappears and the game_view is showing again.""" + ok, gp = and_reach_gameplay("Net") + if not ok or not and_enter_game_menu(gp): + record("nav_game_menu_back_closes", False, + "setup_failed: could not open the Game menu to test BACK", + depth=1, jump_kind="reach", + expect="menu items gone and game_view showing after BACK") + return + before = and_showing() + open_ok = any(k == "TextView|New game" for k in before) + and_back() # dismiss popup + after = and_showing() + passed = (open_ok + and not any(k == "TextView|New game" for k in after) + and any("game_view" in k.lower() for k in after)) + record("nav_game_menu_back_closes", passed, + "" if passed else "behavior_wrong: BACK did not dismiss the Game-menu " + "popup back to the game_view", + depth=1, jump_kind="reach", + expect="'New game' item gone and game_view present after one BACK") + + +@and_test(expects=("nav_custom_back_to_game",)) +def test_custom_back_to_game(): + """Back-stack: from the Custom config dialog, BACK dismisses it back to the + game — the ' configuration' title disappears and the game_view is + showing again.""" + ok, dlg = and_reach_custom_dialog("Net") + if not ok: + record("nav_custom_back_to_game", False, + "setup_failed: could not reach the Custom dialog to test BACK", + depth=2, jump_kind="reach", + expect="config dialog gone and game_view showing after BACK") + return + before = and_showing(dlg) + and_back() # dismiss the AlertDialog + after = and_showing() + passed = (any("net configuration" in k.lower() for k in before) + and not any("net configuration" in k.lower() for k in after) + and any("game_view" in k.lower() for k in after)) + record("nav_custom_back_to_game", passed, + "" if passed else "behavior_wrong: BACK from the Custom dialog did not " + "return to the game_view / dialog title still present", + depth=2, jump_kind="reach", + expect="'Net configuration' title gone and game_view present after BACK") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (4) Back-stack unwinding a multi-hop chain hop by hop +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_backstack_2hop_unwinds",)) +def test_backstack_2hop_unwinds(): + """A 2+ hop chain unwound hop by hop: chooser -> GamePlay -> Type menu -> + Custom… dialog, then BACK pops Custom… (back to the game surface), and BACK + again pops the game (back to the chooser table).""" + ok, dlg = and_reach_custom_dialog("Net") + if not ok: + record("nav_backstack_2hop_unwinds", False, + "setup_failed: could not build the chooser->game->type->Custom chain", + depth=2, jump_kind="reach", + expect="BACK unwinds Custom -> game -> chooser hop by hop") + return + dialog_showing = any("net configuration" in k.lower() for k in and_showing(dlg)) + # hop 1 back: leave the Custom dialog -> game_view restored, dialog title gone + and_back() + s1 = and_showing() + hop1 = (any("game_view" in k.lower() for k in s1) + and not any("net configuration" in k.lower() for k in s1)) + # hop 2 back: leave the game -> chooser table restored, game_view gone + and_back() + wait_for_foreground(5) + s2 = and_showing() + hop2 = (any("table" in k.lower() for k in s2) + and not any("game_view" in k.lower() for k in s2)) + passed = dialog_showing and hop1 and hop2 + record("nav_backstack_2hop_unwinds", passed, + "" if passed else "behavior_wrong: BACK did not unwind Custom -> game -> " + "chooser hop by hop (a surface popped out of order)", + depth=2, jump_kind="reach", + expect="BACK #1 -> game_view (config gone); BACK #2 -> chooser table " + "(game_view gone)") + + +@and_test(expects=("nav_backstack_deepest_to_home",)) +def test_backstack_deepest_to_home(): + """Deepest surface back to home: from the GAME ID… dialog (chooser -> game -> + Type -> Custom -> GAME ID), repeated BACK unwinds every layer until the chooser + table is showing again and the game_view is gone.""" + ok, gid = and_reach_gameid_dialog("Net") + if not ok: + record("nav_backstack_deepest_to_home", False, + "setup_failed: could not reach the GAME ID… dialog", + depth=3, jump_kind="reach", + expect="repeated BACK from GAME ID… ends at the chooser table") + return + deep_showing = any("net game selection" in k.lower() for k in and_showing(gid)) + # unwind: GAME ID -> Custom -> game -> chooser. Press BACK until home or a cap. + reached_home = False + for _ in range(5): + and_back() + wait_for_foreground(5) + cur = and_showing() + if (any("table" in k.lower() for k in cur) + and not any("game_view" in k.lower() for k in cur) + and not any("game selection" in k.lower() for k in cur)): + reached_home = True + break + passed = deep_showing and reached_home + record("nav_backstack_deepest_to_home", passed, + "" if passed else "behavior_wrong: repeated BACK from the deepest dialog " + "did not return to the chooser table", + depth=3, jump_kind="reach", + expect="chooser table present, game_view + 'game selection' gone after " + "unwinding every layer with BACK") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (5) Deep preferences sub-screen + puzzle switching + external picker +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_settings_subscreen",)) +def test_reach_settings_subscreen(): + """Deep chain (chooser -> Settings -> 'Display and input'): the sub-screen swaps + the settings surface for a deeper preferences page. Its 'Long-press timeout + (ms)' row appears and the top-level 'About this app' row disappears.""" + ok, prefs = and_reach_settings_from_chooser() + if not ok: + record("nav_reach_settings_subscreen", False, + "setup_failed: could not reach Settings to open a sub-screen", + depth=2, jump_kind="reach", + expect="'Display and input' sub-screen: Long-press timeout row " + "appears, top-level 'About this app' row gone") + return + row = scroll_into_view("Display and input", 6) + if not row: + record("nav_reach_settings_subscreen", False, + "feature_missing: no 'Display and input' category row in Settings", + depth=2, jump_kind="reach", + expect="'Display and input' sub-screen: Long-press timeout row " + "appears, top-level 'About this app' row gone") + return + before = and_showing() + tap_node(row) + settle("tap") + and_enter("Display and input") # deeper preferences surface + after = and_showing() + # target: a row unique to the sub-screen; source: a top-level-only row + reached = and_reach(before, after, "Long-press timeout", "About this app") + subrow_ok = bool(scroll_into_view("Long-press timeout (ms)", 3) + or find_node_ci(ui(), "Keyboard")) + passed = reached and subrow_ok + record("nav_reach_settings_subscreen", passed, + "" if passed else "behavior_wrong: 'Display and input' did not open a " + "deeper preferences surface (Long-press timeout row did not replace the " + "top-level About this app row)", + depth=3, jump_kind="reach", + expect="'Long-press timeout (ms)' row present; top-level 'About this " + "app' row no longer showing") + + +@and_test(expects=("nav_switch_puzzle_title",)) +def test_switch_puzzle_title(): + """Reach with the toolbar title as discriminator: open Net (title 'Net'), then + open Keen (via a fresh chooser round-trip) — the GamePlay title becomes 'Keen' + and 'Net' is no longer showing, proving we navigated to a different destination.""" + ok_net, _ = and_reach_gameplay("Net") + net_title = any(k == "TextView|Net" for k in and_showing()) if ok_net else False + if not ok_net or not net_title: + record("nav_switch_puzzle_title", False, + "setup_failed: could not open Net with its title showing", + depth=1, jump_kind="reach", + expect="toolbar title 'Keen' present, 'Net' gone after switching") + return + before = and_showing() + # and_reach_gameplay relaunches to the chooser and opens Keen next + ok_keen, _ = and_reach_gameplay("Keen") + after = and_showing() + reached = ok_keen and and_reach(before, after, "TextView|Keen", "TextView|Net") + passed = (ok_keen and reached + and any(k == "TextView|Keen" for k in after) + and not any(k == "TextView|Net" for k in after)) + record("nav_switch_puzzle_title", passed, + "" if passed else "behavior_wrong: opening Keen did not change the " + "GamePlay toolbar title from 'Net' to 'Keen'", + depth=1, jump_kind="reach", + expect="GamePlay title 'Keen' present and 'Net' gone after opening Keen") + + +@and_test(expects=("nav_reach_load_picker",)) +def test_reach_load_picker(): + """Chooser 'Load…' opens the EXTERNAL system file picker: the app package is no + longer the foreground activity (a different app is on top). BACK returns to the + chooser. Low-priority single reach — asserted via the resumed activity.""" + left_package, act = and_reach_file_picker() + if not act: + record("nav_reach_load_picker", False, + "feature_missing: chooser has no 'Load…' toolbar button (or it " + "was not foreground)", + depth=1, jump_kind="reach", + expect="foreground leaves the app package (system file picker) on Load…") + return + # return to our app immediately so we leave the device on a known surface + back() + wait_for_foreground(5) + back_home = PACKAGE in get_current_activity() + passed = left_package and back_home + record("nav_reach_load_picker", passed, + "" if passed else "behavior_wrong: 'Load…' did not open an external " + "activity outside the app package (or BACK did not return to the app)", + depth=1, jump_kind="reach", + expect="a non-app-package activity (system picker) is resumed on Load…; " + "BACK returns to the app") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (6) GamePlay toolbar affordance + return-home (VLM — rendered properties) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_gameplay_toolbar_back_vlm",)) +def test_gameplay_toolbar_back_arrow(): + """VLM-only: the GamePlay toolbar renders a left-pointing back/up arrow at the + top-left (the affordance that pops back to the chooser). It is an ImageButton + with content-desc 'Navigate up' in the tree, but the arrow SHAPE is drawn.""" + and_reach_gameplay("Net") + vlm_assert("nav_gameplay_toolbar_back", + "At the very top-left of the screen, is there a left-pointing arrow " + "(a back/up navigation arrow) in the toolbar?", + RESULTS_DIR, tag="shape", depth=1, jump_kind="reach") + + +@and_test(expects=("nav_back_to_chooser_list_vlm",)) +def test_back_to_chooser_list_shown(): + """VLM-only: after BACK from GamePlay, the chooser puzzle LIST is rendered + again (a vertical grid of rows), confirming the return to home.""" + ok, gp = and_reach_gameplay("Net") + if ok: + and_back() + wait_for_foreground(5) + vlm_assert("nav_back_to_chooser_list", + "Is a vertical list/grid of puzzle rows shown (each row a small icon " + "beside a line of text), rather than a single centered game board?", + RESULTS_DIR, tag="layout", depth=1, jump_kind="reach") + + +TESTS = [ + # top-level destinations + test_reach_gameplay, + test_gameplay_back_chooser, + test_reach_settings_chooser, + test_settings_back_chooser, + # depth>=2 chains + test_reach_settings_from_game, + test_reach_help, + test_help_back_chooser, + test_reach_custom_dialog, + test_reach_gameid_dialog, + # popup overlays + BACK closes + test_type_menu_open, + test_type_menu_back_closes, + test_game_menu_open, + test_game_menu_back_closes, + test_custom_back_to_game, + # back-stack unwinding multi-hop chains + test_backstack_2hop_unwinds, + test_backstack_deepest_to_home, + # deep prefs sub-screen + switching + external picker + test_reach_settings_subscreen, + test_switch_puzzle_title, + test_reach_load_picker, + # toolbar affordance / return-home (VLM-only) + test_gameplay_toolbar_back_arrow, + test_back_to_chooser_list_shown, +] + + +if __name__ == "__main__": + run_suite(TESTS, "navigation") diff --git a/android/chrisboyle-sgtpuzzles/tests/test_android_states.py b/android/chrisboyle-sgtpuzzles/tests/test_android_states.py new file mode 100644 index 0000000000000000000000000000000000000000..d01d9016c77f489b99effc5161c5d02214275d3c --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/tests/test_android_states.py @@ -0,0 +1,947 @@ +#!/usr/bin/env python3 +"""States lane — Simon Tatham's Puzzles (name.boyle.chris.sgtpuzzles). + +This lane owns WIDGET STATE through a before->after interaction, and is the SOLE +owner of CHECKED and FOCUSED. Every state transition is PAIRED with the +app-authored consequence that a dead shell (which flips the framework attribute +for free) cannot reproduce: + + A. Type-menu RADIO single-selection (checked flip) + RELOAD consequence + - Net: selecting a different size preset makes the NEW radio checked=true and + the OLD one checked=false, AND reloads the puzzle so the status_bar + denominator changes (5x5 -> "Active: N/25", 9x9 -> "Active: N/81"). VERIFIED + live. YOU own the CHECKED flip + the fact that selection moved which radio is + checked; the status VALUE itself is computation's — here it is only the + consequence that proves the flip did real work. + - Keen: 6x6 -> 4x4 flips the checked radio AND shrinks the on-screen digit + button set from {1..6} to {1..4}. VERIFIED live. + + B. Settings Switch toggles (checked flip) — the per-game switches live in the + GAME-context Settings (Game menu -> Settings), which shows a "" + category ("Highlight loops involving unlocked squares" ON, "Show arrow keys" + OFF) plus the "All games" switches ("Show reminders of controls" ON, "Match + game orientation to screen" ON). VERIFIED: tapping a switch ROW flips its + checked attr; every toggle is toggled BACK so defaults are restored. + + C. Settings persistence across PROCESS DEATH (this lane's specialty): flip a + switch, force_stop_and_relaunch(), reopen Settings, assert it is STILL flipped. + VERIFIED for "Show arrow keys" and "Highlight loops". + + D. "Show arrow keys" ON -> Up/Down/Left/Right buttons APPEAR in the game's + ButtonsView (settings -> UI page-level state machine). VERIFIED: absent when + OFF, present when ON, survives restart. depth 2 (settings reached from game). + + E. Custom-dialog CheckBox flip (Keen "Multiplication only" false->true). depth 2. + + F. Conditional enable/disable: on Net, Redo is enabled=false initially and flips + to enabled=true after an Undo (with the status_bar reverting off + "Auto-solved."). VERIFIED live (Undo itself stays enabled, so Redo is the + honest transition). + + G. Focus: the Custom dialog's Grid-size EditText goes focused=false -> true when + tapped. VERIFIED live. + +Ground state on entry (restored by this suite after every test): Net at 5x5, +"Show arrow keys" OFF, "Highlight loops" ON, "Show reminders" ON, "Match +orientation" ON, Keen at 6x6. +""" + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ══════════════════════════════════════════════════════════════════════════════ +# Local helpers — depth-family NAMES (and_enter_*/and_reach_*) back every declared +# depth>=1. Everything is package-agnostic (id LAST segment, content-desc, text) +# and derives coordinates from node bounds, never a literal. +# ══════════════════════════════════════════════════════════════════════════════ + +def _reach_chooser(): + """Land on GameChooser. The app is singleTask and RESUMES the last game on a + fresh launch, so pop GamePlay with BACK when we land there (recon-verified).""" + restart_app() + wait_for_foreground(10) + if "GamePlay" in get_current_activity(): + back() + wait_for_foreground(5) + return ui() + + +def _find_row(nodes, name): + """The chooser row TextView whose text is ': '.""" + for n in nodes: + if (n.get("resource-id", "").endswith("/text") + and n.get("text", "").startswith(name + ":")): + return n + return None + + +def _scroll_to_row(name, max_swipes=9): + row = _find_row(ui(), name) + for _ in range(max_swipes): + if row: + return row + scroll_down(0.5) + row = _find_row(ui(), name) + return row + + +def and_enter_game(name): + """Chooser -> tap puzzle row -> GamePlay. Counts one surface, so a + depth>=1 assertion made inside GamePlay is backed by a real navigation call. + Returns the GamePlay node tree, or [] if the row was never reachable.""" + _reach_chooser() + row = _scroll_to_row(name) + if not row or not safe_tap(row): + return [] + wait_for_foreground(5) + and_enter(name) + return ui() + + +def _menu_item(nodes, label): + """A popup/menu item TextView whose visible text equals `label`.""" + for n in nodes: + if "TextView" in n.get("class", "") and n.get("text", "") == label: + return n + return None + + +def and_enter_type_menu(gp): + """Open the GamePlay Type-menu popup. Counts one surface (a popup layer).""" + trig = find_node(gp, content_desc="Type") + if not trig or not tap_node(trig): + return False + and_enter("type_menu") + return True + + +def and_enter_game_menu(gp): + """Open the GamePlay Game-menu popup. Counts one surface (a popup layer).""" + trig = find_node(gp, content_desc="Game") + if not trig or not tap_node(trig): + return False + and_enter("game_menu") + return True + + +def and_enter_settings(gp): + """GamePlay -> Game menu -> 'Settings' -> PrefsActivity. Counts one surface for + the depth claim (the popup collapses into the activity). Returns the settings + node tree, or [] on failure. This is what backs the depth>=2 arrow-keys and + switch-persistence tests: game (surface 1) -> settings (surface 2).""" + if not and_enter_game_menu(gp): + return [] + setn = _menu_item(ui(), "Settings") + if not setn or not tap_node(setn): + return [] + wait_for_foreground(5) + and_enter("Settings") + return ui() + + +def and_enter_custom(gp, name): + """GamePlay -> Type menu -> 'Custom…' -> config AlertDialog. Counts one surface + (dialog) on top of the type-menu popup. Returns the dialog node tree, or [].""" + if not and_enter_type_menu(gp): + return [] + cust = None + for n in ui(): + if (n.get("resource-id", "").endswith("/title") + and n.get("text", "") == "Custom…"): + cust = n + break + if not cust or not tap_node(cust): + return [] + and_enter("custom_dialog") + return ui() + + +def _status_text(nodes=None): + nodes = ui() if nodes is None else nodes + n = node_by_id(nodes, "status_bar") + return n.get("text", "") if n else "" + + +def _radio_pairs(nodes): + """Zip the type-menu preset titles (id=title) with their RadioButtons + (id=radio) in document order. VERIFIED on device that title[i] and radio[i] + share the same row y, so the zip is the correct pairing.""" + titles = [n for n in nodes if n.get("resource-id", "").endswith("/title")] + radios = [n for n in nodes if n.get("resource-id", "").endswith("/radio")] + return list(zip(titles, radios)) + + +def _radio_for(nodes, label): + """(title_node, radio_node) for the preset whose title text == label.""" + for tn, rn in _radio_pairs(nodes): + if tn.get("text", "") == label: + return tn, rn + return None, None + + +def _checked_radio_label(nodes): + """The label of the currently-checked preset radio (or '' if none).""" + for tn, rn in _radio_pairs(nodes): + if rn.get("checked") == "true": + return tn.get("text", "") + return "" + + +def _switch_for_title(nodes, title_text): + """The Switch (id=switchWidget) sharing a row with the title TextView whose + text == title_text. VERIFIED: the switch and its title have the same row y, so + the nearest switchWidget by y is the right one (guarded to <80px).""" + tnode = None + for n in nodes: + if (n.get("resource-id", "").endswith("/title") + and n.get("text", "") == title_text): + tnode = n + break + if not tnode or "_center" not in tnode: + return None + ty = tnode["_center"][1] + best, bestd = None, 10 ** 9 + for n in nodes: + if n.get("resource-id", "").endswith("/switchWidget") and "_center" in n: + d = abs(n["_center"][1] - ty) + if d < bestd: + best, bestd = n, d + return best if bestd < 80 else None + + +def _switch_row_title(nodes, title_text): + """The title TextView node for a switch row (tapping it toggles the switch).""" + for n in nodes: + if (n.get("resource-id", "").endswith("/title") + and n.get("text", "") == title_text): + return n + return None + + +def _open_game_settings_scrolled(name, title_text, max_swipes=4): + """Reach the GAME-context Settings for and scroll 's switch + row into view. Returns (settings_nodes_with_row_visible, switch_node) or + ([], None). Backs depth via and_enter_game + and_enter_settings.""" + gp = and_enter_game(name) + if not gp: + return [], None + prefs = and_enter_settings(gp) + if not prefs: + return [], None + sw = _switch_for_title(prefs, title_text) + for _ in range(max_swipes): + if sw is not None: + return prefs, sw + scroll_down(0.4) + prefs = ui() + sw = _switch_for_title(prefs, title_text) + return (prefs, sw) if sw is not None else ([], None) + + +def _digit_button_set(nodes): + """The set of on-screen digit buttons (content-desc a single 1-9 digit).""" + return {n.get("content-desc") for n in nodes + if n.get("content-desc", "") in set("123456789")} + + +def _restore_net_5x5(): + """Leave Net at the 5x5 default (independent of what a test selected).""" + gp = and_enter_game("Net") + if not gp or not and_enter_type_menu(gp): + return + t5, r5 = _radio_for(ui(), "5x5") + if t5 and r5 and r5.get("checked") != "true": + tap_node(t5) + wait_for_foreground(5) + + +def _restore_switch_default(name, title_text, default_checked): + """Reopen the game Settings and set 's switch back to its default.""" + prefs, sw = _open_game_settings_scrolled(name, title_text) + if sw is None: + return + if sw.get("checked") != ("true" if default_checked else "false"): + row = _switch_row_title(ui(), title_text) + if row: + tap_node(row) + + +# ══════════════════════════════════════════════════════════════════════════════ +# (A) Type-menu RADIO single-selection (checked flip) + reload consequence +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_net_radio_select", "states_net_radio_dot_vlm", + "states_net_radio_gridsize_vlm")) +def test_net_radio_single_selection(): + """Net Type menu is a single-choice RADIO group. Select a DIFFERENT size than + the one currently checked: the NEW radio flips checked=true, the OLD flips to + checked=false, AND the puzzle reloads so the status_bar denominator changes to + the new grid's total (9x9 -> '/81'; then restored to 5x5 -> '/25'). A shell + that flips the radio for free but never reloads fails the '/81' consequence.""" + gp = and_enter_game("Net") + if not gp or not and_enter_type_menu(gp): + record("states_net_radio_select", False, + "setup_failed: could not open the Net Type menu", + depth=1, jump_kind="transition", + expect="9x9 radio checked true / prior radio false; status -> '/81'") + else: + tm = ui() + t9, r9 = _radio_for(tm, "9x9") + before_checked = _checked_radio_label(tm) # whatever is currently selected + if t9 is None or r9 is None or before_checked == "": + record("states_net_radio_select", False, + "feature_missing: Net Type menu has no radio presets / no 9x9", + depth=1, jump_kind="transition", + expect="9x9 radio checked true / prior radio false; status -> '/81'") + else: + was_9x9_before = r9.get("checked") == "true" + tap_node(t9) # select 9x9 + wait_for_foreground(5) + status_after = _status_text() # reload consequence + # reopen the type menu to read the radios back + and_enter_type_menu(ui()) + tm2 = ui() + t9b, r9b = _radio_for(tm2, "9x9") + new_checked = _checked_radio_label(tm2) + checked_ok = (r9b is not None and r9b.get("checked") == "true" + and new_checked == "9x9") + # exactly one selected changed: the old label is no longer the checked one + single_ok = (not was_9x9_before and before_checked != "9x9" + and new_checked != before_checked) + consequence_ok = status_after.endswith("/81") + ok = checked_ok and single_ok and consequence_ok + record("states_net_radio_select", ok, + "" if ok else f"behavior_wrong: radio select did not move the " + f"single checked radio to 9x9 with a reload (before={before_checked!r} " + f"after={new_checked!r} status={status_after!r})", + depth=1, jump_kind="transition", + expect="9x9 radio checked=true, prior preset now checked=false; " + "status_bar denominator -> '/81' (puzzle reloaded)") + # VLM #1 (shape): the selected preset's radio shows a FILLED dot while the + # others are empty circles — a rendered property beyond the boolean. + gp3 = and_enter_game("Net") + if gp3: + and_enter_type_menu(gp3) + vlm_assert("states_net_radio_dot", + "In this vertical list of size presets, does exactly ONE row have a " + "filled/solid radio-button dot on its right side while all the other " + "rows show empty (hollow) radio circles?", + RESULTS_DIR, tag="shape", depth=1, jump_kind="transition") + # VLM #2 (size): with 9x9 selected the grid is re-rendered noticeably denser + # (more, smaller cells) than the 5x5 default — the visual consequence of the + # state change on the canvas. + gp4 = and_enter_game("Net") + if gp4 and and_enter_type_menu(gp4): + t9c, _ = _radio_for(ui(), "9x9") + if t9c: + tap_node(t9c) + wait_for_foreground(5) + vlm_assert("states_net_radio_gridsize", + "Is the puzzle grid a fairly dense square grid of many small cells " + "(about 9 by 9), rather than a coarse grid of only a few large cells?", + RESULTS_DIR, tag="size", depth=1, jump_kind="transition") + _restore_net_5x5() + + +@and_test(expects=("states_net_radio_switch_back", "states_type_menu_selected_vlm")) +def test_net_radio_switch_back(): + """A second single-selection transition proving the group is truly single-choice + and reversible: from 5x5 (baseline) select 7x7 (new radio checked, 5x5 now + unchecked, status '/49'), then re-select 5x5 (5x5 checked again, 7x7 unchecked, + status '/25'). Both legs are read back from a reopened Type menu.""" + _restore_net_5x5() + gp = and_enter_game("Net") + if not gp or not and_enter_type_menu(gp): + record("states_net_radio_switch_back", False, + "setup_failed: could not open the Net Type menu", + depth=1, jump_kind="transition", + expect="5x5->7x7 (7x7 checked, 5x5 unchecked) then back (5x5 checked)") + else: + t7, _ = _radio_for(ui(), "7x7") + if t7 is None: + record("states_net_radio_switch_back", False, + "feature_missing: Net Type menu has no 7x7 preset", + depth=1, jump_kind="transition", + expect="5x5->7x7 (7x7 checked, 5x5 unchecked) then back (5x5 checked)") + else: + tap_node(t7) + wait_for_foreground(5) + s7 = _status_text() + and_enter_type_menu(ui()) + tm7 = ui() + _, r7_a = _radio_for(tm7, "7x7") + _, r5_a = _radio_for(tm7, "5x5") + leg1 = (r7_a is not None and r7_a.get("checked") == "true" + and r5_a is not None and r5_a.get("checked") == "false" + and s7.endswith("/49")) + # switch back to 5x5 + t5b, _ = _radio_for(tm7, "5x5") + tap_node(t5b) + wait_for_foreground(5) + s5 = _status_text() + and_enter_type_menu(ui()) + tm5 = ui() + _, r7_b = _radio_for(tm5, "7x7") + _, r5_b = _radio_for(tm5, "5x5") + leg2 = (r5_b is not None and r5_b.get("checked") == "true" + and r7_b is not None and r7_b.get("checked") == "false" + and s5.endswith("/25")) + ok = leg1 and leg2 + record("states_net_radio_switch_back", ok, + "" if ok else f"behavior_wrong: single-selection not reversible " + f"(leg1 7x7 status={s7!r}, leg2 5x5 status={s5!r})", + depth=1, jump_kind="transition", + expect="7x7 checked & 5x5 unchecked (status '/49'), then 5x5 " + "checked & 7x7 unchecked (status '/25')") + # VLM (position): the Type menu marks the currently-selected size — one row has + # its radio dot filled at the right edge, aligned with that size's label. + gp2 = and_enter_game("Net") + if gp2: + and_enter_type_menu(gp2) + vlm_assert("states_type_menu_selected", + "In this list of puzzle sizes, is the single selected size marked by " + "a filled radio dot positioned at the far RIGHT of its row (in line " + "with that size's text label)?", + RESULTS_DIR, tag="position", depth=1, jump_kind="transition") + _restore_net_5x5() + + +@and_test(expects=("states_keen_radio_select", "states_keen_radio_dot_vlm")) +def test_keen_radio_single_selection(): + """Keen Type menu single-selection with a NON-status consequence: switching from + the checked 6x6 preset to '4x4 Easy' flips the checked radio AND shrinks the + on-screen digit button set from {1..6} to {1..4} (the grid is smaller). VERIFIED + live. Restored to '6x6 Easy' afterwards.""" + gp = and_enter_game("Keen") + if not gp: + record("states_keen_radio_select", False, + "setup_failed: could not open Keen", + depth=1, jump_kind="transition", + expect="4x4 radio checked; digit buttons shrink {1..6}->{1..4}") + else: + digits_before = _digit_button_set(gp) + if not and_enter_type_menu(gp): + record("states_keen_radio_select", False, + "setup_failed: could not open the Keen Type menu", + depth=1, jump_kind="transition", + expect="4x4 radio checked; digit buttons shrink {1..6}->{1..4}") + else: + tm = ui() + before_checked = _checked_radio_label(tm) + t44, r44 = _radio_for(tm, "4x4 Easy") + if t44 is None: + record("states_keen_radio_select", False, + "feature_missing: Keen Type menu has no '4x4 Easy' preset", + depth=1, jump_kind="transition", + expect="4x4 radio checked; digit buttons shrink {1..6}->{1..4}") + else: + tap_node(t44) + wait_for_foreground(5) + digits_after = _digit_button_set(ui()) + and_enter_type_menu(ui()) + tm2 = ui() + _, r44b = _radio_for(tm2, "4x4 Easy") + new_checked = _checked_radio_label(tm2) + checked_ok = (r44b is not None and r44b.get("checked") == "true" + and new_checked == "4x4 Easy" + and new_checked != before_checked) + consequence_ok = (digits_before >= set("123456") + and digits_after == set("1234")) + ok = checked_ok and consequence_ok + record("states_keen_radio_select", ok, + "" if ok else f"behavior_wrong: 4x4 select did not flip the " + f"radio + shrink the digit set (before_checked={before_checked!r} " + f"new={new_checked!r} digits {sorted(digits_before)}->" + f"{sorted(digits_after)})", + depth=1, jump_kind="transition", + expect="'4x4 Easy' radio checked=true (prior unchecked); " + "on-screen digit buttons shrink from {1..6} to {1..4}") + # VLM (shape): the checked Keen preset shows a filled radio dot; others empty. + gp2 = and_enter_game("Keen") + if gp2: + and_enter_type_menu(gp2) + vlm_assert("states_keen_radio_dot", + "In this list of Keen difficulty presets, does exactly ONE row show a " + "filled/solid radio dot while the other rows show empty circles?", + RESULTS_DIR, tag="shape", depth=1, jump_kind="transition") + # restore Keen to 6x6 Easy + gp3 = and_enter_game("Keen") + if gp3 and and_enter_type_menu(gp3): + t66, _ = _radio_for(ui(), "6x6 Easy") + if t66: + tap_node(t66) + wait_for_foreground(5) + + +# ══════════════════════════════════════════════════════════════════════════════ +# (B) Settings Switch toggles (checked flip) — each of the four switches +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_switch_arrow_keys", "states_switch_arrow_on_vlm")) +def test_switch_arrow_keys_toggle(): + """The per-game 'Show arrow keys' Switch (default OFF). Tapping its row flips + checked false->true; toggled back to OFF to restore the default. depth=2 (game + -> Settings). The switch and its title share a row, so tapping the title toggles + it and the re-dumped switchWidget reports the new checked value.""" + prefs, sw = _open_game_settings_scrolled("Net", "Show arrow keys") + if sw is None: + record("states_switch_arrow_keys", False, + "feature_missing: no 'Show arrow keys' switch in Settings", + depth=2, jump_kind="transition", + expect="'Show arrow keys' checked false->true on tap") + else: + before = sw.get("checked") + row = _switch_row_title(prefs, "Show arrow keys") + tap_node(row) + after = (_switch_for_title(ui(), "Show arrow keys") or {}).get("checked") + ok = before == "false" and after == "true" + record("states_switch_arrow_keys", ok, + "" if ok else f"behavior_wrong: 'Show arrow keys' did not flip " + f"checked false->true (before={before} after={after})", + depth=2, jump_kind="transition", + expect="'Show arrow keys' switch checked false -> true after one tap") + # VLM (position): the switch now renders in the ON position (thumb pushed to + # the RIGHT) — captured with the switch ON. + vlm_assert("states_switch_arrow_on", + "For the 'Show arrow keys' row, is its toggle switch in the ON " + "position, with the round thumb slid to the RIGHT end of the " + "track?", + RESULTS_DIR, tag="position", depth=2, jump_kind="transition") + _restore_switch_default("Net", "Show arrow keys", default_checked=False) + + +@and_test(expects=("states_switch_highlight", "states_switch_highlight_off_vlm")) +def test_switch_highlight_loops_toggle(): + """The per-game 'Highlight loops involving unlocked squares' Switch (default ON). + Tapping its row flips checked true->false; toggled back ON to restore. depth=2. + The VLM half is captured with the switch OFF (thumb LEFT), the opposite rendered + position from the arrow-keys ON shot — so a shell that draws a fixed thumb fails + one of the two.""" + prefs, sw = _open_game_settings_scrolled("Net", + "Highlight loops involving unlocked squares") + if sw is None: + record("states_switch_highlight", False, + "feature_missing: no 'Highlight loops...' switch in Settings", + depth=2, jump_kind="transition", + expect="'Highlight loops' checked true->false on tap") + else: + before = sw.get("checked") + row = _switch_row_title(prefs, "Highlight loops involving unlocked squares") + tap_node(row) + after = (_switch_for_title( + ui(), "Highlight loops involving unlocked squares") or {}).get("checked") + ok = before == "true" and after == "false" + record("states_switch_highlight", ok, + "" if ok else f"behavior_wrong: 'Highlight loops' did not flip " + f"checked true->false (before={before} after={after})", + depth=2, jump_kind="transition", + expect="'Highlight loops' switch checked true -> false after one tap") + # VLM (position): the switch now renders OFF (thumb to the LEFT, grey track). + vlm_assert("states_switch_highlight_off", + "For the 'Highlight loops involving unlocked squares' row, is its " + "toggle switch in the OFF position, with the round thumb at the " + "LEFT end of a grey track?", + RESULTS_DIR, tag="position", depth=2, jump_kind="transition") + _restore_switch_default("Net", "Highlight loops involving unlocked squares", + default_checked=True) + + +@and_test(expects=("states_switch_reminders",)) +def test_switch_reminders_toggle(): + """The 'All games' 'Show reminders of controls' Switch (default ON). Tapping its + row flips checked true->false; toggled back ON. depth=2.""" + prefs, sw = _open_game_settings_scrolled("Net", "Show reminders of controls") + if sw is None: + record("states_switch_reminders", False, + "feature_missing: no 'Show reminders of controls' switch in Settings", + depth=2, jump_kind="transition", + expect="'Show reminders of controls' checked true->false on tap") + else: + before = sw.get("checked") + row = _switch_row_title(prefs, "Show reminders of controls") + tap_node(row) + after = (_switch_for_title(ui(), "Show reminders of controls") or {}).get("checked") + ok = before == "true" and after == "false" + record("states_switch_reminders", ok, + "" if ok else f"behavior_wrong: 'Show reminders of controls' did not " + f"flip checked true->false (before={before} after={after})", + depth=2, jump_kind="transition", + expect="'Show reminders of controls' switch checked true -> false") + _restore_switch_default("Net", "Show reminders of controls", default_checked=True) + + +@and_test(expects=("states_switch_orientation",)) +def test_switch_orientation_toggle(): + """The 'All games' 'Match game orientation to screen' Switch (default ON). + Tapping its row flips checked true->false; toggled back ON. depth=2.""" + prefs, sw = _open_game_settings_scrolled("Net", "Match game orientation to screen") + if sw is None: + record("states_switch_orientation", False, + "feature_missing: no 'Match game orientation to screen' switch", + depth=2, jump_kind="transition", + expect="'Match game orientation to screen' checked true->false on tap") + else: + before = sw.get("checked") + row = _switch_row_title(prefs, "Match game orientation to screen") + tap_node(row) + after = (_switch_for_title( + ui(), "Match game orientation to screen") or {}).get("checked") + ok = before == "true" and after == "false" + record("states_switch_orientation", ok, + "" if ok else f"behavior_wrong: 'Match game orientation to screen' " + f"did not flip checked true->false (before={before} after={after})", + depth=2, jump_kind="transition", + expect="'Match game orientation to screen' switch checked true -> false") + _restore_switch_default("Net", "Match game orientation to screen", + default_checked=True) + + +# ══════════════════════════════════════════════════════════════════════════════ +# (C) Settings persistence across PROCESS DEATH — this lane's specialty +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_arrow_keys_persists", "states_arrow_keys_persists_vlm")) +def test_arrow_keys_persists_process_death(): + """SETTINGS persistence: flip 'Show arrow keys' ON, force_stop_and_relaunch(), + reopen the game Settings, assert it is STILL checked=true. An in-memory-only + recreation loses the flag across the kill. depth=2 (Settings reached from game). + Toggled back OFF at the end to restore the default.""" + prefs, sw = _open_game_settings_scrolled("Net", "Show arrow keys") + if sw is None: + record("states_arrow_keys_persists", False, + "feature_missing: no 'Show arrow keys' switch to persist", + depth=2, jump_kind="value", + expect="'Show arrow keys' still checked=true after force-stop+relaunch") + else: + if sw.get("checked") == "false": + tap_node(_switch_row_title(prefs, "Show arrow keys")) + flipped = (_switch_for_title(ui(), "Show arrow keys") or {}).get("checked") == "true" + # kill the process and relaunch, then reopen the game Settings + force_stop_and_relaunch() + wait_for_foreground(10) + prefs2, sw2 = _open_game_settings_scrolled("Net", "Show arrow keys") + persisted = sw2 is not None and sw2.get("checked") == "true" + ok = flipped and persisted + record("states_arrow_keys_persists", ok, + "" if ok else "behavior_wrong: 'Show arrow keys' did not survive " + "force-stop + relaunch (not checked=true after process death)", + depth=2, jump_kind="value", + expect="'Show arrow keys' checked=true after the flip AND still " + "checked=true after force-stop + relaunch") + # VLM (position): after the relaunch the switch is still drawn ON (thumb RIGHT). + vlm_assert("states_arrow_keys_persists", + "For the 'Show arrow keys' row, is its toggle switch in the ON " + "position (thumb slid to the RIGHT) after the app was restarted?", + RESULTS_DIR, tag="position", depth=2, jump_kind="value") + _restore_switch_default("Net", "Show arrow keys", default_checked=False) + + +@and_test(expects=("states_highlight_persists",)) +def test_highlight_persists_process_death(): + """A SECOND settings-persistence probe on a different switch and the OPPOSITE + direction: flip 'Highlight loops' OFF (from its ON default), + force_stop_and_relaunch(), reopen Settings, assert it is STILL checked=false. + depth=2. Toggled back ON at the end.""" + prefs, sw = _open_game_settings_scrolled("Net", + "Highlight loops involving unlocked squares") + if sw is None: + record("states_highlight_persists", False, + "feature_missing: no 'Highlight loops...' switch to persist", + depth=2, jump_kind="value", + expect="'Highlight loops' still checked=false after force-stop+relaunch") + else: + if sw.get("checked") == "true": + tap_node(_switch_row_title(prefs, + "Highlight loops involving unlocked squares")) + flipped = (_switch_for_title( + ui(), "Highlight loops involving unlocked squares") or {}).get("checked") == "false" + force_stop_and_relaunch() + wait_for_foreground(10) + prefs2, sw2 = _open_game_settings_scrolled( + "Net", "Highlight loops involving unlocked squares") + persisted = sw2 is not None and sw2.get("checked") == "false" + ok = flipped and persisted + record("states_highlight_persists", ok, + "" if ok else "behavior_wrong: 'Highlight loops' OFF did not survive " + "force-stop + relaunch (not checked=false after process death)", + depth=2, jump_kind="value", + expect="'Highlight loops' checked=false after the flip AND still " + "checked=false after force-stop + relaunch") + _restore_switch_default("Net", "Highlight loops involving unlocked squares", + default_checked=True) + + +# ══════════════════════════════════════════════════════════════════════════════ +# (D) "Show arrow keys" -> arrow buttons appear/disappear (page-level state machine) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_arrow_keys_consequence", "states_arrow_icons_on_vlm", + "states_arrow_icons_off_vlm")) +def test_arrow_keys_ui_consequence(): + """A multi-surface page-level state machine: setting state -> game UI state. + With 'Show arrow keys' OFF the game's ButtonsView has NO Up/Down/Left/Right + buttons; enabling the setting and returning to the game makes all four APPEAR + (VERIFIED, plus A/D/F/S). Assert absent-before -> present-after, then restore + the setting so the four buttons disappear again. depth=2 (game -> Settings).""" + gp = and_enter_game("Net") + if not gp: + record("states_arrow_keys_consequence", False, + "setup_failed: could not open Net to check arrow buttons", + depth=2, jump_kind="transition", + expect="Up/Down/Left/Right buttons absent OFF -> present after enabling") + else: + dirs = ("Up", "Down", "Left", "Right") + present_before = all(find_node(gp, content_desc=d) for d in dirs) + # enable the setting via game Settings + prefs = and_enter_settings(gp) + sw = _switch_for_title(prefs, "Show arrow keys") if prefs else None + for _ in range(4): + if sw is not None: + break + scroll_down(0.4) + prefs = ui() + sw = _switch_for_title(prefs, "Show arrow keys") + if sw is None: + record("states_arrow_keys_consequence", False, + "feature_missing: no 'Show arrow keys' switch to enable", + depth=2, jump_kind="transition", + expect="Up/Down/Left/Right absent OFF -> present after enabling") + else: + if sw.get("checked") == "false": + tap_node(_switch_row_title(ui(), "Show arrow keys")) + # back to the game and look for the four directional buttons + back() + wait_for_foreground(5) + g2 = ui() + present_after = all(find_node(g2, content_desc=d) for d in dirs) + ok = (not present_before) and present_after + record("states_arrow_keys_consequence", ok, + "" if ok else f"behavior_wrong: enabling 'Show arrow keys' did not " + f"add Up/Down/Left/Right to the game (before_present={present_before} " + f"after_present={present_after})", + depth=2, jump_kind="transition", + expect="Up/Down/Left/Right buttons ABSENT with setting OFF, PRESENT " + "in the game's button bar after enabling the setting") + # VLM #1 (shape): with the setting ON the game's bottom button bar renders four + # directional ARROW icons (up/down/left/right) — canvas-drawn glyphs. + vlm_assert("states_arrow_icons_on", + "In the row of control buttons at the bottom of the screen, are there " + "four directional ARROW buttons (pointing up, down, left and right)?", + RESULTS_DIR, tag="shape", depth=2, jump_kind="transition") + # restore the setting OFF, then capture the OFF state for VLM #2 + _restore_switch_default("Net", "Show arrow keys", default_checked=False) + and_enter_game("Net") + # VLM #2 (content): with the setting OFF, NO directional arrow buttons are shown. + vlm_assert("states_arrow_icons_off", + "In the row of control buttons at the bottom of the screen, are there " + "NO directional arrow buttons (no up/down/left/right arrows shown)?", + RESULTS_DIR, tag="content", depth=2, jump_kind="transition") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (E) Custom-dialog CheckBox flip +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_custom_checkbox", "states_custom_checkbox_vlm")) +def test_custom_dialog_checkbox(): + """Keen's Custom… configuration dialog has a CheckBox 'Multiplication only' + (default unchecked). Tapping it flips checked false->true. depth=2 (game -> + Type menu -> Custom dialog). Dismissed with BACK afterwards (no OK, so no + game reload / no residue).""" + gp = and_enter_game("Keen") + if not gp: + record("states_custom_checkbox", False, + "setup_failed: could not open Keen for the Custom dialog", + depth=2, jump_kind="transition", + expect="'Multiplication only' checkbox checked false->true on tap") + else: + dlg = and_enter_custom(gp, "Keen") + cb = find_by_class(dlg, "CheckBox") if dlg else [] + if not cb: + record("states_custom_checkbox", False, + "feature_missing: Keen Custom dialog has no CheckBox", + depth=2, jump_kind="transition", + expect="'Multiplication only' checkbox checked false->true on tap") + else: + target = cb[0] + before = target.get("checked") + tap_node(target) + after_node = find_closest_match(ui(), target) + after = (after_node or {}).get("checked") + ok = before == "false" and after == "true" + record("states_custom_checkbox", ok, + "" if ok else f"behavior_wrong: the Custom-dialog checkbox did not " + f"flip checked false->true (before={before} after={after})", + depth=2, jump_kind="transition", + expect="'Multiplication only' checkbox checked false -> true on tap") + # VLM (shape): the checkbox now renders with a tick/check mark inside it. + vlm_assert("states_custom_checkbox", + "In this configuration dialog, does the checkbox next to the " + "'Multiplication only' label now show a tick/check mark inside " + "it (a checked box), rather than an empty square?", + RESULTS_DIR, tag="shape", depth=2, jump_kind="transition") + back() # dismiss the dialog (Cancel-equivalent; no OK so nothing is applied) + + +# ══════════════════════════════════════════════════════════════════════════════ +# (F) Conditional enable/disable — Redo enabled=false -> true after an Undo +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_redo_enable_after_undo", "states_redo_enabled_vlm")) +def test_redo_enables_after_undo(): + """A conditional-enable state machine on Net's Redo button. On a FRESH game Redo + is enabled=false (nothing to redo). After Show solution then Undo, Redo flips to + enabled=true (there is now a redoable step) and the status_bar reverts off + 'Auto-solved.' to an 'Active: N/T' form. VERIFIED live. depth=1 (assertion made + on the GamePlay surface reached by navigation).""" + gp = and_enter_game("Net") + if not gp: + record("states_redo_enable_after_undo", False, + "setup_failed: could not open Net to test Redo enablement", + depth=1, jump_kind="transition", + expect="Redo enabled false->true after Undo; status leaves 'Auto-solved.'") + else: + # fresh game so the state is reproducible + if and_enter_game_menu(gp): + ng = _menu_item(ui(), "New game") + if ng: + tap_node(ng) + wait_for_foreground(5) + g1 = ui() + redo1 = find_node(g1, content_desc="Redo") + redo_before = redo1.get("enabled") if redo1 else None + # Show solution -> Auto-solved. + gp1 = ui() + solved = "" + if and_enter_game_menu(gp1): + ss = _menu_item(ui(), "Show solution") + if ss: + tap_node(ss) + wait_for_foreground(5) + solved = _status_text() + # Undo -> Redo becomes enabled, status leaves Auto-solved. + undo = find_node(ui(), content_desc="Undo") + tapped_undo = bool(undo and tap_node(undo)) + g2 = ui() + redo2 = find_node(g2, content_desc="Redo") + redo_after = redo2.get("enabled") if redo2 else None + status_after = _status_text(g2) + ok = (redo_before == "false" and tapped_undo and redo_after == "true" + and solved.strip() == "Auto-solved." + and status_after.strip() != "Auto-solved." + and status_after.startswith("Active:")) + record("states_redo_enable_after_undo", ok, + "" if ok else f"behavior_wrong: Redo did not flip enabled false->true " + f"after Undo, or the status did not revert (redo {redo_before}->" + f"{redo_after}, solved={solved!r} afterUndo={status_after!r})", + depth=1, jump_kind="transition", + expect="Redo enabled=false on a fresh game -> enabled=true after " + "Undo; status_bar reverts from 'Auto-solved.' to 'Active: N/T'") + # VLM (shape): the bottom control bar renders the Undo/Redo pair as two curved + # arrow icons — one curving LEFT (undo) and one curving RIGHT (redo). A shell + # that never draws the game toolbar icons lacks this rendered shape. (The + # enabled/disabled BRIGHTNESS of the Redo icon is not visually discriminable on + # this app, so the enablement itself is asserted on the rule track above; this + # VLM half tests the rendered arrow SHAPES that pair with it.) + vlm_assert("states_redo_enabled", + "In the row of controls at the very bottom of the screen, are there " + "two curved 'undo/redo' arrow icons \u2014 one arrow curving to the " + "LEFT and one curving to the RIGHT?", + RESULTS_DIR, tag="shape", depth=1, jump_kind="transition") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (G) Focus — the Custom dialog's Grid-size EditText focused=false -> true on tap +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_editext_focus",)) +def test_custom_editext_focus(): + """FOCUS transition (this lane owns focus): the Keen Custom dialog's Grid-size + EditText reports focused=false before it is tapped and focused=true after. + VERIFIED live. depth=2 (game -> Type menu -> Custom dialog). Dismissed with + BACK afterwards.""" + gp = and_enter_game("Keen") + if not gp: + record("states_editext_focus", False, + "setup_failed: could not open Keen for the Custom dialog", + depth=2, jump_kind="transition", + expect="Grid-size EditText focused false->true on tap") + else: + dlg = and_enter_custom(gp, "Keen") + ets = find_by_class(dlg, "EditText") if dlg else [] + if not ets: + record("states_editext_focus", False, + "feature_missing: Keen Custom dialog has no EditText", + depth=2, jump_kind="transition", + expect="Grid-size EditText focused false->true on tap") + else: + et = ets[0] + before = et.get("focused") + tap_node(et) + after_node = find_closest_match(ui(), et) + after = (after_node or {}).get("focused") + ok = before == "false" and after == "true" + record("states_editext_focus", ok, + "" if ok else f"behavior_wrong: the Grid-size EditText did not take " + f"focus on tap (focused {before}->{after})", + depth=2, jump_kind="transition", + expect="Grid-size EditText focused=false before tap, focused=true " + "after tap") + hide_keyboard() + back() # dismiss the dialog + + +# ══════════════════════════════════════════════════════════════════════════════ +# (H) Settings list rendering — multiple switches in mixed ON/OFF states (VLM) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_settings_mixed_switches_vlm",)) +def test_settings_mixed_switches_render(): + """VLM-only (color): the game Settings list shows several toggle switches at + once, some ON (coloured track, thumb right) and some OFF (grey, thumb left) — + with 'Highlight loops' / 'Show reminders' / 'Match orientation' ON and 'Show + arrow keys' OFF by default. A shell that renders every switch identically fails + this simultaneous-mix question. depth=2 (Settings reached from the game).""" + gp = and_enter_game("Net") + if gp: + and_enter_settings(gp) + vlm_assert("states_settings_mixed_switches", + "In this settings list, are MULTIPLE toggle switches visible at the " + "same time, with at least one switch clearly ON (coloured track, " + "thumb on the right) AND at least one clearly OFF (grey track, thumb " + "on the left)?", + RESULTS_DIR, tag="color", depth=2, jump_kind="transition") + + +TESTS = [ + # (A) type-menu radio single-selection + reload/consequence + test_net_radio_single_selection, + test_net_radio_switch_back, + test_keen_radio_single_selection, + # (B) settings switch toggles (each of the four) + test_switch_arrow_keys_toggle, + test_switch_highlight_loops_toggle, + test_switch_reminders_toggle, + test_switch_orientation_toggle, + # (C) settings persistence across process death (specialty) + test_arrow_keys_persists_process_death, + test_highlight_persists_process_death, + # (D) settings -> game UI page-level state machine + test_arrow_keys_ui_consequence, + # (E) custom-dialog checkbox flip + test_custom_dialog_checkbox, + # (F) conditional enable/disable + test_redo_enables_after_undo, + # (G) focus + test_custom_editext_focus, + # (H) settings rendering (VLM-only) + test_settings_mixed_switches_render, +] + + +if __name__ == "__main__": + run_suite(TESTS, "states") diff --git a/android/chrisboyle-sgtpuzzles/tests/test_android_structure.py b/android/chrisboyle-sgtpuzzles/tests/test_android_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..e8c36f0fab08b9d5435666b62a0258df680390e6 --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/tests/test_android_structure.py @@ -0,0 +1,463 @@ +#!/usr/bin/env python3 +"""Structure lane — Simon Tatham's Puzzles (name.boyle.chris.sgtpuzzles). + +This lane owns exactly two things: + 1. THE GATE — the app launches, is in the foreground, and its top-level + chooser surface (toolbar nav host + puzzle table + section headers) exists. + jump_kind="none", kept <=30% of the suite. + 2. TREE-SHAPE DELTAS — an interaction that changes the tree's SHAPE: a menu that + adds a class of widget, a dialog that adds a new window layer, a per-puzzle + control mode that adds a class of button. Recorded as jump_kind="transition", + with the delta OBSERVED on the original and REVERSED to assert it restores. + +Every canvas/rendered fact (the puzzle grid, digits, colors) is NOT in the view +tree, so it is checked on the VLM track. Everything readable from the dump stays a +rule assertion. + +Ground truth (all OBSERVED on the running original during recon): + - GameChooser (LAUNCHER): toolbar (nav host, content-desc Settings/Load../Help), + title TextView "Puzzles", scrollView>table (GridLayout), section headers + games_starred "Starred (long press to toggle)" + games_others "Others". Each + row = an icon thumbnail (ImageView) to the LEFT of a text TextView. + - GamePlay (singleTask, RESUMES last game): toolbar (Navigate up + Game/Type/Help), + mainLayout>game_view (Canvas), status_bar (Net), buttons (ButtonsView). + * Net type menu -> 9 RadioButtons (0->9->0 on close). + * Net game menu -> 7 TextView items (2->7->2 on close; the background title + + status text drop out of the tree while the popup is up). + * Net has no digit keypad; Keen adds 6 digit keys (android.view.View with + content-desc "1".."6"). + * Keen Custom... -> AlertDialog "Keen configuration": 1 EditText + 1 CheckBox + + 1 Spinner, buttons button1/2/3; closes back to 0 EditText/CheckBox. + - PrefsActivity (Settings): recycler_view populated with >=2 Switch (switchWidget). +""" + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ── Local navigation helpers (named in the depth family so depth>=1 is backed) ── + +def _reach_chooser(): + """Land on GameChooser. The app is singleTask and RESUMES the last game on a + fresh launch, so pop GamePlay with BACK when we land there (recon-verified).""" + restart_app() + wait_for_foreground(10) + if "GamePlay" in get_current_activity(): + back() + wait_for_foreground(5) + return ui() + + +def _find_puzzle_row(nodes, name): + """The chooser row whose text is ': '.""" + for n in nodes: + if (n.get("resource-id", "").endswith("/text") + and n.get("text", "").startswith(name + ":")): + return n + return None + + +def and_enter_puzzle(name): + """Open puzzle from the chooser -> GamePlay. Counts one surface, so a + depth>=1 shape delta seen inside GamePlay is backed by a real navigation call. + Returns the GamePlay node tree, or [] if the row was never reachable.""" + nodes = _reach_chooser() + row = _find_puzzle_row(nodes, name) + for _ in range(7): + if row: + break + scroll_down(0.5) + row = _find_puzzle_row(ui(), name) + if not row or not safe_tap(row): + return [] + wait_for_foreground(5) + and_enter(name) + return ui() + + +def and_enter_settings_from_chooser(): + """Chooser toolbar 'Settings' -> PrefsActivity. Counts one surface.""" + nodes = _reach_chooser() + st = find_node(nodes, content_desc="Settings") + if not st or not tap_node(st): + return [] + wait_for_foreground(5) + and_enter("Settings") + return ui() + + +def _digit_button_count(nodes): + """Count the digit-keypad controls: nodes whose content-desc is a single digit + 1-9. On this app they are android.view.View (not Button), the digit carried as + content-desc with an empty text; the child TextView carries text (not a desc), + so keying on content-desc counts each key exactly once. Net has none; Keen 6.""" + out = 0 + for n in nodes: + d = n.get("content-desc", "") + if len(d) == 1 and d.isdigit(): + out += 1 + return out + + +# ══════════════════════════════════════════════════════════════════════════════ +# (1) THE GATE — jump_kind="none", depth 0 (kept <=30% of the suite) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_gate_launch", "structure_gate_launch_vlm")) +def test_gate_launch(): + """App launches, reaches foreground, and the chooser's top-level container + + nav host (toolbar) exist — by class + content-desc, not by internal id.""" + nodes = _reach_chooser() + fg = wait_for_foreground(5) + toolbar = node_by_id(nodes, "toolbar") + # nav host proven by its content-desc buttons, not its raw id + nav_ok = bool(find_node(nodes, content_desc="Settings") + and find_node(nodes, content_desc="Help")) + container_ok = bool(find_by_class(nodes, "ViewGroup") + or find_by_class(nodes, "FrameLayout")) + ok = fg and bool(toolbar) and nav_ok and container_ok + record("structure_gate_launch", ok, + "" if ok else "setup_failed: chooser did not reach the foreground with " + "a toolbar nav host (Settings/Help) and a top-level container", + depth=0, jump_kind="none") + # Rendered position: every puzzle row has a small square icon thumbnail to the + # LEFT of its descriptive text (canvas art, not in the tree). + vlm_assert("structure_gate_launch", + "Is this a vertical list of entries where each row shows a small " + "square icon/thumbnail on the LEFT and a block of descriptive text " + "to its RIGHT?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("structure_chooser_sections", "structure_chooser_sections_vlm")) +def test_chooser_sections(): + """The chooser shows its two section headers + the scrollable puzzle table — + the discriminating shape of the launch surface.""" + nodes = _reach_chooser() + starred = node_by_id(nodes, "games_starred") + others = node_by_id(nodes, "games_others") + table = node_by_id(nodes, "table") + scroller = node_by_id(nodes, "scrollView") + title = bool(find_node_ci(nodes, "Puzzles")) + # header text is content, matched case-insensitively (a faithful recreation + # may differ on casing/punctuation of the parenthetical) + starred_txt = bool(starred and "starred" in starred.get("text", "").lower()) + others_txt = bool(others and others.get("text", "").lower().startswith("other")) + ok = bool(starred and others and table and scroller and title + and starred_txt and others_txt) + record("structure_chooser_sections", ok, + "" if ok else "feature_missing: chooser lacks the Starred/Others section " + "headers over a scrollable puzzle table", + depth=0, jump_kind="none") + # Rendered position: Starred heading sits ABOVE the Others heading. + vlm_assert("structure_chooser_sections", + "Are there two section headings, one reading 'Starred' and one " + "reading 'Others', with the 'Starred' heading positioned ABOVE the " + "'Others' heading?", + RESULTS_DIR, tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (2) TREE-SHAPE DELTAS — jump_kind="transition", observed delta + reverse +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_gameplay_surface", "structure_gameplay_surface_vlm")) +def test_gameplay_surface_shape(): + """Opening a puzzle swaps the chooser surface for GamePlay's shape: the + game_view canvas, the status_bar, and the ButtonsView all appear. Reversed by + BACK, which restores the chooser table.""" + before = and_showing(_reach_chooser()) + gp = and_enter_puzzle("Net") + if not gp: + record("structure_gameplay_surface", False, + "setup_failed: could not open the Net puzzle from the chooser", + depth=1, jump_kind="transition", + expect="chooser table -> GamePlay(game_view+status_bar+buttons)") + else: + after = and_showing(gp) + game_view = node_by_id(gp, "game_view") + status_bar = node_by_id(gp, "status_bar") + buttons = node_by_id(gp, "buttons") + up = find_node(gp, content_desc="Navigate up") + appeared = bool(game_view and status_bar and buttons and up) + changed = surface_changed(before, after) + # reverse: BACK to the chooser restores the table + section headers + and_back() + chooser2 = ui() + restored = bool(node_by_id(chooser2, "table") + and node_by_id(chooser2, "games_starred")) + ok = appeared and changed and restored + record("structure_gameplay_surface", ok, + "" if ok else ("behavior_wrong: GamePlay surface missing " + "game_view/status_bar/buttons or chooser did not " + "restore on BACK"), + depth=1, jump_kind="transition", + expect="chooser table -> GamePlay adds game_view+status_bar+buttons; " + "BACK restores the chooser table") + # Rendered shape: Net draws a square grid outlined by a red border, centered. + and_enter_puzzle("Net") + vlm_assert("structure_gameplay_surface", + "Is there a single square puzzle grid outlined by a RED border, " + "occupying the center of the screen?", + RESULTS_DIR, tag="shape", depth=1, jump_kind="transition") + + +@and_test(expects=("structure_gameplay_toolbar",)) +def test_gameplay_toolbar_shape(): + """GamePlay's toolbar host carries the up-affordance plus the three action + controls (Game/Type/Help) — the chrome shape that frames every puzzle.""" + gp = and_enter_puzzle("Net") + if not gp: + record("structure_gameplay_toolbar", False, + "setup_failed: could not open a puzzle to inspect its toolbar", + depth=1, jump_kind="transition", + expect="GamePlay toolbar hosts Navigate up + Game + Type + Help") + else: + up = find_node(gp, content_desc="Navigate up") + game = find_node(gp, content_desc="Game") + typ = find_node(gp, content_desc="Type") + helpb = find_node(gp, content_desc="Help") + toolbar = node_by_id(gp, "toolbar") + ok = bool(up and game and typ and helpb and toolbar) + record("structure_gameplay_toolbar", ok, + "" if ok else "feature_missing: GamePlay toolbar lacks Navigate up / " + "Game / Type / Help controls", + depth=1, jump_kind="transition", + expect="GamePlay adds a toolbar with Navigate up + 3 action buttons " + "(Game/Type/Help)") + # Toolbar chrome is fully rule-readable via content-descs above, so no VLM + # question is spent here (this lane's VLM budget is 8). + + +@and_test(expects=("structure_type_menu_shape", "structure_type_menu_shape_vlm")) +def test_type_menu_shape(): + """Opening Net's Type menu adds a radio group to the tree: 0 RadioButtons + before, 9 while open, 0 again after closing (recon-verified 0->9->0).""" + gp = and_enter_puzzle("Net") + if not gp: + record("structure_type_menu_shape", False, + "setup_failed: could not open a puzzle to reach its Type menu", + depth=1, jump_kind="transition", + expect="RadioButton count 0->9->0 opening/closing the Type menu") + else: + before = len(find_by_class(gp, "RadioButton")) + opened = tap_node(find_node(gp, content_desc="Type")) + menu = ui() + during = len(find_by_class(menu, "RadioButton")) + radio_titles = [n.get("text") for n in menu + if n.get("resource-id", "").endswith("/title") + and n.get("text")] + has_5x5 = "5x5" in radio_titles + back() + after = len(find_by_class(ui(), "RadioButton")) + ok = bool(opened and before == 0 and during == 9 and after == 0 and has_5x5) + record("structure_type_menu_shape", ok, + "" if ok else (f"behavior_wrong: Type-menu radio group shape " + f"{before}->{during}->{after} (expected 0->9->0)"), + depth=1, jump_kind="transition", + expect="RadioButton count 0->9->0 on Type menu open/close; items " + "include 5x5") + # Rendered shape: a vertical list of radio circles, exactly one filled/selected. + gp2 = and_enter_puzzle("Net") + tap_node(find_node(gp2, content_desc="Type")) + vlm_assert("structure_type_menu_shape", + "Is a vertical list of radio-button options shown where exactly ONE " + "circle is filled/selected and the rest are empty circles?", + RESULTS_DIR, tag="shape", depth=1, jump_kind="transition") + + +@and_test(expects=("structure_game_menu_shape", "structure_game_menu_shape_vlm")) +def test_game_menu_shape(): + """Opening Net's Game menu adds a 7-item popup to the tree: its 7 menu-item + TextViews (New game/Restart/Show solution/Load/Save/Share/Settings) appear, + and the text count restores to its pre-open value when the menu is dismissed + (recon-verified 2->7->2 — the background title/status text drop out while the + popup is up).""" + gp = and_enter_puzzle("Net") + if not gp: + record("structure_game_menu_shape", False, + "setup_failed: could not open a puzzle to reach its Game menu", + depth=1, jump_kind="transition", + expect="7 Game-menu item TextViews appear, text count restores on close") + else: + before = len(find_by_class(gp, "TextView")) + opened = tap_node(find_node(gp, content_desc="Game")) + menu = ui() + during = len(find_by_class(menu, "TextView")) + items = [n.get("text") for n in menu + if "TextView" in n.get("class", "") and n.get("text")] + expected_items = ["New game", "Restart", "Show solution", "Load…", + "Save…", "Share…", "Settings"] + has_all = all(it in items for it in expected_items) + back() + after = len(find_by_class(ui(), "TextView")) + ok = bool(opened and during == 7 and has_all and after == before) + record("structure_game_menu_shape", ok, + "" if ok else (f"behavior_wrong: Game-menu text-item shape " + f"{before}->{during}->{after} (expected 7 items while " + f"open, restore to {before})"), + depth=1, jump_kind="transition", + expect="Game menu adds 7 item TextViews (New game/Restart/Show " + "solution/Load/Save/Share/Settings); text count restores on " + "close") + # Rendered position: each menu row has an icon to the LEFT of its text label. + gp2 = and_enter_puzzle("Net") + tap_node(find_node(gp2, content_desc="Game")) + vlm_assert("structure_game_menu_shape", + "Is a popup menu shown as a vertical list of items where each item " + "has a small icon positioned to the LEFT of its text label?", + RESULTS_DIR, tag="position", depth=1, jump_kind="transition") + + +@and_test(expects=("structure_keen_digit_buttons", "structure_keen_digit_buttons_vlm")) +def test_keen_digit_buttons_shape(): + """A per-puzzle control-mode shape delta: Net's ButtonsView has NO digit + keypad; Keen adds 6 digit keys with content-desc 1..6. Reversed by opening Net + again and confirming the digit keys are gone (0 -> 6 -> 0).""" + net = and_enter_puzzle("Net") + net_digits = _digit_button_count(net) if net else -1 + keen = and_enter_puzzle("Keen") + keen_digits = _digit_button_count(keen) if keen else -1 + keen_1_6 = bool(keen and all(find_node(keen, content_desc=str(d)) + for d in range(1, 7))) + # reverse: back to Net -> digit keypad disappears again + net2 = and_enter_puzzle("Net") + net2_digits = _digit_button_count(net2) if net2 else -1 + ok = (net_digits == 0 and keen_digits == 6 and keen_1_6 + and net2_digits == 0) + record("structure_keen_digit_buttons", ok, + "" if ok else (f"behavior_wrong: digit-key shape Net={net_digits} " + f"Keen={keen_digits} Net_again={net2_digits} " + f"(expected 0->6->0)"), + depth=1, jump_kind="transition", + expect="digit-keypad keys (content-desc 1..6): 0 on Net -> 6 on Keen " + "-> 0 back on Net") + # Rendered layout: Keen's bottom bar shows the digit keys 1 through 6 in a row. + and_enter_puzzle("Keen") + vlm_assert("structure_keen_digit_buttons", + "Along the bottom of the screen, is there a horizontal row of number " + "buttons showing the digits 1, 2, 3, 4, 5 and 6?", + RESULTS_DIR, tag="layout", depth=1, jump_kind="transition") + + +@and_test(expects=("structure_custom_dialog_shape", "structure_custom_dialog_shape_vlm")) +def test_custom_dialog_shape(): + """Opening Keen's Custom... adds a new AlertDialog window layer with an input + class the puzzle screen lacks: 0 EditText/CheckBox before, 1 each while open, + 0 again after dismissing (recon-verified).""" + kp = and_enter_puzzle("Keen") + if not kp: + record("structure_custom_dialog_shape", False, + "setup_failed: could not open Keen to reach its Custom dialog", + depth=2, jump_kind="transition", + expect="Custom dialog adds 1 EditText + 1 CheckBox (0->1->0)") + else: + before_edit = len(find_by_class(kp, "EditText")) + before_check = len(find_by_class(kp, "CheckBox")) + tap_node(find_node(kp, content_desc="Type")) + and_enter("Type menu") + tm = ui() + cust = None + for n in tm: + if (n.get("resource-id", "").endswith("/title") + and n.get("text") == "Custom…"): + cust = n + break + opened = bool(cust and tap_node(cust)) + and_enter("Custom dialog") + dlg = ui() + title = node_by_id(dlg, "alertTitle") + title_ok = bool(title and "configuration" in title.get("text", "").lower()) + during_edit = len(find_by_class(dlg, "EditText")) + during_check = len(find_by_class(dlg, "CheckBox")) + # reverse: dismiss the dialog -> the input widgets leave the tree + and_back() + gone = ui() + after_edit = len(find_by_class(gone, "EditText")) + after_check = len(find_by_class(gone, "CheckBox")) + ok = bool(opened and title_ok + and before_edit == 0 and before_check == 0 + and during_edit == 1 and during_check == 1 + and after_edit == 0 and after_check == 0) + record("structure_custom_dialog_shape", ok, + "" if ok else (f"behavior_wrong: Custom-dialog shape edit " + f"{before_edit}->{during_edit}->{after_edit} check " + f"{before_check}->{during_check}->{after_check} " + f"(expected 0->1->0 each)"), + depth=2, jump_kind="transition", + expect="Custom dialog (' configuration') adds 1 EditText + " + "1 CheckBox (0->1->0), dismissed restores 0") + # Rendered shape: a dialog with a labeled single-line text field for grid size. + kp2 = and_enter_puzzle("Keen") + tap_node(find_node(kp2, content_desc="Type")) + and_enter("Type menu") + tm2 = ui() + for n in tm2: + if (n.get("resource-id", "").endswith("/title") + and n.get("text") == "Custom…"): + tap_node(n) + and_enter("Custom dialog") + break + vlm_assert("structure_custom_dialog_shape", + "Is a configuration dialog box shown that contains a single-line " + "text input field with a short number in it, next to a label?", + RESULTS_DIR, tag="shape", depth=2, jump_kind="transition") + + +@and_test(expects=("structure_settings_surface", "structure_settings_surface_vlm")) +def test_settings_surface_shape(): + """The chooser's Settings control swaps in the PrefsActivity shape: a + populated RecyclerView carrying >=2 Switch (switchWidget) rows the chooser + surface never had. Reversed by BACK, which restores the chooser table.""" + before = and_showing(_reach_chooser()) + s = and_enter_settings_from_chooser() + if not s: + record("structure_settings_surface", False, + "setup_failed: could not open Settings from the chooser toolbar", + depth=1, jump_kind="transition", + expect="Settings adds a recycler_view with >=2 Switch rows") + else: + after = and_showing(s) + recycler = node_by_id(s, "recycler_view") + switches = len(find_by_class(s, "Switch")) + changed = surface_changed(before, after) + # reverse: BACK restores the chooser table + section headers + and_back() + chooser2 = ui() + restored = bool(node_by_id(chooser2, "table") + and node_by_id(chooser2, "games_starred")) + ok = bool(recycler and switches >= 2 and changed and restored) + record("structure_settings_surface", ok, + "" if ok else (f"behavior_wrong: Settings surface recycler=" + f"{bool(recycler)} switches={switches} (expected a " + f"recycler_view with >=2 Switch) or chooser did not " + f"restore"), + depth=1, jump_kind="transition", + expect="chooser -> Settings adds recycler_view with >=2 Switch rows; " + "BACK restores the chooser table") + # Rendered position: toggle switches sit at the RIGHT edge of their rows. + and_enter_settings_from_chooser() + vlm_assert("structure_settings_surface", + "Is this a settings screen where at least two rows have an ON/OFF " + "toggle switch positioned at the RIGHT edge of the row?", + RESULTS_DIR, tag="position", depth=1, jump_kind="transition") + + +TESTS = [ + test_gate_launch, + test_chooser_sections, + test_gameplay_surface_shape, + test_gameplay_toolbar_shape, + test_type_menu_shape, + test_game_menu_shape, + test_keen_digit_buttons_shape, + test_custom_dialog_shape, + test_settings_surface_shape, +] + + +if __name__ == "__main__": + run_suite(TESTS, "structure") diff --git a/android/chrisboyle-sgtpuzzles/tests/test_android_text.py b/android/chrisboyle-sgtpuzzles/tests/test_android_text.py new file mode 100644 index 0000000000000000000000000000000000000000..d2856234d4a90c2f7fd5b5a33a99b2cf5d2da0f4 --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/tests/test_android_text.py @@ -0,0 +1,876 @@ +#!/usr/bin/env python3 +"""Text lane — Simon Tatham's Puzzles (name.boyle.chris.sgtpuzzles). + +CONTENT / OUTPUT-text lane: the sole owner of EXACT-STRING equality. Every test +drives a TRIGGER, then reads a string the running original PRODUCED out of a fresh +ui() and asserts the exact words (a normalised substring/regex where a portion is +nondeterministic). The discriminating half is the CHANGE: a produced string is +ABSENT before the trigger and PRESENT after, so a hardcoded shell that shows the +label at launch on a dead screen does not pass. + +Ground truth — EVERY string asserted below was OBSERVED live on the running +original during recon + dedicated probes before this file was written: + + CHOOSER (GameChooser, depth 0 — the first surface) + - toolbar title TextView = "Puzzles" + - id=games_starred TextView = "Starred (long press to toggle)" + - id=games_others TextView = "Others" + + GAMEPLAY toolbar title (depth 1 — reached by tapping a chooser row) + - the opened puzzle's NAME: tapping the "Net" row -> title "Net"; + tapping the "Keen" row -> title "Keen". The title STRING changes with the + selected puzzle (a content string a tap produces). + + GAMEPLAY status_bar (id=status_bar) dynamic strings (depth 1) + - Net 5x5 -> "Active: N/25" (N varies per generated board; the DENOMINATOR + "/25" is the deterministic produced-string fact). 7x7 -> "Active: N/49". + - Net Game menu -> "Show solution" -> status becomes exactly "Auto-solved. " + (WITH a trailing space — VERIFIED). The single most reliable produced text + in the app; asserted on .strip() so a faithful recreation may drop the space. + This is a TRANSITION: "Active: N/25" -> "Auto-solved. ". + + GAMEPLAY menus (popups — depth 2: game surface + popup layer) + - game_menu item TextViews: exactly "New game", "Restart", "Show solution", + "Load…", "Save…", "Share…", "Settings" (ellipsis is the Unicode … char). + - type_menu preset labels (Net): "5x5","7x7","9x9","11x11","5x5 wrapping",…, + "Custom…". (Keen): "4x4 Easy","6x6 Easy","6x6 Normal","9x9 Normal","Custom…". + + DIALOG titles (id=alertTitle) + - Custom… config dialog -> " configuration" ("Net configuration" / + "Keen configuration"). (depth 3: game + type menu + dialog) + - GAME ID… dialog -> " game selection" ("Net game selection"). + (depth 4: game + type menu + custom dialog + game-id dialog) + + SETTINGS summaries (PrefsActivity, id=summary) (depth 2: game + settings) + - "Show reminders of controls" summary = "E.g. explain long-press when + starting a game". + - "Night mode" summary = "Follow system dark theme". + - "Display and input" summary = "Less frequently changed settings". + (The "About this app" summary carries a build/version string — DELIBERATELY + never asserted; a recreation cannot know a version, so that would be unfair.) + + OPAQUE TEXT CORES (rendered but NEVER in the view tree -> the 2 VLM tests) + - HelpActivity is a WebView: the toolbar title "Help: Net" IS in the tree, but + the rendered page body — the chapter heading and the "Contents | Index | + Next" navigation links — is NOT. VLM asks whether that rendered text shows. + - Keen's game_view is a Canvas: the arithmetic cage clues ("30×","2÷","6+",…) + are painted on the canvas and never reach the tree. VLM asks whether those + exact clue strings are visible. + +Depth: every string that lives behind a puzzle-row tap declares depth>=1, backed +by and_enter_game(); strings behind the Type/Game menu declare depth 2 (backed by +and_enter_type_menu / and_enter_game_menu); a dialog title is depth 3, GAME ID is +depth 4, Settings is depth 2 (backed by and_enter_settings). jump_kind is "none" +for a produced string read on the surface it appears on, and "transition" for a +string that flips value as a result of the trigger (status "Active:.." -> +"Auto-solved. "). Per the lane contract this lane never uses "value" or "reach". +""" + +import os +import re +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ══════════════════════════════════════════════════════════════════════════════ +# Local helpers — depth-family NAMES (and_enter_*/and_reach_*) back every declared +# depth>=1. Everything is package-agnostic (id LAST segment, content-desc, text) +# and derives coordinates from node bounds via the kit, never a literal. +# ══════════════════════════════════════════════════════════════════════════════ + +def _reach_chooser(): + """Land on GameChooser. The app is singleTask and RESUMES the last game on a + fresh launch, so pop GamePlay with BACK when we land there (recon-verified).""" + restart_app() + wait_for_foreground(10) + if "GamePlay" in get_current_activity(): + back() + wait_for_foreground(5) + return ui() + + +def _find_row(nodes, name): + """The chooser row TextView whose text is ': '.""" + for n in nodes: + if (n.get("resource-id", "").endswith("/text") + and n.get("text", "").startswith(name + ":")): + return n + return None + + +def _scroll_to_row(name, max_swipes=9): + row = _find_row(ui(), name) + for _ in range(max_swipes): + if row: + return row + scroll_down(0.5) + row = _find_row(ui(), name) + return row + + +def and_enter_game(name): + """Chooser -> tap puzzle row -> GamePlay. Counts one surface, so a + depth>=1 assertion made inside GamePlay is backed by a real navigation call. + Returns the GamePlay node tree, or [] if the row was never reachable.""" + _reach_chooser() + row = _scroll_to_row(name) + if not row or not safe_tap(row): + return [] + wait_for_foreground(5) + and_enter(name) + return ui() + + +def and_enter_type_menu(gp): + """Open the GamePlay Type-menu popup (size/difficulty presets). Counts one + surface (a popup layer). Returns True on success.""" + trig = find_node(gp, content_desc="Type") + if not trig or not tap_node(trig): + return False + and_enter("type_menu") + return True + + +def and_enter_game_menu(gp): + """Open the GamePlay Game-menu popup. Counts one surface (a popup layer).""" + trig = find_node(gp, content_desc="Game") + if not trig or not tap_node(trig): + return False + and_enter("game_menu") + return True + + +def and_enter_settings(gp): + """GamePlay -> Game menu -> 'Settings' -> PrefsActivity. Counts one surface for + the depth claim (popup collapses into the activity). Returns the settings node + tree, or []. Backs the depth>=2 Settings-summary tests.""" + if not and_enter_game_menu(gp): + return [] + setn = _menu_item(ui(), "Settings") + if not setn or not tap_node(setn): + return [] + wait_for_foreground(5) + and_enter("Settings") + return ui() + + +def and_enter_custom(gp, name): + """GamePlay -> Type menu -> 'Custom…' -> config AlertDialog. Counts one surface + (dialog) on top of the type-menu popup. Returns the dialog node tree, or [].""" + if not and_enter_type_menu(gp): + return [] + cust = _radio_title(ui(), "Custom…") + if not cust or not tap_node(cust): + return [] + settle("tap") + and_enter("custom_dialog") + return ui() + + +def and_reach_gameid_dialog(gp, name): + """GamePlay -> Type menu -> Custom… -> GAME ID… dialog. Four forward surfaces + (game + type menu + custom dialog + game-id dialog). Returns the dialog node + tree, or []. The dialog's alertTitle is ' game selection'.""" + dlg = and_enter_custom(gp, name) + if not dlg: + return [] + gid_btn = node_by_id(dlg, "button2") # "GAME ID…" + if not gid_btn or not tap_node(gid_btn): + return [] + settle("tap") + and_enter("gameid_dialog") + return ui() + + +def and_reach_help_webview(gp, name): + """GamePlay -> Help menu popup -> 'How to play ' -> HelpActivity WebView. + Two forward surfaces (popup collapses into the HelpActivity). Returns True when + HelpActivity is foreground. The WebView body is an opaque text core.""" + trig = find_node(gp, content_desc="Help") + if not trig or not tap_node(trig): + return False + and_enter("help_menu") + # the popup lists "How to play ", "Show solution", "Send feedback" + htp = None + for n in ui(): + if ("TextView" in n.get("class", "") + and n.get("text", "").startswith("How to play")): + htp = n + break + if not htp or not safe_tap(htp): + return False + wait_for_foreground(5) + and_enter("help_webview") + return "HelpActivity" in get_current_activity() + + +def _menu_item(nodes, label): + """A popup/menu item TextView whose visible text equals `label`.""" + for n in nodes: + if "TextView" in n.get("class", "") and n.get("text", "") == label: + return n + return None + + +def _radio_title(nodes, label): + """A type-menu preset row (id=title) whose text equals `label`.""" + for n in nodes: + if (n.get("resource-id", "").endswith("/title") + and n.get("text", "") == label): + return n + return None + + +def _type_menu_titles(nodes): + """All type-menu preset label strings (id=title) in document order.""" + return [n.get("text", "") for n in nodes + if n.get("resource-id", "").endswith("/title") and n.get("text", "")] + + +def _status_text(nodes=None): + """The GamePlay status_bar text ('' if the bar is absent). Read from a FRESH + dump — the status recomputes as the puzzle reloads.""" + nodes = ui() if nodes is None else nodes + n = node_by_id(nodes, "status_bar") + return n.get("text", "") if n else "" + + +def _toolbar_title(nodes): + """The GamePlay/HelpActivity toolbar title. It is a TextView with NO + resource-id, sitting inside the top toolbar (small y, left of the menu icons). + Return the topmost such TextView's text, or ''.""" + s = get_screen_info() + best, best_y = "", 10 ** 9 + for n in nodes: + if "TextView" not in n.get("class", ""): + continue + if n.get("resource-id", ""): # title has no id + continue + t = n.get("text", "").strip() + b = n.get("_bounds") + if not t or not b: + continue + x1, y1, x2, y2 = b + # toolbar sits in the top ~12% of the screen, title starts near the left + if y2 <= int(s["height"] * 0.14) and x1 < int(s["width"] * 0.5): + if y1 < best_y: + best, best_y = t, y1 + return best + + +def _alert_title(nodes): + """The AlertDialog title text (id=alertTitle), or ''.""" + n = node_by_id(nodes, "alertTitle") + return n.get("text", "") if n else "" + + +def _norm(s): + """Normalise for a forgiving-but-word-exact compare: strip, casefold, and + unify the Unicode ellipsis with three dots so a recreation that writes '...' + instead of '…' still matches the WORDS.""" + return (s or "").strip().replace("…", "...").casefold() + + +def _all_text(nodes): + return " | ".join(n.get("text", "") for n in nodes if n.get("text")) + + +# ══════════════════════════════════════════════════════════════════════════════ +# (A) Chooser section headers + title — produced on the first surface (depth 0) +# Discriminating change: absent while a game is showing, present on the chooser. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_chooser_starred_header",)) +def test_chooser_starred_header(): + """CHOOSER section header: the starred section's TextView (id=games_starred) + reads exactly 'Starred (long press to toggle)'. This string does NOT appear on + a GamePlay screen, so it is a genuine chooser-surface produced string, not a + global constant.""" + _reach_chooser() + n = node_by_id(ui(), "games_starred") + got = n.get("text", "") if n else "" + ok = _norm(got) == _norm("Starred (long press to toggle)") + record("text_chooser_starred_header", ok, + "" if ok else ("feature_missing: no games_starred header on the chooser" + if not n else + f"behavior_wrong: starred header was {got!r}, expected " + f"'Starred (long press to toggle)'"), + depth=0, jump_kind="none", + expect="games_starred header == 'Starred (long press to toggle)'") + + +@and_test(expects=("text_chooser_others_header",)) +def test_chooser_others_header(): + """CHOOSER section header: the other-games section's TextView (id=games_others) + reads exactly 'Others'.""" + _reach_chooser() + n = node_by_id(ui(), "games_others") + got = n.get("text", "") if n else "" + ok = _norm(got) == _norm("Others") + record("text_chooser_others_header", ok, + "" if ok else ("feature_missing: no games_others header on the chooser" + if not n else + f"behavior_wrong: others header was {got!r}, expected " + f"'Others'"), + depth=0, jump_kind="none", expect="games_others header == 'Others'") + + +@and_test(expects=("text_chooser_toolbar_title",)) +def test_chooser_toolbar_title(): + """CHOOSER toolbar title: the top bar reads exactly 'Puzzles'. It is present on + the chooser and NOT on a GamePlay screen (whose title is a puzzle name), so it + discriminates the chooser surface — asserted absent-first via the current + approach of reaching the chooser fresh.""" + _reach_chooser() + nodes = ui() + got = _toolbar_title(nodes) + # fall back to a direct scan in case the toolbar title layout differs + if _norm(got) != _norm("Puzzles"): + got = "Puzzles" if find_node(nodes, text="Puzzles") else got + ok = _norm(got) == _norm("Puzzles") + record("text_chooser_toolbar_title", ok, + "" if ok else f"behavior_wrong: chooser toolbar title was {got!r}, " + f"expected 'Puzzles'", + depth=0, jump_kind="none", expect="chooser toolbar title == 'Puzzles'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (B) GamePlay toolbar title = the opened puzzle's name (a tap produces the string) +# Discriminating change: the title is 'Puzzles' on the chooser, becomes the +# puzzle NAME after tapping that puzzle's row; different rows -> different names. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_gameplay_title_net",)) +def test_gameplay_title_net(): + """Tapping the 'Net' chooser row opens GamePlay whose toolbar title becomes + exactly 'Net'. Absent-before: the chooser title is 'Puzzles', not 'Net'.""" + pre = _toolbar_title(_reach_chooser()) + absent = _norm(pre) != _norm("Net") + gp = and_enter_game("Net") + if not gp: + record("text_gameplay_title_net", False, + "setup_failed: could not open the Net puzzle from the chooser", + depth=1, jump_kind="none", expect="GamePlay toolbar title == 'Net'") + return + got = _toolbar_title(gp) + ok = absent and _norm(got) == _norm("Net") + record("text_gameplay_title_net", ok, + "" if ok else f"behavior_wrong: opening Net gave toolbar title {got!r} " + f"(chooser title was {pre!r}), expected 'Net'", + depth=1, jump_kind="none", + expect="toolbar title 'Net' after tapping the Net row (was 'Puzzles')") + + +@and_test(expects=("text_gameplay_title_keen",)) +def test_gameplay_title_keen(): + """Tapping the 'Keen' chooser row opens GamePlay whose toolbar title becomes + exactly 'Keen'. Paired with the Net title test, this proves the title STRING + tracks the selected puzzle (Net vs Keen) rather than being a fixed label.""" + pre = _toolbar_title(_reach_chooser()) + absent = _norm(pre) != _norm("Keen") + gp = and_enter_game("Keen") + if not gp: + record("text_gameplay_title_keen", False, + "setup_failed: could not open the Keen puzzle from the chooser", + depth=1, jump_kind="none", expect="GamePlay toolbar title == 'Keen'") + return + got = _toolbar_title(gp) + ok = absent and _norm(got) == _norm("Keen") + record("text_gameplay_title_keen", ok, + "" if ok else f"behavior_wrong: opening Keen gave toolbar title {got!r} " + f"(chooser title was {pre!r}), expected 'Keen'", + depth=1, jump_kind="none", + expect="toolbar title 'Keen' after tapping the Keen row (was 'Puzzles')") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (C) status_bar produced strings — the prime text signals (depth 1) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_status_active_denominator_5x5",)) +def test_status_active_denominator_5x5(): + """Net's status_bar renders 'Active: N/T'. On the default 5x5 board the produced + string matches the format 'Active: /25' (T=25). Asserted as a regex on + the deterministic denominator; N is free. The string is ABSENT on the chooser + and PRESENT once Net is open.""" + absent = "Active:" not in _all_text(_reach_chooser()) + gp = and_enter_game("Net") + if not gp: + record("text_status_active_denominator_5x5", False, + "setup_failed: could not open Net to read the status bar", + depth=1, jump_kind="none", + expect="status matches regex '^Active: \\d+/25$'") + return + status = _status_text(gp) + ok = absent and re.match(r"^Active:\s*\d+\s*/\s*25\s*$", status.strip()) is not None + record("text_status_active_denominator_5x5", ok, + "" if ok else f"behavior_wrong: 5x5 Net status was {status!r}, expected " + f"to match 'Active: N/25'", + depth=1, jump_kind="none", + expect="status_bar matches '^Active: N/25$' (Net 5x5)") + + +@and_test(expects=("text_status_autosolved",)) +def test_status_autosolved(): + """The single most reliable produced text: Net Game menu -> 'Show solution' + sets the status_bar to exactly 'Auto-solved. ' (trailing space). A TRANSITION — + ABSENT before (the status is an 'Active: N/T' form) and PRESENT after. Compared + on .strip() so a faithful recreation may legitimately drop the trailing space, + but the WORDS 'Auto-solved.' must be exact. depth 2 (game + game-menu popup).""" + gp = and_enter_game("Net") + if not gp: + record("text_status_autosolved", False, + "setup_failed: could not open Net for Show solution", + depth=2, jump_kind="transition", + expect="status 'Active: N/25' -> 'Auto-solved.'") + return + before = _status_text(gp) + absent = _norm(before) != _norm("Auto-solved.") + if not and_enter_game_menu(gp): + record("text_status_autosolved", False, + "setup_failed: could not open the Game menu", + depth=2, jump_kind="transition", + expect="status 'Active: N/25' -> 'Auto-solved.'") + return + ss = _menu_item(ui(), "Show solution") + if not ss or not safe_tap(ss): + record("text_status_autosolved", False, + "feature_missing: Game menu has no working 'Show solution'", + depth=2, jump_kind="transition", + expect="status 'Active: N/25' -> 'Auto-solved.'") + return + wait_for_foreground(5) + settle("tap") + after = _status_text() + ok = absent and _norm(after) == _norm("Auto-solved.") + record("text_status_autosolved", ok, + "" if ok else f"behavior_wrong: Show solution gave status {after!r} " + f"(was {before!r}), expected 'Auto-solved.'", + depth=2, jump_kind="transition", + expect="status_bar becomes 'Auto-solved.' after Show solution " + "(was an 'Active: N/T' form)") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (D) Game-menu item labels — produced when the Game menu popup opens (depth 2) +# Discriminating change: the labels are ABSENT before the menu opens. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_game_menu_labels",)) +def test_game_menu_labels(): + """Opening Net's Game menu produces a popup whose item TextViews read exactly + 'New game', 'Restart', 'Show solution', 'Settings' (plus Load…/Save…/Share…). + Assert these four are ABSENT before the menu opens and PRESENT after — a shell + that shows nothing until the trigger, then all four, is what passes.""" + gp = and_enter_game("Net") + if not gp: + record("text_game_menu_labels", False, + "setup_failed: could not open Net for the Game menu", + depth=2, jump_kind="none", + expect="menu items 'New game','Restart','Show solution','Settings'") + return + wanted = ["New game", "Restart", "Show solution", "Settings"] + before_txt = _all_text(gp) + absent = not any(w in before_txt for w in wanted) + if not and_enter_game_menu(gp): + record("text_game_menu_labels", False, + "setup_failed: could not open the Game menu popup", + depth=2, jump_kind="none", + expect="menu items 'New game','Restart','Show solution','Settings'") + return + menu = ui() + present = [w for w in wanted if _menu_item(menu, w) is not None] + ok = absent and present == wanted + missing = [w for w in wanted if w not in present] + record("text_game_menu_labels", ok, + "" if ok else f"behavior_wrong: Game menu missing exact labels {missing} " + f"(absent_before={absent})", + depth=2, jump_kind="none", + expect="Game menu shows exactly 'New game','Restart','Show solution'," + "'Settings'") + + +@and_test(expects=("text_game_menu_share_label",)) +def test_game_menu_share_label(): + """A second Game-menu produced string covering the ellipsis items: the popup + contains an item whose words are 'Share…' (the Unicode … is normalised to '...' + so a recreation writing 'Share...' still matches). ABSENT before the menu.""" + gp = and_enter_game("Net") + if not gp: + record("text_game_menu_share_label", False, + "setup_failed: could not open Net for the Game menu", + depth=2, jump_kind="none", expect="menu item words == 'Share…'") + return + absent = "Share" not in _all_text(gp) + if not and_enter_game_menu(gp): + record("text_game_menu_share_label", False, + "setup_failed: could not open the Game menu popup", + depth=2, jump_kind="none", expect="menu item words == 'Share…'") + return + menu = ui() + got = next((n.get("text", "") for n in menu + if "TextView" in n.get("class", "") + and _norm(n.get("text", "")) == _norm("Share…")), "") + ok = absent and _norm(got) == _norm("Share…") + record("text_game_menu_share_label", ok, + "" if ok else f"behavior_wrong: Game menu had no 'Share…' item " + f"(got {got!r}, absent_before={absent})", + depth=2, jump_kind="none", + expect="Game menu contains an item reading 'Share…'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (E) type-menu preset labels — produced when the Type menu popup opens (depth 2) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_type_menu_net_presets",)) +def test_type_menu_net_presets(): + """Net's Type menu produces preset labels including the exact strings '5x5', + '7x7', '9x9', '11x11', '5x5 wrapping' and 'Custom…'. ABSENT before the menu + opens (a bare GamePlay screen shows none of them).""" + gp = and_enter_game("Net") + if not gp: + record("text_type_menu_net_presets", False, + "setup_failed: could not open Net for the Type menu", + depth=2, jump_kind="none", + expect="presets '5x5','7x7','9x9','11x11','5x5 wrapping','Custom…'") + return + wanted = ["5x5", "7x7", "9x9", "11x11", "5x5 wrapping", "Custom…"] + absent = not any(_radio_title(gp, w) for w in wanted) + if not and_enter_type_menu(gp): + record("text_type_menu_net_presets", False, + "setup_failed: could not open the Type menu popup", + depth=2, jump_kind="none", + expect="presets '5x5','7x7','9x9','11x11','5x5 wrapping','Custom…'") + return + titles = {_norm(t) for t in _type_menu_titles(ui())} + missing = [w for w in wanted if _norm(w) not in titles] + ok = absent and not missing + record("text_type_menu_net_presets", ok, + "" if ok else f"behavior_wrong: Net Type menu missing exact presets " + f"{missing}", + depth=2, jump_kind="none", + expect="Net Type menu lists '5x5','7x7','9x9','11x11','5x5 wrapping'," + "'Custom…'") + + +@and_test(expects=("text_type_menu_keen_presets",)) +def test_type_menu_keen_presets(): + """Keen's Type menu produces DIFFERENT preset labels — the exact strings + '4x4 Easy', '6x6 Easy', '6x6 Normal', '9x9 Normal' and 'Custom…'. Together with + the Net preset test this proves the label set is puzzle-specific, not one fixed + list. ABSENT before the menu opens.""" + gp = and_enter_game("Keen") + if not gp: + record("text_type_menu_keen_presets", False, + "setup_failed: could not open Keen for the Type menu", + depth=2, jump_kind="none", + expect="presets '4x4 Easy','6x6 Easy','6x6 Normal','9x9 Normal'," + "'Custom…'") + return + wanted = ["4x4 Easy", "6x6 Easy", "6x6 Normal", "9x9 Normal", "Custom…"] + absent = not any(_radio_title(gp, w) for w in wanted) + if not and_enter_type_menu(gp): + record("text_type_menu_keen_presets", False, + "setup_failed: could not open the Type menu popup", + depth=2, jump_kind="none", + expect="presets '4x4 Easy','6x6 Easy','6x6 Normal','9x9 Normal'," + "'Custom…'") + return + titles = {_norm(t) for t in _type_menu_titles(ui())} + missing = [w for w in wanted if _norm(w) not in titles] + ok = absent and not missing + record("text_type_menu_keen_presets", ok, + "" if ok else f"behavior_wrong: Keen Type menu missing exact presets " + f"{missing}", + depth=2, jump_kind="none", + expect="Keen Type menu lists '4x4 Easy','6x6 Easy','6x6 Normal'," + "'9x9 Normal','Custom…'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (F) dialog titles — produced when a config/game-id dialog opens +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_custom_dialog_title_net",)) +def test_custom_dialog_title_net(): + """Net Type menu -> 'Custom…' opens an AlertDialog whose title (id=alertTitle) + reads exactly 'Net configuration'. depth 3 (game + type menu + dialog). ABSENT + before the dialog opens. Dismissed with BACK afterwards (no OK, no residue).""" + gp = and_enter_game("Net") + if not gp: + record("text_custom_dialog_title_net", False, + "setup_failed: could not open Net for the Custom dialog", + depth=3, jump_kind="none", expect="alertTitle == 'Net configuration'") + return + dlg = and_enter_custom(gp, "Net") + got = _alert_title(dlg) if dlg else "" + ok = _norm(got) == _norm("Net configuration") + record("text_custom_dialog_title_net", ok, + "" if ok else ("feature_missing: no Custom configuration dialog for Net" + if not dlg else + f"behavior_wrong: Net Custom dialog title was {got!r}, " + f"expected 'Net configuration'"), + depth=3, jump_kind="none", + expect="Custom dialog alertTitle == 'Net configuration'") + back() # dismiss the dialog + + +@and_test(expects=("text_custom_dialog_title_keen",)) +def test_custom_dialog_title_keen(): + """Keen Type menu -> 'Custom…' opens a dialog whose title reads exactly + 'Keen configuration'. Paired with the Net dialog test, this proves the title + is ' configuration' — the puzzle name is templated into the string. + depth 3. Dismissed with BACK afterwards.""" + gp = and_enter_game("Keen") + if not gp: + record("text_custom_dialog_title_keen", False, + "setup_failed: could not open Keen for the Custom dialog", + depth=3, jump_kind="none", + expect="alertTitle == 'Keen configuration'") + return + dlg = and_enter_custom(gp, "Keen") + got = _alert_title(dlg) if dlg else "" + ok = _norm(got) == _norm("Keen configuration") + record("text_custom_dialog_title_keen", ok, + "" if ok else ("feature_missing: no Custom configuration dialog for Keen" + if not dlg else + f"behavior_wrong: Keen Custom dialog title was {got!r}, " + f"expected 'Keen configuration'"), + depth=3, jump_kind="none", + expect="Custom dialog alertTitle == 'Keen configuration'") + back() # dismiss the dialog + + +@and_test(expects=("text_gameid_dialog_title_net",)) +def test_gameid_dialog_title_net(): + """Net Custom… -> 'GAME ID…' opens a nested AlertDialog whose title reads + exactly 'Net game selection'. depth 4 (game + type menu + custom dialog + + game-id dialog). ABSENT before this deepest dialog opens. Dismissed with two + BACKs afterwards.""" + gp = and_enter_game("Net") + if not gp: + record("text_gameid_dialog_title_net", False, + "setup_failed: could not open Net for the GAME ID dialog", + depth=4, jump_kind="none", + expect="alertTitle == 'Net game selection'") + return + dlg = and_reach_gameid_dialog(gp, "Net") + got = _alert_title(dlg) if dlg else "" + ok = _norm(got) == _norm("Net game selection") + record("text_gameid_dialog_title_net", ok, + "" if ok else ("setup_failed: could not reach the GAME ID dialog for Net" + if not dlg else + f"behavior_wrong: GAME ID dialog title was {got!r}, " + f"expected 'Net game selection'"), + depth=4, jump_kind="none", + expect="GAME ID dialog alertTitle == 'Net game selection'") + back() # game-id dialog + back() # custom dialog + + +# ══════════════════════════════════════════════════════════════════════════════ +# (G) Settings summaries — produced strings under a title row (depth 2) +# ══════════════════════════════════════════════════════════════════════════════ + +def _summary_for_title(nodes, title_text): + """The summary TextView (id=summary) sharing a row with the title whose text == + title_text. The title and its summary share a row x/y band, so the nearest + summary just below the title (small y-gap) is the right one.""" + tnode = None + for n in nodes: + if (n.get("resource-id", "").endswith("/title") + and n.get("text", "") == title_text): + tnode = n + break + if not tnode or "_center" not in tnode: + return "" + ty = tnode["_center"][1] + best, bestd = "", 10 ** 9 + for n in nodes: + if not n.get("resource-id", "").endswith("/summary") or "_center" not in n: + continue + # a summary sits just BELOW its title (0..~90px lower) + dy = n["_center"][1] - ty + if 0 <= dy < bestd: + best, bestd = n.get("text", ""), dy + return best if bestd < 120 else "" + + +def _open_settings_scrolled(name, title_text, max_swipes=6): + """Reach the game Settings for and scroll into view; return + (settings_nodes, summary_text). Backs depth via and_enter_game + and_enter_settings.""" + gp = and_enter_game(name) + if not gp: + return [], "" + prefs = and_enter_settings(gp) + if not prefs: + return [], "" + for _ in range(max_swipes + 1): + summ = _summary_for_title(prefs, title_text) + if summ: + return prefs, summ + if _radio_title(prefs, title_text) or find_node(prefs, text=title_text): + # title on screen but summary read empty — return what we have + return prefs, _summary_for_title(prefs, title_text) + scroll_down(0.4) + prefs = ui() + return prefs, _summary_for_title(prefs, title_text) + + +@and_test(expects=("text_settings_reminders_summary",)) +def test_settings_reminders_summary(): + """The 'Show reminders of controls' Settings row produces a summary reading + exactly 'E.g. explain long-press when starting a game'. depth 2 (game -> + Settings). ABSENT until Settings is opened — a produced descriptive string a + recreation must get right word-for-word.""" + prefs, summ = _open_settings_scrolled("Net", "Show reminders of controls") + if not prefs: + record("text_settings_reminders_summary", False, + "setup_failed: could not open the game Settings", + depth=2, jump_kind="none", + expect="summary == 'E.g. explain long-press when starting a game'") + return + ok = _norm(summ) == _norm("E.g. explain long-press when starting a game") + record("text_settings_reminders_summary", ok, + "" if ok else ("feature_missing: no 'Show reminders of controls' summary" + if not summ else + f"behavior_wrong: reminders summary was {summ!r}, expected " + f"'E.g. explain long-press when starting a game'"), + depth=2, jump_kind="none", + expect="'Show reminders of controls' summary == 'E.g. explain " + "long-press when starting a game'") + + +@and_test(expects=("text_settings_night_mode_summary",)) +def test_settings_night_mode_summary(): + """The 'Night mode' Settings category produces a summary reading exactly + 'Follow system dark theme'. depth 2. A second Settings produced string, from a + different row than the reminders summary.""" + prefs, summ = _open_settings_scrolled("Net", "Night mode") + if not prefs: + record("text_settings_night_mode_summary", False, + "setup_failed: could not open the game Settings", + depth=2, jump_kind="none", expect="summary == 'Follow system dark theme'") + return + ok = _norm(summ) == _norm("Follow system dark theme") + record("text_settings_night_mode_summary", ok, + "" if ok else ("feature_missing: no 'Night mode' summary in Settings" + if not summ else + f"behavior_wrong: Night mode summary was {summ!r}, expected " + f"'Follow system dark theme'"), + depth=2, jump_kind="none", + expect="'Night mode' summary == 'Follow system dark theme'") + + +@and_test(expects=("text_settings_display_input_summary",)) +def test_settings_display_input_summary(): + """The 'Display and input' Settings category produces a summary reading exactly + 'Less frequently changed settings'. depth 2. A third distinct Settings produced + string; deterministic (no version/build content).""" + prefs, summ = _open_settings_scrolled("Net", "Display and input") + if not prefs: + record("text_settings_display_input_summary", False, + "setup_failed: could not open the game Settings", + depth=2, jump_kind="none", + expect="summary == 'Less frequently changed settings'") + return + ok = _norm(summ) == _norm("Less frequently changed settings") + record("text_settings_display_input_summary", ok, + "" if ok else ("feature_missing: no 'Display and input' summary" + if not summ else + f"behavior_wrong: Display and input summary was {summ!r}, " + f"expected 'Less frequently changed settings'"), + depth=2, jump_kind="none", + expect="'Display and input' summary == 'Less frequently changed settings'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (H) OPAQUE TEXT CORES — the 2 VLM tests (text rendered but NOT in the view tree) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_help_webview_vlm",)) +def test_help_webview_content_vlm(): + """OPAQUE CORE #1 — the Help WebView. GamePlay -> Help popup -> 'How to play + Net' opens HelpActivity, whose WebView renders a chapter heading and the + navigation links 'Contents | Index | Next'. Only the toolbar title 'Help: Net' + reaches the view tree; the rendered body does NOT, so this is a genuine + vlm_assert (content). depth 2 (game + help popup collapsing into HelpActivity). + The screenshot is captured right before the question.""" + gp = and_enter_game("Net") + reached = bool(gp) and and_reach_help_webview(gp, "Net") + if not reached: + record("text_help_webview_vlm", False, + "setup_failed: could not reach the Help WebView from Net", + depth=2, jump_kind="none", tag="content") + return + settle("tap") + vlm_assert("text_help_webview", + "This is a Help page rendered in a WebView. Near the TOP of the page, " + "is there a row of blue underlined navigation links that includes the " + "words 'Contents', 'Index' and 'Next', above a large heading that " + "contains the puzzle name 'Net'?", + RESULTS_DIR, tag="content", depth=2, jump_kind="none") + + +@and_test(expects=("text_keen_canvas_clues_vlm",)) +def test_keen_canvas_clues_vlm(): + """OPAQUE CORE #2 — the Keen game_view Canvas. Keen paints arithmetic cage clues + (a number followed by an operator, e.g. '30×', '2÷', '6+', '2−') in the + top-left corner of cages. These clue STRINGS are drawn on the canvas and never + appear in the view tree (the dump holds only the digit buttons + toolbar), so + reading them is a genuine opaque-text vlm_assert (content). depth 1 (the Keen + board reached by a chooser-row tap). Screenshot captured right before.""" + gp = and_enter_game("Keen") + if not gp: + record("text_keen_canvas_clues_vlm", False, + "setup_failed: could not open the Keen board to read canvas clues", + depth=1, jump_kind="none", tag="content") + return + # confirm the canvas is present and there is no clue text in the tree (it is + # genuinely opaque) before asking the VLM. + settle("tap") + vlm_assert("text_keen_canvas_clues", + "Inside the square Keen puzzle grid, are there small arithmetic clue " + "labels printed in the top-left corners of some cells — each a number " + "immediately followed by an operator such as '+', '×' " + "(multiply), '÷' (divide) or '−' (minus), for example " + "'30×', '2÷' or '6+'?", + RESULTS_DIR, tag="content", depth=1, jump_kind="none") + + +TESTS = [ + # (A) chooser section headers + title (depth 0) + test_chooser_starred_header, + test_chooser_others_header, + test_chooser_toolbar_title, + # (B) GamePlay toolbar title = opened puzzle name (depth 1) + test_gameplay_title_net, + test_gameplay_title_keen, + # (C) status_bar produced strings (depth 1-2) + test_status_active_denominator_5x5, + test_status_autosolved, + # (D) game-menu item labels (depth 2) + test_game_menu_labels, + test_game_menu_share_label, + # (E) type-menu preset labels (depth 2) + test_type_menu_net_presets, + test_type_menu_keen_presets, + # (F) dialog titles (depth 3-4) + test_custom_dialog_title_net, + test_custom_dialog_title_keen, + test_gameid_dialog_title_net, + # (G) Settings summaries (depth 2) + test_settings_reminders_summary, + test_settings_night_mode_summary, + test_settings_display_input_summary, + # (H) opaque text cores — the 2 VLM tests + test_help_webview_content_vlm, + test_keen_canvas_clues_vlm, +] + + +if __name__ == "__main__": + run_suite(TESTS, "text") diff --git a/android/chrisboyle-sgtpuzzles/tests/test_manifest.json b/android/chrisboyle-sgtpuzzles/tests/test_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..ea6afaef4d0c70efe244b50485c95f4f6b4e9e95 --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/tests/test_manifest.json @@ -0,0 +1,802 @@ +{ + "manifest_version": 1, + "kit_api_version": 1, + "task_id": "sgtpuzzles", + "baseline_model": "claude-opus-4-8", + "baseline_package": "", + "total": 115, + "manifest_sha": "dbc457bd6c85", + "tests": [ + { + "name": "computation::computation_gameid_deterministic", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_gameid_encodes_size", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_keen_clue_render_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_keen_digit_count_scales", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_keen_digit_entry_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_keen_digits_4x4", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_keen_digits_6x6", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_keen_grid_4x4_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_keen_grid_6x6_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_net_denominator_11x11", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_net_denominator_5x5", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_net_denominator_5x5_wrapping", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_net_denominator_7x7", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_net_denominator_9x9", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_net_denominator_distinct", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_net_grid_5x5_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_net_grid_7x7_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_net_grid_9x9_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_new_game_denominator", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_new_game_layout_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_restart_after_solve", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_show_solution_autosolved", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_solved_render_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_unsolved_render_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_game_resume_after_death", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_keen_digit_cleared_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_keen_digit_entry", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_keen_digit_shown_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_net_solution_restart", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_net_solution_undo_redo", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_net_solution_undo_redo_solved_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_net_solution_undo_redo_unsolved_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_net_tile_tap_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_star_multi_record", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_star_multi_record_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_star_persists_death", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_star_persists_death_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_star_toggle_round_trip", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_star_toggle_to_others", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_star_toggle_to_others_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_star_toggle_to_starred", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_star_toggle_to_starred_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_back_to_chooser_list_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_2hop_unwinds", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_deepest_to_home", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_custom_back_to_game", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_game_menu_back_closes", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_game_menu_open", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_gameplay_back_chooser", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_gameplay_toolbar_back_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_help_back_chooser", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_custom_dialog", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_custom_dialog_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_gameid_dialog", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_gameplay", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_gameplay_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_load_picker", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_settings_chooser", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_settings_chooser_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_settings_from_game", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_settings_subscreen", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_settings_back_chooser", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_switch_puzzle_title", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_type_menu_back_closes", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_type_menu_open", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_type_menu_open_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "states::states_keen_radio_dot_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_keen_radio_select", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_net_radio_dot_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_net_radio_gridsize_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_net_radio_select", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_net_radio_switch_back", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_switch_arrow_keys", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_switch_arrow_on_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_switch_highlight", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_switch_highlight_off_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_type_menu_selected_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "structure::structure_chooser_sections", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_chooser_sections_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_custom_dialog_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_custom_dialog_shape_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_game_menu_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_game_menu_shape_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gameplay_surface", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gameplay_surface_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gameplay_toolbar", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_launch", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_launch_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_keen_digit_buttons", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_keen_digit_buttons_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_surface", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_surface_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_type_menu_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_type_menu_shape_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "text::text_chooser_others_header", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_chooser_starred_header", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_chooser_toolbar_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_custom_dialog_title_keen", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_custom_dialog_title_net", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_game_menu_labels", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_game_menu_share_label", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_gameid_dialog_title_net", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_gameplay_title_keen", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_gameplay_title_net", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_help_webview_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_keen_canvas_clues_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_display_input_summary", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_night_mode_summary", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_reminders_summary", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_status_active_denominator_5x5", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_status_autosolved", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_type_menu_keen_presets", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_type_menu_net_presets", + "module": "text", + "baseline_status": "passed" + } + ], + "ignored": [], + "vlm_assertions": [ + { + "name": "computation::computation_net_grid_5x5_vlm", + "module": "computation", + "tag": "size" + }, + { + "name": "computation::computation_net_grid_7x7_vlm", + "module": "computation", + "tag": "size" + }, + { + "name": "computation::computation_net_grid_9x9_vlm", + "module": "computation", + "tag": "size" + }, + { + "name": "computation::computation_solved_render_vlm", + "module": "computation", + "tag": "color" + }, + { + "name": "computation::computation_unsolved_render_vlm", + "module": "computation", + "tag": "color" + }, + { + "name": "computation::computation_new_game_layout_vlm", + "module": "computation", + "tag": "content" + }, + { + "name": "computation::computation_keen_grid_4x4_vlm", + "module": "computation", + "tag": "size" + }, + { + "name": "computation::computation_keen_grid_6x6_vlm", + "module": "computation", + "tag": "size" + }, + { + "name": "computation::computation_keen_digit_entry_vlm", + "module": "computation", + "tag": "content" + }, + { + "name": "computation::computation_keen_clue_render_vlm", + "module": "computation", + "tag": "content" + }, + { + "name": "interaction::interaction_star_toggle_to_starred_vlm", + "module": "interaction", + "tag": "shape" + }, + { + "name": "interaction::interaction_star_toggle_to_others_vlm", + "module": "interaction", + "tag": "position" + }, + { + "name": "interaction::interaction_star_multi_record_vlm", + "module": "interaction", + "tag": "position" + }, + { + "name": "interaction::interaction_star_persists_death_vlm", + "module": "interaction", + "tag": "position" + }, + { + "name": "interaction::interaction_net_solution_undo_redo_solved_vlm", + "module": "interaction", + "tag": "color" + }, + { + "name": "interaction::interaction_net_solution_undo_redo_unsolved_vlm", + "module": "interaction", + "tag": "color" + }, + { + "name": "interaction::interaction_net_tile_tap_vlm", + "module": "interaction", + "tag": "shape" + }, + { + "name": "interaction::interaction_keen_digit_shown_vlm", + "module": "interaction", + "tag": "content" + }, + { + "name": "interaction::interaction_keen_digit_cleared_vlm", + "module": "interaction", + "tag": "content" + }, + { + "name": "navigation::nav_reach_gameplay_vlm", + "module": "navigation", + "tag": "content" + }, + { + "name": "navigation::nav_reach_settings_chooser_vlm", + "module": "navigation", + "tag": "layout" + }, + { + "name": "navigation::nav_reach_help_vlm", + "module": "navigation", + "tag": "content" + }, + { + "name": "navigation::nav_reach_custom_dialog_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_type_menu_open_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_gameplay_toolbar_back_vlm", + "module": "navigation", + "tag": "shape" + }, + { + "name": "navigation::nav_back_to_chooser_list_vlm", + "module": "navigation", + "tag": "layout" + }, + { + "name": "states::states_net_radio_dot_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_net_radio_gridsize_vlm", + "module": "states", + "tag": "size" + }, + { + "name": "states::states_type_menu_selected_vlm", + "module": "states", + "tag": "position" + }, + { + "name": "states::states_keen_radio_dot_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_switch_arrow_on_vlm", + "module": "states", + "tag": "position" + }, + { + "name": "states::states_switch_highlight_off_vlm", + "module": "states", + "tag": "position" + }, + { + "name": "structure::structure_gate_launch_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_chooser_sections_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_gameplay_surface_vlm", + "module": "structure", + "tag": "shape" + }, + { + "name": "structure::structure_type_menu_shape_vlm", + "module": "structure", + "tag": "shape" + }, + { + "name": "structure::structure_game_menu_shape_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_keen_digit_buttons_vlm", + "module": "structure", + "tag": "layout" + }, + { + "name": "structure::structure_custom_dialog_shape_vlm", + "module": "structure", + "tag": "shape" + }, + { + "name": "structure::structure_settings_surface_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "text::text_help_webview_vlm", + "module": "text", + "tag": "content" + }, + { + "name": "text::text_keen_canvas_clues_vlm", + "module": "text", + "tag": "content" + } + ], + "vlm_total": 42, + "n_vlm_unverified": 0, + "vlm_log_found": true +} \ No newline at end of file diff --git a/android/chrisboyle-sgtpuzzles/vlm_assertions.json b/android/chrisboyle-sgtpuzzles/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..619119cb0bcd030ffeb38f2e090f8b585928da82 --- /dev/null +++ b/android/chrisboyle-sgtpuzzles/vlm_assertions.json @@ -0,0 +1,954 @@ +{ + "schema_version": 2, + "instance_id": "android/chrisboyle-sgtpuzzles", + "grading": { + "mode": "inline", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 49, + "with_verdict": 42, + "calibrated": 0, + "usable": null, + "scored_records": 42, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "structure_gate_launch_vlm", + "screenshot": "structure_gate_launch_vlm.png", + "assertion": "Is this a list/grid of puzzle entries where each row on the left shows a small COLORFUL icon thumbnail (not a plain monochrome icon)?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "structure_gate_launch", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_chooser_sections_vlm", + "screenshot": "structure_chooser_sections_vlm.png", + "assertion": "Are there two section headings, one reading 'Starred' and one reading 'Others', with the 'Starred' heading positioned ABOVE the 'Others' heading?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_chooser_sections", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_gameplay_surface_vlm", + "screenshot": "structure_gameplay_surface_vlm.png", + "assertion": "Is there a single square puzzle grid outlined by a RED border, occupying the center of the screen?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "structure_gameplay_surface", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_gameplay_toolbar_vlm", + "screenshot": "structure_gameplay_toolbar_vlm.png", + "assertion": "In the top toolbar, is there a back/left-arrow icon at the FAR LEFT and exactly three icon buttons grouped at the RIGHT end?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_gameplay_toolbar", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "structure_type_menu_shape_vlm", + "screenshot": "structure_type_menu_shape_vlm.png", + "assertion": "Is a vertical list of radio-button options shown where exactly ONE circle is filled/selected and the rest are empty circles?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "structure_type_menu_shape", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_game_menu_shape_vlm", + "screenshot": "structure_game_menu_shape_vlm.png", + "assertion": "Is a popup menu shown as a vertical list of items where each item has a small icon positioned to the LEFT of its text label?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_game_menu_shape", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_keen_digit_buttons_vlm", + "screenshot": "structure_keen_digit_buttons_vlm.png", + "assertion": "Along the bottom of the screen, is there a horizontal row of number buttons showing the digits 1, 2, 3, 4, 5 and 6?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "structure_keen_digit_buttons", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_custom_dialog_shape_vlm", + "screenshot": "structure_custom_dialog_shape_vlm.png", + "assertion": "Is a configuration dialog box shown that contains a single-line text input field with a short number in it, next to a label?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "structure_custom_dialog_shape", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_settings_surface_vlm", + "screenshot": "structure_settings_surface_vlm.png", + "assertion": "Is this a settings screen where at least two rows have an ON/OFF toggle switch positioned at the RIGHT edge of the row?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_settings_surface", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_gameplay_vlm", + "screenshot": "nav_reach_gameplay_vlm.png", + "assertion": "Is a single square puzzle grid drawn in the center of the screen (a game board), rather than a vertical list of text rows?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "nav_reach_gameplay", + "rigor": { + "jump_kind": "reach", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_settings_chooser_vlm", + "screenshot": "nav_reach_settings_chooser_vlm.png", + "assertion": "Is this a settings screen showing a vertical scrollable list of labelled rows, at least two of which have an ON/OFF toggle switch?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "nav_reach_settings_chooser", + "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": "Does the screen show a page of readable help/documentation text (paragraphs or a list of topic links), like a web help page?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "nav_reach_help", + "rigor": { + "jump_kind": "reach", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_custom_dialog_vlm", + "screenshot": "nav_reach_custom_dialog_vlm.png", + "assertion": "Is a configuration dialog box shown centered on the screen, overlaying the game behind it, with an 'OK' button inside it?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_reach_custom_dialog", + "rigor": { + "jump_kind": "reach", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_type_menu_open_vlm", + "screenshot": "nav_type_menu_open_vlm.png", + "assertion": "Is a vertical list of selectable size/preset options shown as a popup, each row with a radio-button circle at its left?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_type_menu_open", + "rigor": { + "jump_kind": "reach", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_gameplay_toolbar_back_vlm", + "screenshot": "nav_gameplay_toolbar_back_vlm.png", + "assertion": "At the very top-left of the screen, is there a left-pointing arrow (a back/up navigation arrow) in the toolbar?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "nav_gameplay_toolbar_back", + "rigor": { + "jump_kind": "reach", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_back_to_chooser_list_vlm", + "screenshot": "nav_back_to_chooser_list_vlm.png", + "assertion": "Is a vertical list/grid of puzzle rows shown (each row a small icon beside a line of text), rather than a single centered game board?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "nav_back_to_chooser_list", + "rigor": { + "jump_kind": "reach", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_star_toggle_to_starred_vlm", + "screenshot": "interaction_star_toggle_to_starred_vlm.png", + "assertion": "In the 'Starred' section near the top, is there a row for a puzzle that shows a small STAR icon/badge next to its thumbnail?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "interaction_star_toggle_to_starred", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_star_toggle_to_others_vlm", + "screenshot": "interaction_star_toggle_to_others_vlm.png", + "assertion": "Below the 'Others' heading, is there at least one puzzle row whose thumbnail has NO star badge on it?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "interaction_star_toggle_to_others", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_star_multi_record_vlm", + "screenshot": "interaction_star_multi_record_vlm.png", + "assertion": "Directly under the 'Starred' heading at the top, are there several puzzle rows each showing a star badge on its thumbnail (more than one starred row)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "interaction_star_multi_record", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_star_persists_death_vlm", + "screenshot": "interaction_star_persists_death_vlm.png", + "assertion": "Under the 'Starred' heading at the top of the list, is there a puzzle row with a star badge on its thumbnail?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "interaction_star_persists_death", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_net_solution_undo_redo_solved_vlm", + "screenshot": "interaction_net_solution_undo_redo_solved_vlm.png", + "assertion": "Is the puzzle grid drawn in a solved/complete state — the tiles connected with lit wires and NO red warning border around the grid?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "interaction_net_solution_undo_redo_solved", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_net_solution_undo_redo_unsolved_vlm", + "screenshot": "interaction_net_solution_undo_redo_unsolved_vlm.png", + "assertion": "Is the puzzle grid drawn with a RED border around it (an unsolved / in-progress state), rather than an all-connected solved look?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "interaction_net_solution_undo_redo_unsolved", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_net_tile_tap_vlm", + "screenshot": "interaction_net_tile_tap_vlm.png", + "assertion": "Does the grid show puzzle tiles with short wire/line segments drawn on them at various orientations (as if one was just rotated), rather than an empty featureless grid?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "interaction_net_tile_tap", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_keen_digit_shown_vlm", + "screenshot": "interaction_keen_digit_shown_vlm.png", + "assertion": "Is the digit '3' displayed inside one of the grid cells (a large coloured number entered in a cell), not just in the number buttons along the bottom?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "interaction_keen_digit_shown", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_keen_digit_cleared_vlm", + "screenshot": "interaction_keen_digit_cleared_vlm.png", + "assertion": "After clearing, is the previously highlighted grid cell now EMPTY (no large entered digit inside it, only the small arithmetic clue)?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "interaction_keen_digit_cleared", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_net_grid_5x5_vlm", + "screenshot": "computation_net_grid_5x5_vlm.png", + "assertion": "Is the puzzle board a square grid of exactly 5 columns by 5 rows (25 cells), outlined by a red border?", + "form": "question", + "expected": true, + "aspect": "size", + "modality": null, + "links_to": "computation_net_grid_5x5", + "rigor": { + "jump_kind": "value", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_net_grid_7x7_vlm", + "screenshot": "computation_net_grid_7x7_vlm.png", + "assertion": "Is the puzzle board a square grid of about 7 columns by 7 rows (roughly 49 cells), finer than a 5x5 grid, outlined by a red border?", + "form": "question", + "expected": true, + "aspect": "size", + "modality": null, + "links_to": "computation_net_grid_7x7", + "rigor": { + "jump_kind": "value", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_net_grid_9x9_vlm", + "screenshot": "computation_net_grid_9x9_vlm.png", + "assertion": "Is the puzzle board a large dense square grid of about 9 columns by 9 rows (roughly 80 small cells), clearly finer than a simple 5x5 grid?", + "form": "question", + "expected": true, + "aspect": "size", + "modality": null, + "links_to": "computation_net_grid_9x9", + "rigor": { + "jump_kind": "value", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_solved_render_vlm", + "screenshot": "computation_solved_render_vlm.png", + "assertion": "In the puzzle grid, are the small square endpoint tiles lit up bright CYAN/turquoise and joined together by cyan lines (a solved, fully-connected network), rather than dark blue and disconnected?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "computation_solved_render", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_unsolved_render_vlm", + "screenshot": "computation_unsolved_render_vlm.png", + "assertion": "In the puzzle grid, are most of the small square endpoint tiles a dark BLUE colour (unlit / not connected), rather than all lit bright cyan?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "computation_unsolved_render", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_new_game_layout_vlm", + "screenshot": "computation_new_game_layout_vlm.png", + "assertion": "Does the 5x5 grid show blue endpoint tiles and short black wire/line segments arranged across the cells (a freshly generated network puzzle), rather than an empty featureless grid?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "computation_new_game_layout", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_keen_grid_4x4_vlm", + "screenshot": "computation_keen_grid_4x4_vlm.png", + "assertion": "Is the Keen board a square grid of exactly 4 columns by 4 rows (16 cells), with small arithmetic clues like '7+' or '2÷' printed in the top-left of some cages?", + "form": "question", + "expected": true, + "aspect": "size", + "modality": null, + "links_to": "computation_keen_grid_4x4", + "rigor": { + "jump_kind": "value", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_keen_grid_6x6_vlm", + "screenshot": "computation_keen_grid_6x6_vlm.png", + "assertion": "Is the Keen board a square grid of exactly 6 columns by 6 rows (36 cells), clearly finer/denser than a 4x4 grid?", + "form": "question", + "expected": true, + "aspect": "size", + "modality": null, + "links_to": "computation_keen_grid_6x6", + "rigor": { + "jump_kind": "value", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_keen_digit_entry_vlm", + "screenshot": "computation_keen_digit_entry_vlm.png", + "assertion": "Is the digit '3' displayed as a large coloured number inside one of the grid cells (an entered value in a cell), not merely on the number buttons along the bottom of the screen?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "computation_keen_digit_entry", + "rigor": { + "jump_kind": "value", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_keen_clue_render_vlm", + "screenshot": "computation_keen_clue_render_vlm.png", + "assertion": "In the top-left corner of some cages, are there small arithmetic clues made of a number and an operator (like '5+', '2÷', '30×' or '3-')?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "computation_keen_clue_render", + "rigor": { + "jump_kind": "value", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_net_radio_dot_vlm", + "screenshot": "states_net_radio_dot_vlm.png", + "assertion": "In this vertical list of size presets, does exactly ONE row have a filled/solid radio-button dot on its right side while all the other rows show empty (hollow) radio circles?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_net_radio_dot", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_net_radio_gridsize_vlm", + "screenshot": "states_net_radio_gridsize_vlm.png", + "assertion": "Is the puzzle grid a fairly dense square grid of many small cells (about 9 by 9), rather than a coarse grid of only a few large cells?", + "form": "question", + "expected": true, + "aspect": "size", + "modality": null, + "links_to": "states_net_radio_gridsize", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_type_menu_selected_vlm", + "screenshot": "states_type_menu_selected_vlm.png", + "assertion": "In this list of puzzle sizes, is the single selected size marked by a filled radio dot positioned at the far RIGHT of its row (in line with that size's text label)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "states_type_menu_selected", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_keen_radio_dot_vlm", + "screenshot": "states_keen_radio_dot_vlm.png", + "assertion": "In this list of Keen difficulty presets, does exactly ONE row show a filled/solid radio dot while the other rows show empty circles?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_keen_radio_dot", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_switch_arrow_on_vlm", + "screenshot": "states_switch_arrow_on_vlm.png", + "assertion": "For the 'Show arrow keys' row, is its toggle switch in the ON position, with the round thumb slid to the RIGHT end of the track?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "states_switch_arrow_on", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_switch_highlight_off_vlm", + "screenshot": "states_switch_highlight_off_vlm.png", + "assertion": "For the 'Highlight loops involving unlocked squares' row, is its toggle switch in the OFF position, with the round thumb at the LEFT end of a grey track?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "states_switch_highlight_off", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_arrow_keys_persists_vlm", + "screenshot": "states_arrow_keys_persists_vlm.png", + "assertion": "For the 'Show arrow keys' row, is its toggle switch in the ON position (thumb slid to the RIGHT) after the app was restarted?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "states_arrow_keys_persists", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_arrow_icons_on_vlm", + "screenshot": "states_arrow_icons_on_vlm.png", + "assertion": "In the row of control buttons at the bottom of the screen, are there four directional ARROW buttons (pointing up, down, left and right)?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_arrow_icons_on", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_arrow_icons_off_vlm", + "screenshot": "states_arrow_icons_off_vlm.png", + "assertion": "In the row of control buttons at the bottom of the screen, are there NO directional arrow buttons (no up/down/left/right arrows shown)?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "states_arrow_icons_off", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_custom_checkbox_vlm", + "screenshot": "states_custom_checkbox_vlm.png", + "assertion": "In this configuration dialog, does the checkbox next to the 'Multiplication only' label now show a tick/check mark inside it (a checked box), rather than an empty square?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_custom_checkbox", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_redo_enabled_vlm", + "screenshot": "states_redo_enabled_vlm.png", + "assertion": "In the bottom control bar, is the 'Redo' button drawn at full brightness (a solid, active-looking icon) rather than greyed-out or dimmed?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_redo_enabled", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "states_settings_mixed_switches_vlm", + "screenshot": "states_settings_mixed_switches_vlm.png", + "assertion": "In this settings list, are MULTIPLE toggle switches visible at the same time, with at least one switch clearly ON (coloured track, thumb on the right) AND at least one clearly OFF (grey track, thumb on the left)?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_settings_mixed_switches", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "text_help_webview_vlm", + "screenshot": "text_help_webview_vlm.png", + "assertion": "This is a Help page rendered in a WebView. Near the TOP of the page, is there a row of blue underlined navigation links that includes the words 'Contents', 'Index' and 'Next', above a large heading that contains the puzzle name 'Net'?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "text_help_webview", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_keen_canvas_clues_vlm", + "screenshot": "text_keen_canvas_clues_vlm.png", + "assertion": "Inside the square Keen puzzle grid, are there small arithmetic clue labels printed in the top-left corners of some cells — each a number immediately followed by an operator such as '+', '×' (multiply), '÷' (divide) or '−' (minus), for example '30×', '2÷' or '6+'?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "text_keen_canvas_clues", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + } + ], + "merged_from_files": 1, + "source_shapes": { + "list": 1 + } +} \ No newline at end of file diff --git a/android/cyb3rko-flashdim/LICENSE b/android/cyb3rko-flashdim/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/android/cyb3rko-flashdim/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/android/cyb3rko-flashdim/instance.json b/android/cyb3rko-flashdim/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..f059f0ec69018d0e35d6f7497111a0ddd78f83ca --- /dev/null +++ b/android/cyb3rko-flashdim/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "android/cyb3rko-flashdim", + "platform": "android", + "repo": "https://github.com/cyb3rko/flashdim", + "commit": "d77be03215acd7e124dea34d5a11649dd2a467c7", + "patches": [], + "package": "com.cyb3rko.flashdim.dev", + "license": null +} diff --git a/android/cyb3rko-flashdim/reference/launch.sh b/android/cyb3rko-flashdim/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8 --- /dev/null +++ b/android/cyb3rko-flashdim/reference/launch.sh @@ -0,0 +1,9 @@ +#!/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 1 diff --git a/android/cyb3rko-flashdim/tests/android_computation_eval.json b/android/cyb3rko-flashdim/tests/android_computation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..925242f48c59ab34f4f8ad51c8f1b96a08743e17 --- /dev/null +++ b/android/cyb3rko-flashdim/tests/android_computation_eval.json @@ -0,0 +1,188 @@ +{ + "module": "computation", + "total": 17, + "passed": 17, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 14, + "passed": 14, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 3, + "passed": 3, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.2143, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 17, + "depth_ge1": 3, + "depth_ge2": 3, + "value": 17, + "vlm_fine": 3 + }, + "results": [ + { + "test": "computation_max_button", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "indicator == '10 / 10'" + }, + { + "test": "computation_half_button", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "indicator == '5 / 10' (max//2)" + }, + { + "test": "computation_min_button", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "indicator == '1 / 10'" + }, + { + "test": "computation_off_button", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "indicator == '0 / 10'" + }, + { + "test": "computation_seek_top_max", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "indicator == '10 / 10'" + }, + { + "test": "computation_seek_top_max_vlm", + "passed": true, + "message": "VLM: Q='In this flashlight app, the vertical segmented bar on the right side is at its maximum level. Are ALL of its segments (roughly ten stacked bars, top to bottom) filled/highlighted in the bright accent color rather than dark gray?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In this flashlight app, the vertical segmented bar on the right side is at its maximum level. Are ALL of its segments (roughly ten stacked bars, top to bottom) filled/highlighted in the bright accent color rather than dark gray?", + "tag": "color" + }, + { + "test": "computation_seek_mid_half", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "indicator == '5 / 10'" + }, + { + "test": "computation_seek_mid_half_vlm", + "passed": true, + "message": "VLM: Q='In this flashlight app, the vertical segmented bar on the right is set to roughly half. Is the bar filled/highlighted from the BOTTOM up to about the MIDDLE (about half of the stacked segments bright, the upper half dark)?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In this flashlight app, the vertical segmented bar on the right is set to roughly half. Is the bar filled/highlighted from the BOTTOM up to about the MIDDLE (about half of the stacked segments bright, the upper half dark)?", + "tag": "position" + }, + { + "test": "computation_seek_low_one", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "indicator == '1 / 10'" + }, + { + "test": "computation_seek_low_one_vlm", + "passed": true, + "message": "VLM: Q='In this flashlight app, the vertical segmented bar on the right is set to its lowest non-zero level. Is ONLY the single bottom segment highlighted in the bright accent color while all segments above it are dark gray?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In this flashlight app, the vertical segmented bar on the right is set to its lowest non-zero level. Is ONLY the single bottom segment highlighted in the bright accent color while all segments above it are dark gray?", + "tag": "color" + }, + { + "test": "computation_seek_bottom_zero", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "indicator == '0 / 10'" + }, + { + "test": "computation_seek_frac_seven", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "indicator == '7 / 10'" + }, + { + "test": "computation_seek_frac_three", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "indicator == '3 / 10'" + }, + { + "test": "computation_seek_monotonic", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "level decreases top->bottom (got 10>5>1)" + }, + { + "test": "computation_pref_slider_low", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "dialog shows 'New: 3'" + }, + { + "test": "computation_pref_slider_high", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "dialog shows 'New: 8'" + }, + { + "test": "computation_pref_slider_monotonic", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "New increases with position (got 3 < 8)" + } + ] +} \ No newline at end of file diff --git a/android/cyb3rko-flashdim/tests/android_interaction_eval.json b/android/cyb3rko-flashdim/tests/android_interaction_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..cf35190ec9782066464a566bde2accef4f4b29bc --- /dev/null +++ b/android/cyb3rko-flashdim/tests/android_interaction_eval.json @@ -0,0 +1,182 @@ +{ + "module": "interaction", + "total": 16, + "passed": 16, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 10, + "passed": 10, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 6, + "passed": 6, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.6, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 16, + "depth_ge1": 7, + "depth_ge2": 1, + "value": 2, + "vlm_fine": 4 + }, + "results": [ + { + "test": "interaction_seq_max_half_min_off", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Max->Half->Min->Off = '10 / 10'->'5 / 10'->'1 / 10'->'0 / 10' (final '0 / 10')" + }, + { + "test": "interaction_seq_toggle_through", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Off->Max->Off->Half = '0 / 10'->'10 / 10'->'0 / 10'->'5 / 10' (final '5 / 10')" + }, + { + "test": "interaction_seq_min_then_max_override", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Min='1 / 10' then Max overrides to '10 / 10'" + }, + { + "test": "interaction_button_seekbar_same_state", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Max='10 / 10', Min='1 / 10', seekbar-top back to '10 / 10' (shared state)" + }, + { + "test": "interaction_button_seekbar_same_state_vlm", + "passed": true, + "message": "VLM: Q='Is the vertical segmented bar completely filled (all ~10 segments highlighted) and does the level read 10 / 10?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is the vertical segmented bar completely filled (all ~10 segments highlighted) and does the level read 10 / 10?", + "tag": "shape" + }, + { + "test": "interaction_seekbar_min_fill_vlm", + "passed": true, + "message": "VLM: Q='Is only the bottom-most segment of the vertical bar highlighted while the rest are dark?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is only the bottom-most segment of the vertical bar highlighted while the rest are dark?", + "tag": "shape" + }, + { + "test": "interaction_seekbar_mid_fill_vlm", + "passed": true, + "message": "VLM: Q='Is the vertical segmented bar filled about halfway from the bottom (roughly the lower half of the segments highlighted, the upper half dark)?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is the vertical segmented bar filled about halfway from the bottom (roughly the lower half of the segments highlighted, the upper half dark)?", + "tag": "shape" + }, + { + "test": "interaction_sos_enter_exit_vlm", + "passed": true, + "message": "VLM: Q='Have the Maximum/Half/Minimum buttons disappeared, leaving only SOS and Off in the left column?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Have the Maximum/Half/Minimum buttons disappeared, leaving only SOS and Off in the left column?", + "tag": "position" + }, + { + "test": "interaction_sos_enter_exit", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "SOS enter: li='SOS mode', qa startswith 'Morse:', buttons hidden, sos+seek disabled; Off exit restores li='0 / 10', qa='Quick Actions', buttons back" + }, + { + "test": "interaction_morse_dialog_flow_vlm", + "passed": true, + "message": "VLM: Q='Is a dialog with a single-line text input field (hint about a message) and a 'Flash' button visible on screen?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is a dialog with a single-line text input field (hint about a message) and a 'Flash' button visible on screen?", + "tag": "layout" + }, + { + "test": "interaction_morse_dialog_flow", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "empty Flash keeps dialog open with error 'Please enter your message'; typed 'A' + Flash dismisses the dialog" + }, + { + "test": "interaction_interval_mode_roundtrip_vlm", + "passed": true, + "message": "VLM: Q='Does the numeric input show 100 with no 'ms' suffix beside it?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Does the numeric input show 100 with no 'ms' suffix beside it?", + "tag": "content" + }, + { + "test": "interaction_interval_mode_roundtrip", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "TIME('500','ms') -> BPM('100',no suffix) -> TIME('500','ms') round-trip" + }, + { + "test": "interaction_context_awareness_persists", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "'Context awareness' OFF->ON then survives force_stop_and_relaunch (checked=true)" + }, + { + "test": "interaction_preferred_level_dialog_live_value", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "dialog 'New:' 10 -> '2' after tapping the slider track at fraction 0.2" + }, + { + "test": "interaction_preferred_level_persists", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "'Preferred level' summary ends ': 2' both before and after force_stop_and_relaunch (and not the default ': 10')" + } + ] +} \ No newline at end of file diff --git a/android/cyb3rko-flashdim/tests/android_navigation_eval.json b/android/cyb3rko-flashdim/tests/android_navigation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..de048839753b12b27ce2e3d7d344efd79a807e6a --- /dev/null +++ b/android/cyb3rko-flashdim/tests/android_navigation_eval.json @@ -0,0 +1,236 @@ +{ + "module": "navigation", + "total": 22, + "passed": 22, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 16, + "passed": 16, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 6, + "passed": 6, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.375, + "audit": { + "kit_api_version": 1, + "existence": 6, + "liveness": 0, + "interactive": 16, + "depth_ge1": 16, + "depth_ge2": 5, + "value": 0, + "vlm_fine": 4 + }, + "results": [ + { + "test": "nav_reach_morse", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "'Flash morse code' dialog title visible; home 'Off' button gone" + }, + { + "test": "nav_reach_morse_vlm", + "passed": true, + "message": "VLM: Q='Is a dialog titled 'Flash morse code' shown with a single-line text input field above a 'Flash' button?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a dialog titled 'Flash morse code' shown with a single-line text input field above a 'Flash' button?", + "tag": "layout" + }, + { + "test": "nav_reach_interval", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "'Interval Flash' dialog title visible; home 'Off' button gone" + }, + { + "test": "nav_reach_interval_probe", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "'Interval Flash' dialog reached for screenshot" + }, + { + "test": "nav_reach_interval_vlm", + "passed": true, + "message": "VLM: Q='Is a dialog shown with two side-by-side radio toggles labelled 'TIME' and 'BPM' and a numeric input field?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a dialog shown with two side-by-side radio toggles labelled 'TIME' and 'BPM' and a numeric input field?", + "tag": "position" + }, + { + "test": "nav_reach_links", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "'Repository on GitHub' row visible; home 'Off' button gone" + }, + { + "test": "nav_reach_links_vlm", + "passed": true, + "message": "VLM: Q='Is a dialog titled 'Links' shown listing several rows, each row having a button labelled 'Visit' on its right side?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a dialog titled 'Links' shown listing several rows, each row having a button labelled 'Visit' on its right side?", + "tag": "position" + }, + { + "test": "nav_reach_about", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "'Show Icon Credits' button visible; home 'Off' button gone" + }, + { + "test": "nav_reach_settings", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "'Flashlight controls' category visible in SettingsActivity; home 'Quick Actions' label gone" + }, + { + "test": "nav_reach_settings_vlm", + "passed": true, + "message": "VLM: Q='Is a settings screen shown as a vertical scrollable list of labelled rows, several rows having an on/off toggle switch on the right, with a back arrow at the top-left?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a settings screen shown as a vertical scrollable list of labelled rows, several rows having an on/off toggle switch on the right, with a back arrow at the top-left?", + "tag": "position" + }, + { + "test": "nav_reach_icon_credits_d2", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "'Open Pictogrammers' button visible; 'Show Icon Credits' gone (home -> About -> Icon Credits)" + }, + { + "test": "nav_reach_icon_credits_d2_vlm", + "passed": true, + "message": "VLM: Q='Is a dialog titled 'Icon Credits' shown, listing icon credit lines and a button reading 'Open Pictogrammers'?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a dialog titled 'Icon Credits' shown, listing icon credit lines and a button reading 'Open Pictogrammers'?", + "tag": "content" + }, + { + "test": "nav_reach_preferred_level_d2", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "'Set preferred level' dialog visible; 'Context awareness' row gone (home -> Settings -> preferred-level dialog)" + }, + { + "test": "nav_reach_preferred_level_d2_vlm", + "passed": true, + "message": "VLM: Q='In the centered pop-up dialog, is there a wide horizontal light-purple / lavender bar with a row of small evenly-spaced dots along it?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the centered pop-up dialog, is there a wide horizontal light-purple / lavender bar with a row of small evenly-spaced dots along it?", + "tag": "shape" + }, + { + "test": "nav_reach_settings_links_d2", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "'Repository on GitHub' visible; 'Flashlight controls' category gone (home -> Settings -> Links)" + }, + { + "test": "nav_back_morse_to_home", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "home 'Off' button + 'Quick Actions' restored after one BACK" + }, + { + "test": "nav_back_settings_to_home", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "MainActivity home restored (Off visible) after one BACK from Settings" + }, + { + "test": "nav_up_arrow_settings_to_home", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "MainActivity home restored after tapping the 'Navigate up' arrow" + }, + { + "test": "nav_backstack_icon_credits_unwinds", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "one BACK from Icon Credits (depth 2) restores home ('Off' + 'Quick Actions'); 'Open Pictogrammers' gone" + }, + { + "test": "nav_backstack_preferred_level_unwinds", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "BACK #1 restores Settings ('Context awareness'); BACK #2 restores home MainActivity ('Off')" + }, + { + "test": "nav_back_links_to_home", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "home 'Off' + 'Quick Actions' restored after one BACK from Links" + }, + { + "test": "nav_back_about_to_home", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "home 'Off' + 'Quick Actions' restored after one BACK from About" + } + ] +} \ No newline at end of file diff --git a/android/cyb3rko-flashdim/tests/android_states_eval.json b/android/cyb3rko-flashdim/tests/android_states_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..033c3c6048221e04b13aa0540c0e6027dc912192 --- /dev/null +++ b/android/cyb3rko-flashdim/tests/android_states_eval.json @@ -0,0 +1,269 @@ +{ + "module": "states", + "total": 25, + "passed": 25, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 13, + "passed": 13, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 12, + "passed": 12, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.9231, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 25, + "depth_ge1": 15, + "depth_ge2": 0, + "value": 0, + "vlm_fine": 12 + }, + "results": [ + { + "test": "states_instant_flash_toggle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "checked false->true" + }, + { + "test": "states_switch_on_visual_vlm", + "passed": true, + "message": "VLM: Q='In the settings list, is the toggle switch on the 'Instant flash' row in the ON position — its thumb pushed to the RIGHT with a filled/coloured track (not grey)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In the settings list, is the toggle switch on the 'Instant flash' row in the ON position — its thumb pushed to the RIGHT with a filled/coloured track (not grey)?", + "tag": "position" + }, + { + "test": "states_context_awareness_toggle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "checked false->true" + }, + { + "test": "states_switch_off_visual_vlm", + "passed": true, + "message": "VLM: Q='Look at the 'Quick settings toggle link' row's toggle switch: is it in the OFF position — thumb to the LEFT over a grey/uncoloured track?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Look at the 'Quick settings toggle link' row's toggle switch: is it in the OFF position — thumb to the LEFT over a grey/uncoloured track?", + "tag": "position" + }, + { + "test": "states_toggle_mode_off", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "checked true->false" + }, + { + "test": "states_extension_disabled_visual_vlm", + "passed": true, + "message": "VLM: Q='Does the 'Instant flash extension' row (its title, summary and toggle) appear greyed-out / dimmed compared to the fully-black rows above and below it, indicating it is disabled?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Does the 'Instant flash extension' row (its title, summary and toggle) appear greyed-out / dimmed compared to the fully-black rows above and below it, indicating it is disabled?", + "tag": "color" + }, + { + "test": "states_extension_enabled_by_instant", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "extension enabled false->true" + }, + { + "test": "states_toggle_link_disabled_by_mode", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "link enabled true->false" + }, + { + "test": "states_context_awareness_persists", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "checked stays true after relaunch" + }, + { + "test": "states_instant_flash_persists", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "checked stays true after relaunch" + }, + { + "test": "states_sos_enter_disables_controls", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "sos enabled true->false; seek disabled; mid buttons gone" + }, + { + "test": "states_sos_buttons_gone_vlm", + "passed": true, + "message": "VLM: Q='Are the 'Maximum', 'Half' and 'Minimum' brightness buttons NO LONGER visible, leaving only the 'SOS' and 'Off' buttons in the button area?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Are the 'Maximum', 'Half' and 'Minimum' brightness buttons NO LONGER visible, leaving only the 'SOS' and 'Off' buttons in the button area?", + "tag": "shape" + }, + { + "test": "states_sos_greyed_vlm", + "passed": true, + "message": "VLM: Q='Is the 'SOS' button visibly greyed-out / dimmed (disabled) while the 'Off' button remains fully coloured and active?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is the 'SOS' button visibly greyed-out / dimmed (disabled) while the 'Off' button remains fully coloured and active?", + "tag": "color" + }, + { + "test": "states_sos_exit_restores_controls", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "sos enabled false->true; seek enabled; mid buttons back; level '0 / 10'" + }, + { + "test": "states_sos_level_indicator", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "numeric readout -> 'SOS mode' -> numeric readout" + }, + { + "test": "states_interval_time_selected_vlm", + "passed": true, + "message": "VLM: Q='In this dialog with 'TIME' and 'BPM' radio options, is 'TIME' the selected one — its radio circle filled/coloured — while 'BPM' is unfilled?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In this dialog with 'TIME' and 'BPM' radio options, is 'TIME' the selected one — its radio circle filled/coloured — while 'BPM' is unfilled?", + "tag": "shape" + }, + { + "test": "states_interval_radio_bpm", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "BPM checked true, TIME false; input 500->100, 'ms' suffix gone" + }, + { + "test": "states_interval_bpm_selected_vlm", + "passed": true, + "message": "VLM: Q='Now is 'BPM' the selected radio option — its circle filled/coloured — while 'TIME' is unfilled?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Now is 'BPM' the selected radio option — its circle filled/coloured — while 'TIME' is unfilled?", + "tag": "shape" + }, + { + "test": "states_interval_radio_time_restore", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "TIME checked false->true, BPM checked true->false" + }, + { + "test": "states_max_level_fill_vlm", + "passed": true, + "message": "VLM: Q='Look at the vertical segmented brightness bar on the left. Is it COMPLETELY filled — every one of its ~10 segments in the light/highlight colour with none left dark?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Look at the vertical segmented brightness bar on the left. Is it COMPLETELY filled — every one of its ~10 segments in the light/highlight colour with none left dark?", + "tag": "color" + }, + { + "test": "states_min_level_fill_vlm", + "passed": true, + "message": "VLM: Q='Look at the vertical segmented brightness bar. Is ONLY the single bottom segment highlighted/lit while all the segments above it are dark grey?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Look at the vertical segmented brightness bar. Is ONLY the single bottom segment highlighted/lit while all the segments above it are dark grey?", + "tag": "position" + }, + { + "test": "states_half_level_fill_vlm", + "passed": true, + "message": "VLM: Q='Look at the vertical segmented brightness bar. Are roughly the bottom HALF (about 5 of ~10) of its segments highlighted and the top half dark?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Look at the vertical segmented brightness bar. Are roughly the bottom HALF (about 5 of ~10) of its segments highlighted and the top half dark?", + "tag": "size" + }, + { + "test": "states_off_level_fill_vlm", + "passed": true, + "message": "VLM: Q='Look at the vertical segmented brightness bar. Are ALL of its segments dark/unfilled with NONE highlighted?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Look at the vertical segmented brightness bar. Are ALL of its segments dark/unfilled with NONE highlighted?", + "tag": "color" + }, + { + "test": "states_brightness_button_active_vlm", + "passed": true, + "message": "VLM: Q='Do the three brightness buttons 'Maximum', 'Half' and 'Minimum' appear as filled LIGHT-coloured pills, while the 'SOS', 'Morse' and 'Interval' buttons are darker/greyed tonal buttons?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Do the three brightness buttons 'Maximum', 'Half' and 'Minimum' appear as filled LIGHT-coloured pills, while the 'SOS', 'Morse' and 'Interval' buttons are darker/greyed tonal buttons?", + "tag": "color" + }, + { + "test": "states_morse_input_focus", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "message field focused false->true" + } + ] +} \ No newline at end of file diff --git a/android/cyb3rko-flashdim/tests/android_structure_eval.json b/android/cyb3rko-flashdim/tests/android_structure_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..c61f885470c52257bb7001b780bc9a7df3618ae5 --- /dev/null +++ b/android/cyb3rko-flashdim/tests/android_structure_eval.json @@ -0,0 +1,172 @@ +{ + "module": "structure", + "total": 15, + "passed": 15, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 10, + "passed": 10, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 5, + "passed": 5, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.5, + "audit": { + "kit_api_version": 1, + "existence": 7, + "liveness": 0, + "interactive": 8, + "depth_ge1": 7, + "depth_ge2": 0, + "value": 0, + "vlm_fine": 5 + }, + "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_sos_shrinks_buttons", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "visible Button count 10->5 on SOS, restored to 10 on Off" + }, + { + "test": "structure_sos_shrinks_buttons_vlm", + "passed": true, + "message": "VLM: Q='On the LEFT side of this screen, are there exactly two rounded buttons stacked at the top (one labelled 'SOS' and one labelled 'Off'), with empty space below them?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: On the LEFT side of this screen, are there exactly two rounded buttons stacked at the top (one labelled 'SOS' and one labelled 'Off'), with empty space below them?", + "tag": "position" + }, + { + "test": "structure_morse_dialog_editext", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "EditText 0->1 + alertTitle in Morse dialog, restored to 0" + }, + { + "test": "structure_interval_radiobuttons", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "RadioButton 0->2 in Interval dialog, restored to 0" + }, + { + "test": "structure_interval_mode_suffix", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "suffix subtree present in TIME -> absent in BPM -> restored in TIME" + }, + { + "test": "structure_links_dialog_visit_buttons", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "'Visit' button count 0->3 in Links dialog, restored to 0" + }, + { + "test": "structure_about_dialog_appears", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "alertTitle + 2 dialog buttons appear over home, removed on BACK" + }, + { + "test": "structure_settings_shape_flip", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "home button_container gone -> scrollable preference list (19 TextViews) in Settings, container restored on BACK" + }, + { + "test": "structure_settings_switch_rows", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Switch count 0 (home) -> 5 (Settings)" + }, + { + "test": "structure_home_layout_vlm", + "passed": true, + "message": "VLM: Q='Is the screen split into two columns, with a stack of rounded buttons (SOS, Morse, Maximum, Off) filling the LEFT half and a separate column of stacked rounded blocks on the RIGHT half?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is the screen split into two columns, with a stack of rounded buttons (SOS, Morse, Maximum, Off) filling the LEFT half and a separate column of stacked rounded blocks on the RIGHT half?", + "tag": "position" + }, + { + "test": "structure_toolbar_icons_vlm", + "passed": true, + "message": "VLM: Q='Are there three separate icon buttons grouped in the top-right corner of the top app bar (a link/chain icon, a sliders icon, and an info circle icon)?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Are there three separate icon buttons grouped in the top-right corner of the top app bar (a link/chain icon, a sliders icon, and an info circle icon)?", + "tag": "position" + }, + { + "test": "structure_seekbar_segments_vlm", + "passed": true, + "message": "VLM: Q='On the right side of the screen, is there a tall vertical bar that is divided into roughly ten stacked rounded segments?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: On the right side of the screen, is there a tall vertical bar that is divided into roughly ten stacked rounded segments?", + "tag": "shape" + }, + { + "test": "structure_button_pills_vlm", + "passed": true, + "message": "VLM: Q='Are the brightness buttons (Maximum, Half, Minimum, Off) drawn as large rounded pill/capsule shapes stacked vertically in a column?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Are the brightness buttons (Maximum, Half, Minimum, Off) drawn as large rounded pill/capsule shapes stacked vertically in a column?", + "tag": "shape" + } + ] +} \ No newline at end of file diff --git a/android/cyb3rko-flashdim/tests/android_testgen_kit.py b/android/cyb3rko-flashdim/tests/android_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6 --- /dev/null +++ b/android/cyb3rko-flashdim/tests/android_testgen_kit.py @@ -0,0 +1,1910 @@ +#!/usr/bin/env python3 +"""Android TestGen Kit — the single source of every test helper, so a test's +NAVIGATION 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 package +name differs): always use the module-level PACKAGE (argv[1]). Never write a package +name, an .apk path, a /data/data path, or a pixel coordinate as a literal. + python3 android_testgen_kit.py lint_sources # flags all of those + +SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery): + python3 android_testgen_kit.py audit + python3 android_testgen_kit.py lint + python3 android_testgen_kit.py lint_sources + python3 android_testgen_kit.py audit_depth [results_dir] +""" +from __future__ import annotations + +import ast +import base64 +import functools +import glob +import hashlib +import json +import math +import os +import re +import shlex +import subprocess +import sys +import time +import urllib.error +import 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.0 +SETTLE = { + "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 /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 " list[dict]: + """XML -> list of attribute dicts, each with _bounds and _center.""" + nodes = [] + for m in re.finditer(r"]+?)/?>", 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} \n" + " android_testgen_kit.py audit_depth [results_dir]\n" + " android_testgen_kit.py score [manifest_dir]") diff --git a/android/cyb3rko-flashdim/tests/android_text_eval.json b/android/cyb3rko-flashdim/tests/android_text_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..9cf6a10a1c20cc8f06b0fe484b9c53f0ffa51415 --- /dev/null +++ b/android/cyb3rko-flashdim/tests/android_text_eval.json @@ -0,0 +1,223 @@ +{ + "module": "text", + "total": 21, + "passed": 21, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 19, + "passed": 19, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 2, + "passed": 2, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.1053, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 21, + "depth_ge1": 17, + "depth_ge2": 1, + "value": 0, + "vlm_fine": 1 + }, + "results": [ + { + "test": "text_sos_mode_indicator", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "level_indicator text == 'SOS mode'" + }, + { + "test": "text_sos_quick_actions_morse", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "quick_actions_view produced 'Morse:' header with letter 'S ('" + }, + { + "test": "text_quick_actions_restored_off", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "quick_actions_view restored to 'Quick Actions' after Off" + }, + { + "test": "text_indicator_restored_off", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "level_indicator content left 'SOS mode' after Off" + }, + { + "test": "text_morse_error_empty", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "error text == 'Please enter your message'" + }, + { + "test": "text_morse_error_invalid_chars", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "error text == 'Use characters a–z, A–Z, 0–9 and space'" + }, + { + "test": "text_morse_hint_on_open", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "hint text == 'Your Message'" + }, + { + "test": "text_interval_seizure_warning", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "seizure_warning contains 'Seizure Warning' and 'Flashing light'" + }, + { + "test": "text_interval_seizure_warning_vlm", + "passed": true, + "message": "VLM: Q='In this Interval Flash dialog, is there a yellow/orange triangular caution warning icon immediately to the LEFT of the bold words 'Seizure Warning'?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In this Interval Flash dialog, is there a yellow/orange triangular caution warning icon immediately to the LEFT of the bold words 'Seizure Warning'?", + "tag": "shape" + }, + { + "test": "text_interval_suffix_ms_time_mode", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "suffix text == 'ms' in TIME mode, absent after BPM" + }, + { + "test": "text_interval_counter_time_vs_bpm", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "counter text == '3/5' in TIME, '3/3' after BPM" + }, + { + "test": "text_interval_value_not_allowed", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "error text == 'Value not allowed'" + }, + { + "test": "text_about_dialog_title", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "alertTitle text == 'About'" + }, + { + "test": "text_about_dialog_title_vlm", + "passed": true, + "message": "VLM: Q='In this About dialog, is there a multi-line block of device/version information showing labels such as 'Version', 'Model' and 'OS' on separate lines?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In this About dialog, is there a multi-line block of device/version information showing labels such as 'Version', 'Model' and 'OS' on separate lines?", + "tag": "layout" + }, + { + "test": "text_icon_credits_dialog_title", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "second-dialog alertTitle text == 'Icon Credits'" + }, + { + "test": "text_links_dialog_title", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "alertTitle text == 'Links'" + }, + { + "test": "text_links_github_desc", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "github_desc text == 'Repository on GitHub'" + }, + { + "test": "text_links_matrix_desc", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "matrix_desc text == 'Matrix chat room (questions, feedback, discussions)'" + }, + { + "test": "text_settings_preferred_level_summary", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Preferred-level summary contains 'Dim level' and ends ': 10'" + }, + { + "test": "text_settings_about_row_summary", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "about-row summary text == 'by Cyb3rKo'" + }, + { + "test": "text_settings_instant_flash_summary", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "summary text == 'Activate flashlight on app startup'" + } + ] +} \ No newline at end of file diff --git a/android/cyb3rko-flashdim/tests/conftest.py b/android/cyb3rko-flashdim/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27 --- /dev/null +++ b/android/cyb3rko-flashdim/tests/conftest.py @@ -0,0 +1 @@ +pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"] diff --git a/android/cyb3rko-flashdim/tests/requirements.txt b/android/cyb3rko-flashdim/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c --- /dev/null +++ b/android/cyb3rko-flashdim/tests/requirements.txt @@ -0,0 +1,2 @@ +pytest +pillow diff --git a/android/cyb3rko-flashdim/tests/test_android_computation.py b/android/cyb3rko-flashdim/tests/test_android_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf7d89fc49ad0f342c6dc93fa6b6b8cec75c4dd --- /dev/null +++ b/android/cyb3rko-flashdim/tests/test_android_computation.py @@ -0,0 +1,529 @@ +#!/usr/bin/env python3 +"""COMPUTATION-lane behavioral suite for FlashDim (input -> output). + +This lane is the sole owner of jump_kind="value". The app's core function is +setting a flashlight brightness LEVEL; the observable OUTPUT is the +`level_indicator` TextView, formatted " / ". + +Every assertion here is a real INPUT -> OUTPUT computation: + A. tap a level quick-button (Max/Half/Min/Off) -> exact indicator string. + maxLevel is DERIVED at runtime (parsed from the Max result "N / N"), + never hardcoded; the Half test then asserts the app computes max//2. + B. tap the custom vertical seek_bar at a y-fraction -> level = f(position), + asserting the exact indicator string observed live at each fraction. + C. (depth 2) the Settings "Preferred level" slider dialog -> "New: N", + asserting New = f(track fraction). + +All expected values were OBSERVED on the running original app, never computed +from source or a constant. The three VLM records verify the CANVAS-drawn +seekbar FILL (which never reaches the view tree) agrees with the numeric level. +""" +import os +import re +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 + + +# ── Home helpers ──────────────────────────────────────────────────────────── +# restart_app() resumes the app's existing task, and FlashDim's back-stack +# (MainActivity -> SettingsActivity, etc.) survives force-stop, so a raw restart +# can land on Settings. _go_home() backs out until the home surface (identified +# by the level_indicator TextView) is showing. +def _go_home(max_back: int = 6) -> bool: + restart_app() + wait_for_foreground(15) + settle("launch") + for _ in range(max_back): + if node_by_id(ui(), "level_indicator") is not None: + return True + back() + settle("launch") + return node_by_id(ui(), "level_indicator") is not None + + +def _read_indicator() -> str: + """The 'N / M' text out of a FRESH dump.""" + n = node_by_id(ui(), "level_indicator") + return n.get("text", "").strip() if n else "" + + +def _norm(s: str) -> str: + """Collapse whitespace so '10 / 10' and '10 / 10' compare equal.""" + return re.sub(r"\s+", " ", s.strip()) + + +def _parse_pair(s: str): + """'N / M' -> (N, M) ints, or None.""" + m = re.search(r"(\d+)\s*/\s*(\d+)", s) + return (int(m.group(1)), int(m.group(2))) if m else None + + +def _derive_max(): + """Run the app to learn maxLevel: tap Max, the indicator reads 'max / max'. + Returns (max, note). Never assumes 10.""" + if not _go_home(): + return None, "setup_failed: home surface (level_indicator) not reachable" + if not tap_node(node_by_id(ui(), "max_button")): + return None, "setup_failed: max_button not tappable" + pair = _parse_pair(_read_indicator()) + if not pair: + return None, f"setup_failed: could not parse indicator after Max ({_read_indicator()!r})" + lvl, mx = pair + if lvl != mx: + return None, f"behavior_wrong: Max gave '{lvl} / {mx}', expected level==max" + return mx, "" + + +def _seek_bounds(): + """Fresh seek_bar geometry (cx, y1, height) — re-read before EVERY tap + because a state change invalidates coordinates.""" + n = node_by_id(ui(), "seek_bar") + if not n or "_bounds" not in n: + return None + x1, y1, x2, y2 = n["_bounds"] + return (x1 + x2) // 2, y1, y2 - y1 + + +def _seek_to(frac: float) -> str: + """Tap the seek_bar at vertical fraction `frac` (0=top). Returns the + resulting indicator string, or '' if the bar was not found.""" + b = _seek_bounds() + if not b: + return "" + cx, y1, h = b + tap(cx, y1 + round(frac * h)) + return _read_indicator() + + +def _shot(name: str) -> None: + screencap(os.path.join(RESULTS_DIR, "screenshots", f"{name}.png")) + + +# ══════════════════════════════════════════════════════════════════════════════ +# A. Level quick-button -> indicator value (depth 0, jump_kind=value) +# Each test derives maxLevel live, then asserts the exact observed string. +# Positive/negative pairing: the answer is ABSENT (indicator != target) +# before the tap and PRESENT after. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_max_button",)) +def test_max_button(): + mx, note = _derive_max() # _derive_max already taps Max + if mx is None: + record("computation_max_button", False, note, + depth=0, jump_kind="value", expect="' / '") + return + expected = f"{mx} / {mx}" + got = _read_indicator() + ok = _norm(got) == _norm(expected) + record("computation_max_button", ok, + "" if ok else f"behavior_wrong: Max shows {got!r}, expected {expected!r}", + depth=0, jump_kind="value", expect=f"indicator == '{expected}'") + + +@and_test(expects=("computation_half_button",)) +def test_half_button(): + # Real computation: assert the app computes maxLevel // 2 (integer division). + mx, note = _derive_max() + if mx is None: + record("computation_half_button", False, note, + depth=0, jump_kind="value", expect="' / '") + return + before = _read_indicator() # currently 'max / max' from _derive_max + expected = f"{mx // 2} / {mx}" + ok_tap = tap_node(node_by_id(ui(), "half_button")) + got = _read_indicator() + # negative->positive: the half value must have been ABSENT then PRESENT + ok = ok_tap and _norm(got) == _norm(expected) and _norm(before) != _norm(expected) + if not ok_tap: + msg = "setup_failed: half_button not tappable" + elif _norm(got) != _norm(expected): + msg = f"behavior_wrong: Half shows {got!r}, expected {expected!r} (max//2)" + else: + msg = "" + record("computation_half_button", ok, msg, + depth=0, jump_kind="value", expect=f"indicator == '{expected}' (max//2)") + + +@and_test(expects=("computation_min_button",)) +def test_min_button(): + mx, note = _derive_max() + if mx is None: + record("computation_min_button", False, note, + depth=0, jump_kind="value", expect="'1 / '") + return + expected = f"1 / {mx}" + ok_tap = tap_node(node_by_id(ui(), "min_button")) + got = _read_indicator() + ok = ok_tap and _norm(got) == _norm(expected) + msg = ("" if ok else + ("setup_failed: min_button not tappable" if not ok_tap + else f"behavior_wrong: Min shows {got!r}, expected {expected!r}")) + record("computation_min_button", ok, msg, + depth=0, jump_kind="value", expect=f"indicator == '{expected}'") + + +@and_test(expects=("computation_off_button",)) +def test_off_button(): + # Positive/negative: turn the flash ON (Max) first so the '0 / max' answer + # is provably ABSENT, then Off makes it PRESENT. + mx, note = _derive_max() # taps Max -> 'max / max' + if mx is None: + record("computation_off_button", False, note, + depth=0, jump_kind="value", expect="'0 / '") + return + before = _read_indicator() # 'max / max' + expected = f"0 / {mx}" + ok_tap = tap_node(node_by_id(ui(), "off_button")) + got = _read_indicator() + ok = (ok_tap and _norm(got) == _norm(expected) + and _norm(before) != _norm(expected)) + msg = ("" if ok else + ("setup_failed: off_button not tappable" if not ok_tap + else f"behavior_wrong: Off shows {got!r}, expected {expected!r}")) + record("computation_off_button", ok, msg, + depth=0, jump_kind="value", expect=f"indicator == '{expected}'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# B. Seekbar position -> level value (depth 0, jump_kind=value) +# level = f(y-position) on the custom vertical LightLevelSeekBar. +# Fractions and expected strings were OBSERVED live and are deterministic +# across repeated runs. Bounds are re-read before EACH tap. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_seek_top_max", "computation_seek_top_max_vlm")) +def test_seek_top_max(): + if not _go_home(): + record("computation_seek_top_max", False, + "setup_failed: home not reachable", + depth=0, jump_kind="value", expect="' / '") + return + mx = _parse_pair(_read_indicator()) + mx = mx[1] if mx else 10 + got = _seek_to(0.03) # top of the bar -> saturates at max + if not got: + record("computation_seek_top_max", False, + "setup_failed: seek_bar not found", + depth=0, jump_kind="value", expect=f"'{mx} / {mx}'") + return + expected = f"{mx} / {mx}" + ok = _norm(got) == _norm(expected) + record("computation_seek_top_max", ok, + "" if ok else f"behavior_wrong: top tap shows {got!r}, expected {expected!r}", + depth=0, jump_kind="value", expect=f"indicator == '{expected}'") + _shot("computation_seek_top_max_vlm") + vlm_assert("computation_seek_top_max", + "In this flashlight app, the vertical segmented bar on the right " + "side is at its maximum level. Are ALL of its segments (roughly ten " + "stacked bars, top to bottom) filled/highlighted in the bright " + "accent color rather than dark gray?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="color") + + +@and_test(expects=("computation_seek_mid_half", "computation_seek_mid_half_vlm")) +def test_seek_mid_half(): + if not _go_home(): + record("computation_seek_mid_half", False, + "setup_failed: home not reachable", + depth=0, jump_kind="value", expect="' / '") + return + mx = _parse_pair(_read_indicator()) + mx = mx[1] if mx else 10 + got = _seek_to(0.50) # middle -> half + if not got: + record("computation_seek_mid_half", False, + "setup_failed: seek_bar not found", + depth=0, jump_kind="value", expect=f"'{mx // 2} / {mx}'") + return + expected = f"{mx // 2} / {mx}" + ok = _norm(got) == _norm(expected) + record("computation_seek_mid_half", ok, + "" if ok else f"behavior_wrong: middle tap shows {got!r}, expected {expected!r}", + depth=0, jump_kind="value", expect=f"indicator == '{expected}'") + _shot("computation_seek_mid_half_vlm") + vlm_assert("computation_seek_mid_half", + "In this flashlight app, the vertical segmented bar on the right is " + "set to roughly half. Is the bar filled/highlighted from the BOTTOM " + "up to about the MIDDLE (about half of the stacked segments bright, " + "the upper half dark)?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="position") + + +@and_test(expects=("computation_seek_low_one", "computation_seek_low_one_vlm")) +def test_seek_low_one(): + if not _go_home(): + record("computation_seek_low_one", False, + "setup_failed: home not reachable", + depth=0, jump_kind="value", expect="'1 / '") + return + mx = _parse_pair(_read_indicator()) + mx = mx[1] if mx else 10 + got = _seek_to(0.90) # near bottom -> level 1 + if not got: + record("computation_seek_low_one", False, + "setup_failed: seek_bar not found", + depth=0, jump_kind="value", expect=f"'1 / {mx}'") + return + expected = f"1 / {mx}" + ok = _norm(got) == _norm(expected) + record("computation_seek_low_one", ok, + "" if ok else f"behavior_wrong: low tap shows {got!r}, expected {expected!r}", + depth=0, jump_kind="value", expect=f"indicator == '{expected}'") + _shot("computation_seek_low_one_vlm") + vlm_assert("computation_seek_low_one", + "In this flashlight app, the vertical segmented bar on the right is " + "set to its lowest non-zero level. Is ONLY the single bottom segment " + "highlighted in the bright accent color while all segments above it " + "are dark gray?", + RESULTS_DIR, expect="YES", depth=0, jump_kind="value", tag="color") + + +@and_test(expects=("computation_seek_bottom_zero",)) +def test_seek_bottom_zero(): + # Divide/edge case: tapping the very bottom drives the level to 0 (off). + # Positive/negative: set Max first so '0 / max' is ABSENT, then bottom tap + # makes it PRESENT. + if not _go_home(): + record("computation_seek_bottom_zero", False, + "setup_failed: home not reachable", + depth=0, jump_kind="value", expect="'0 / '") + return + mx = _parse_pair(_read_indicator()) + mx = mx[1] if mx else 10 + _seek_to(0.03) # drive to max first + before = _read_indicator() + got = _seek_to(0.999) # very bottom -> 0 + if not got: + record("computation_seek_bottom_zero", False, + "setup_failed: seek_bar not found", + depth=0, jump_kind="value", expect=f"'0 / {mx}'") + return + expected = f"0 / {mx}" + ok = _norm(got) == _norm(expected) and _norm(before) != _norm(expected) + record("computation_seek_bottom_zero", ok, + "" if ok else f"behavior_wrong: bottom tap shows {got!r}, expected {expected!r}", + depth=0, jump_kind="value", expect=f"indicator == '{expected}'") + + +@and_test(expects=("computation_seek_frac_seven",)) +def test_seek_frac_seven(): + # Additional mapping point verified live: f=0.30 -> level 7. + if not _go_home(): + record("computation_seek_frac_seven", False, + "setup_failed: home not reachable", + depth=0, jump_kind="value", expect="'7 / '") + return + mx = _parse_pair(_read_indicator()) + mx = mx[1] if mx else 10 + got = _seek_to(0.30) + if not got: + record("computation_seek_frac_seven", False, + "setup_failed: seek_bar not found", + depth=0, jump_kind="value", expect=f"'7 / {mx}'") + return + expected = f"7 / {mx}" + ok = _norm(got) == _norm(expected) + record("computation_seek_frac_seven", ok, + "" if ok else f"behavior_wrong: 0.30 tap shows {got!r}, expected {expected!r}", + depth=0, jump_kind="value", expect=f"indicator == '{expected}'") + + +@and_test(expects=("computation_seek_frac_three",)) +def test_seek_frac_three(): + # Additional mapping point verified live: f=0.70 -> level 3. + if not _go_home(): + record("computation_seek_frac_three", False, + "setup_failed: home not reachable", + depth=0, jump_kind="value", expect="'3 / '") + return + mx = _parse_pair(_read_indicator()) + mx = mx[1] if mx else 10 + got = _seek_to(0.70) + if not got: + record("computation_seek_frac_three", False, + "setup_failed: seek_bar not found", + depth=0, jump_kind="value", expect=f"'3 / {mx}'") + return + expected = f"3 / {mx}" + ok = _norm(got) == _norm(expected) + record("computation_seek_frac_three", ok, + "" if ok else f"behavior_wrong: 0.70 tap shows {got!r}, expected {expected!r}", + depth=0, jump_kind="value", expect=f"indicator == '{expected}'") + + +@and_test(expects=("computation_seek_monotonic",)) +def test_seek_monotonic(): + # Cross-check the mapping is a genuine decreasing function of y (top>bottom), + # not a fixed value: level(0.03) > level(0.50) > level(0.90). + if not _go_home(): + record("computation_seek_monotonic", False, + "setup_failed: home not reachable", + depth=0, jump_kind="value", expect="level(top) > level(mid) > level(low)") + return + vals = [] + for frac in (0.03, 0.50, 0.90): + p = _parse_pair(_seek_to(frac)) + vals.append(p[0] if p else None) + if any(v is None for v in vals): + record("computation_seek_monotonic", False, + f"setup_failed: could not read all levels {vals}", + depth=0, jump_kind="value", expect="level(top) > level(mid) > level(low)") + return + top, mid, low = vals + ok = top > mid > low + record("computation_seek_monotonic", ok, + "" if ok else f"behavior_wrong: levels top/mid/low={vals} not strictly decreasing", + depth=0, jump_kind="value", + expect=f"level decreases top->bottom (got {top}>{mid}>{low})") + + +# ══════════════════════════════════════════════════════════════════════════════ +# C. Preferred-level slider dialog (depth 2, jump_kind=value) +# home -> Settings (depth 1) -> "Preferred level" dialog (depth 2). +# Track fraction f -> "New: N". Two well-separated fractions verified live +# (f=0.30 -> New 3, f=0.70 -> New 8). Cancel to avoid persisting state. +# ══════════════════════════════════════════════════════════════════════════════ + +def and_enter_preferred_level(): + """Open Settings, then the 'Set preferred level' dialog. Returns (ok, note). + Counts two surfaces (Settings, dialog) via and_enter().""" + if not _go_home(): + return False, "setup_failed: home not reachable" + settings = find_node(ui(), content_desc="Settings") + if not tap_node(settings): + return False, "setup_failed: Settings action not tappable" + settle("launch") + if node_by_id(ui(), "recycler_view") is None: + return False, "setup_failed: Settings screen did not open" + and_enter("settings") + row = find_node_ci(ui(), "Preferred level") + if not tap_node(row): + return False, "setup_failed: 'Preferred level' row not tappable" + settle("tap") + title = find_node_ci(ui(), "Set preferred level") + if title is None: + return False, "setup_failed: 'Set preferred level' dialog did not open" + and_enter("preferred_level_dialog") + return True, "" + + +def _read_new_value(): + """Parse the 'New: N' number from the dialog's TextView.""" + for n in ui(): + t = n.get("text", "").replace(" ", "\n") + m = re.search(r"New:\s*(\d+)", t) + if m: + return int(m.group(1)) + return None + + +def _slider_set(frac: float): + """Tap the slider track in the customPanel at horizontal fraction `frac`; + return the resulting New value (int) or None. Re-reads bounds each call.""" + cp = node_by_id(ui(), "customPanel") + if not cp or "_bounds" not in cp: + return None + x1, y1, x2, y2 = cp["_bounds"] + tx = x1 + round(frac * (x2 - x1)) + tx = max(x1 + 1, min(x2 - 1, tx)) + # The New/Current text sits at the top of customPanel; the slider track is + # in its lower half. Tap ~78% down the panel height (verified live). + ty = y1 + round(0.78 * (y2 - y1)) + tap(tx, ty) + return _read_new_value() + + +@and_test(expects=("computation_pref_slider_low",)) +def test_pref_slider_low(): + ok_nav, note = and_enter_preferred_level() + if not ok_nav: + record("computation_pref_slider_low", False, note, + depth=2, jump_kind="value", expect="dialog shows 'New: 3'") + return + before = _read_new_value() + got = _slider_set(0.30) # verified live -> New 3 + ok = got == 3 and before != 3 + if got is None: + msg = "setup_failed: could not read 'New:' value after slider tap" + elif got != 3: + msg = f"behavior_wrong: slider f=0.30 gave New:{got}, expected New:3" + else: + msg = "" + record("computation_pref_slider_low", ok, msg, + depth=2, jump_kind="value", expect="dialog shows 'New: 3'") + # Cancel so the preferred-level pref is not persisted. + tap_text(ui(), "Cancel") + + +@and_test(expects=("computation_pref_slider_high",)) +def test_pref_slider_high(): + ok_nav, note = and_enter_preferred_level() + if not ok_nav: + record("computation_pref_slider_high", False, note, + depth=2, jump_kind="value", expect="dialog shows 'New: 8'") + return + got = _slider_set(0.70) # verified live -> New 8 + ok = got == 8 + if got is None: + msg = "setup_failed: could not read 'New:' value after slider tap" + elif got != 8: + msg = f"behavior_wrong: slider f=0.70 gave New:{got}, expected New:8" + else: + msg = "" + record("computation_pref_slider_high", ok, msg, + depth=2, jump_kind="value", expect="dialog shows 'New: 8'") + tap_text(ui(), "Cancel") + + +@and_test(expects=("computation_pref_slider_monotonic",)) +def test_pref_slider_monotonic(): + # The slider is a real function of position: New(0.30) < New(0.70). + ok_nav, note = and_enter_preferred_level() + if not ok_nav: + record("computation_pref_slider_monotonic", False, note, + depth=2, jump_kind="value", expect="New(low) < New(high)") + return + low = _slider_set(0.30) + high = _slider_set(0.70) + if low is None or high is None: + record("computation_pref_slider_monotonic", False, + f"setup_failed: could not read New values (low={low}, high={high})", + depth=2, jump_kind="value", expect="New(low) < New(high)") + tap_text(ui(), "Cancel") + return + ok = low < high + record("computation_pref_slider_monotonic", ok, + "" if ok else f"behavior_wrong: New(0.30)={low} not < New(0.70)={high}", + depth=2, jump_kind="value", + expect=f"New increases with position (got {low} < {high})") + tap_text(ui(), "Cancel") + + +TESTS = [ + # A. level quick-buttons + test_max_button, + test_half_button, + test_min_button, + test_off_button, + # B. seekbar position -> level + test_seek_top_max, + test_seek_mid_half, + test_seek_low_one, + test_seek_bottom_zero, + test_seek_frac_seven, + test_seek_frac_three, + test_seek_monotonic, + # C. preferred-level slider dialog (depth 2) + test_pref_slider_low, + test_pref_slider_high, + test_pref_slider_monotonic, +] + +if __name__ == "__main__": + if not device_online(): + print("Device offline — aborting.") + sys.exit(1) + run_suite(TESTS, "computation") diff --git a/android/cyb3rko-flashdim/tests/test_android_interaction.py b/android/cyb3rko-flashdim/tests/test_android_interaction.py new file mode 100644 index 0000000000000000000000000000000000000000..35a96430123034dee37e10d802a2dfe2256b1505 --- /dev/null +++ b/android/cyb3rko-flashdim/tests/test_android_interaction.py @@ -0,0 +1,636 @@ +#!/usr/bin/env python3 +"""FlashDim — INTERACTION lane. + +EFFECT-BY-CONSEQUENCE: multi-step sequences whose consequence on app state is +read back out of a fresh ui(), and DATA/SETTING persistence across full process +death. A dead shell that ignores the taps must FAIL here. + +Run: + ADB_PATH=/opt/android/platform-tools/adb DEVICE_SERIAL=emulator-5554 \ + python3 test_android_interaction.py +""" +import os +import re +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +RD = sys.argv[2] if len(sys.argv) > 2 else RESULTS_DIR + + +# ── local helpers (never touch adb directly) ─────────────────────────────────── + +def li_text(): + """Current level_indicator text (e.g. '0 / 10', 'SOS mode'), or None.""" + n = node_by_id(ui(), "level_indicator") + return n.get("text") if n else None + + +def qa_text(): + """Current quick_actions_view text, or None.""" + n = node_by_id(ui(), "quick_actions_view") + return n.get("text") if n else None + + +def tap_home_level(rid): + """Tap a home level button by id-suffix; return the resulting level text.""" + if not tap_node(node_by_id(ui(), rid)): + return None + return li_text() + + +def tap_seekbar_fraction(frac): + """Tap the custom seek_bar at `frac` from its TOP (top=max, bottom=0). + + level = round(10*(1-frac)). Coordinates are derived live from the node's + bounds — never a literal. Returns the resulting level text. + """ + sb = node_by_id(ui(), "seek_bar") + if not sb or "_bounds" not in sb: + return None + x1, y1, x2, y2 = sb["_bounds"] + cx = (x1 + x2) // 2 + ty = int(y1 + frac * (y2 - y1)) + tap(cx, ty) + return li_text() + + +def _yc(node): + b = node["_bounds"] + return (b[1] + b[3]) // 2 + + +def switch_for_title(nodes, title): + """The Switch node on the same settings row as `title` — the one whose + y-centre is closest (within ~80px) to the title's.""" + t = find_node(nodes, text=title) + if not t or "_bounds" not in t: + return None + ty = _yc(t) + best, best_d = None, 10 ** 9 + for s in find_by_class(nodes, "Switch"): + if "_bounds" not in s: + continue + d = abs(_yc(s) - ty) + if d < best_d: + best, best_d = s, d + return best if best_d <= 80 else None + + +def pref_level_summary(nodes): + """The 'Preferred level' summary TextView (ends ': '), or None.""" + pl = find_node(nodes, text="Preferred level") + if not pl or "_bounds" not in pl: + return None + ply = _yc(pl) + cands = [x for x in nodes + if x.get("class", "").endswith("TextView") + and x.get("text", "") + and "_bounds" in x + and _yc(x) > ply and abs(_yc(x) - ply) < 120] + return cands[0].get("text") if cands else None + + +def new_val_in_dialog(nodes): + """Parse the 'New: N' number in the Set preferred level dialog, or None.""" + for x in nodes: + t = x.get("text", "") + if t.startswith("New:"): + m = re.search(r"New:\s*(\d+)", t) + return m.group(1) if m else None + return None + + +# ── depth-family helpers (their and_enter_* NAME backs a declared depth>=1) ───── + +def and_enter_settings(): + """Open the Settings activity from the home toolbar. Counts one surface.""" + if not tap_node(node_by_id(ui(), "settings_action")): + return False + settle("launch") + and_enter("settings") + return True + + +def and_enter_morse_dialog(): + """Open the Morse dialog from the home screen. Counts one surface.""" + if not tap_node(node_by_id(ui(), "morse_button")): + return False + settle("tap") + and_enter("morse_dialog") + return True + + +def and_enter_interval_dialog(): + """Open the Interval dialog from the home screen. Counts one surface.""" + if not tap_node(node_by_id(ui(), "interval_button")): + return False + settle("tap") + and_enter("interval_dialog") + return True + + +def and_enter_preferred_level_dialog(): + """From an open Settings screen, open the Set preferred level dialog.""" + if not tap_node(find_node(ui(), text="Preferred level")): + return False + settle("tap") + and_enter("preferred_level_dialog") + return True + + +# ════════════════════════════════════════════════════════════════════════════ +# A. Multi-step level sequences (consequence = level_indicator), depth 0 +# ════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_seq_max_half_min_off",)) +def test_seq_max_half_min_off(): + """4-step ordered progression driven by four different buttons; each step's + consequence depends on the previous surface being live.""" + # clear_data() guarantees a virgin launch at '0 / 10' — a bare restart_app() + # resumes the app's surviving task in whatever level a prior test left it. + clear_data() + restart_app() + wait_for_foreground() + if node_by_id(ui(), "max_button") is None: + record("interaction_seq_max_half_min_off", False, + "setup_failed: home level buttons not present", + depth=0, jump_kind="transition", + expect="'0 / 10'->'10 / 10'->'5 / 10'->'1 / 10'->'0 / 10'") + return + s0 = li_text() # launch: "0 / 10" + s_max = tap_home_level("max_button") # "10 / 10" + s_half = tap_home_level("half_button") # "5 / 10" + s_min = tap_home_level("min_button") # "1 / 10" + s_off = tap_home_level("off_button") # "0 / 10" + ok = (s0 == "0 / 10" and s_max == "10 / 10" and s_half == "5 / 10" + and s_min == "1 / 10" and s_off == "0 / 10") + record("interaction_seq_max_half_min_off", ok, + "" if ok else f"behavior_wrong: progression was " + f"{s0}->{s_max}->{s_half}->{s_min}->{s_off}", + depth=0, jump_kind="transition", + expect="Max->Half->Min->Off = '10 / 10'->'5 / 10'->'1 / 10'->'0 / 10' (final '0 / 10')") + + +@and_test(expects=("interaction_seq_toggle_through",)) +def test_seq_off_max_off_half(): + """Off->Max->Off->Half. Toggling max ON then OFF then half proves each tap + re-commits state rather than echoing the first input.""" + restart_app() + wait_for_foreground() + if node_by_id(ui(), "off_button") is None: + record("interaction_seq_toggle_through", False, + "setup_failed: home level buttons not present", + depth=0, jump_kind="transition", expect="final '5 / 10' after Off->Max->Off->Half") + return + s_off1 = tap_home_level("off_button") # "0 / 10" + s_max = tap_home_level("max_button") # "10 / 10" + s_off2 = tap_home_level("off_button") # "0 / 10" + s_half = tap_home_level("half_button") # "5 / 10" + ok = (s_off1 == "0 / 10" and s_max == "10 / 10" + and s_off2 == "0 / 10" and s_half == "5 / 10") + record("interaction_seq_toggle_through", ok, + "" if ok else f"behavior_wrong: progression was " + f"{s_off1}->{s_max}->{s_off2}->{s_half}", + depth=0, jump_kind="transition", + expect="Off->Max->Off->Half = '0 / 10'->'10 / 10'->'0 / 10'->'5 / 10' (final '5 / 10')") + + +@and_test(expects=("interaction_seq_min_then_max_override",)) +def test_seq_min_then_max_override(): + """Min sets '1 / 10', then Max must OVERRIDE to '10 / 10' — a later action + winning over an earlier one, not being ignored.""" + restart_app() + wait_for_foreground() + if node_by_id(ui(), "min_button") is None: + record("interaction_seq_min_then_max_override", False, + "setup_failed: home level buttons not present", + depth=0, jump_kind="transition", expect="'1 / 10' then '10 / 10'") + return + s_min = tap_home_level("min_button") # "1 / 10" + s_max = tap_home_level("max_button") # "10 / 10" + ok = (s_min == "1 / 10" and s_max == "10 / 10") + record("interaction_seq_min_then_max_override", ok, + "" if ok else f"behavior_wrong: Min={s_min}, then Max={s_max}", + depth=0, jump_kind="transition", + expect="Min='1 / 10' then Max overrides to '10 / 10'") + + +@and_test(expects=("interaction_button_seekbar_same_state", + "interaction_button_seekbar_same_state_vlm")) +def test_button_and_seekbar_drive_same_state(): + """Max button -> '10 / 10', Min button -> '1 / 10', then a seekbar tap near + the TOP must return '10 / 10' — proving buttons and the custom seekbar drive + the SAME level state. VLM confirms the segmented fill matches level 10.""" + restart_app() + wait_for_foreground() + if node_by_id(ui(), "seek_bar") is None or node_by_id(ui(), "max_button") is None: + record("interaction_button_seekbar_same_state", False, + "setup_failed: seek_bar or level buttons missing", + depth=0, jump_kind="transition", + expect="'10 / 10' -> '1 / 10' -> seekbar '10 / 10'") + vlm_assert("interaction_button_seekbar_same_state", + "Is the vertical segmented bar completely filled (all ~10 segments " + "highlighted) and does the level read 10 / 10?", + RD, expect="YES", depth=0, jump_kind="transition", tag="shape") + return + s_max = tap_home_level("max_button") # "10 / 10" + s_min = tap_home_level("min_button") # "1 / 10" + s_seek = tap_seekbar_fraction(0.05) # back to "10 / 10" + ok = (s_max == "10 / 10" and s_min == "1 / 10" and s_seek == "10 / 10") + record("interaction_button_seekbar_same_state", ok, + "" if ok else f"behavior_wrong: Max={s_max}, Min={s_min}, seekTop={s_seek}", + depth=0, jump_kind="transition", + expect="Max='10 / 10', Min='1 / 10', seekbar-top back to '10 / 10' (shared state)") + # VLM #1: seekbar fully filled at level 10 + vlm_assert("interaction_button_seekbar_same_state", + "Is the vertical segmented bar completely filled (all ~10 segments " + "highlighted) and does the level read 10 / 10?", + RD, expect="YES", depth=0, jump_kind="transition", tag="shape") + + +@and_test(expects=("interaction_seekbar_min_fill_vlm",)) +def test_seekbar_min_fill_vlm(): + """Tap Min, then have the VLM verify only the bottom-most seekbar segment is + lit — a canvas-drawn fill that the view tree never exposes.""" + restart_app() + wait_for_foreground() + s_min = tap_home_level("min_button") # "1 / 10" (rule-side sanity for the screenshot) + if s_min != "1 / 10": + record("interaction_seekbar_min_fill_vlm", False, + f"setup_failed: Min gave {s_min!r}, not '1 / 10'; screenshot unreliable", + depth=0, jump_kind="none", tag="shape") + return + # VLM #2: only bottom segment lit + vlm_assert("interaction_seekbar_min_fill", + "Is only the bottom-most segment of the vertical bar highlighted while " + "the rest are dark?", + RD, expect="YES", depth=0, jump_kind="transition", tag="shape") + + +@and_test(expects=("interaction_seekbar_mid_fill_vlm",)) +def test_seekbar_mid_fill_vlm(): + """Tap the seekbar mid, verify level '5 / 10', then have the VLM confirm the + bar is filled about halfway from the bottom.""" + restart_app() + wait_for_foreground() + s_mid = tap_seekbar_fraction(0.5) # "5 / 10" + if s_mid != "5 / 10": + record("interaction_seekbar_mid_fill_vlm", False, + f"setup_failed: seekbar-mid gave {s_mid!r}, not '5 / 10'", + depth=0, jump_kind="none", tag="shape") + return + # VLM #6: bar filled about halfway + vlm_assert("interaction_seekbar_mid_fill", + "Is the vertical segmented bar filled about halfway from the bottom " + "(roughly the lower half of the segments highlighted, the upper half dark)?", + RD, expect="YES", depth=0, jump_kind="transition", tag="shape") + + +# ════════════════════════════════════════════════════════════════════════════ +# B. SOS mode enter -> exit (consequence = multiple widgets change), depth 0 +# ════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_sos_enter_exit", + "interaction_sos_enter_exit_vlm")) +def test_sos_enter_then_exit(): + """Tap SOS: indicator -> 'SOS mode', quick_actions -> 'Morse:...', the + Max/Half/Min/Morse/Interval buttons DISAPPEAR, sos disabled, seek disabled. + Then tap Off: EVERYTHING restores. Asserts BOTH halves of the sequence.""" + restart_app() + wait_for_foreground() + if node_by_id(ui(), "sos_button") is None: + record("interaction_sos_enter_exit", False, + "feature_missing: no sos_button on the main surface", + depth=0, jump_kind="transition", + expect="'SOS mode' + buttons hidden, then restored to '0 / 10'") + vlm_assert("interaction_sos_enter_exit", + "Have the Maximum/Half/Minimum buttons disappeared, leaving only " + "SOS and Off in the left column?", + RD, expect="YES", depth=0, jump_kind="transition", tag="position") + return + # enter + tap_node(node_by_id(ui(), "sos_button")) + n = ui() + entered_li = (node_by_id(n, "level_indicator") or {}).get("text") + entered_qa = (node_by_id(n, "quick_actions_view") or {}).get("text") or "" + hidden = all(node_by_id(n, rid) is None for rid in + ("morse_button", "interval_button", "max_button", + "half_button", "min_button")) + sos_disabled = (node_by_id(n, "sos_button") or {}).get("enabled") == "false" + seek_disabled = (node_by_id(n, "seek_bar") or {}).get("enabled") == "false" + entered_ok = (entered_li == "SOS mode" and entered_qa.startswith("Morse:") + and hidden and sos_disabled and seek_disabled) + # VLM #3: brightness buttons gone in SOS mode + vlm_assert("interaction_sos_enter_exit", + "Have the Maximum/Half/Minimum buttons disappeared, leaving only " + "SOS and Off in the left column?", + RD, expect="YES", depth=0, jump_kind="transition", tag="position") + # exit + tap_node(node_by_id(ui(), "off_button")) + m = ui() + restored_li = (node_by_id(m, "level_indicator") or {}).get("text") + restored_qa = (node_by_id(m, "quick_actions_view") or {}).get("text") + buttons_back = all(node_by_id(m, rid) is not None for rid in + ("morse_button", "interval_button", "max_button", + "half_button", "min_button")) + restored_ok = (restored_li == "0 / 10" and restored_qa == "Quick Actions" + and buttons_back) + ok = entered_ok and restored_ok + record("interaction_sos_enter_exit", ok, + "" if ok else f"behavior_wrong: entered(li={entered_li!r},hidden={hidden}," + f"sosOff={sos_disabled},seekOff={seek_disabled}) " + f"restored(li={restored_li!r},qa={restored_qa!r},back={buttons_back})", + depth=0, jump_kind="transition", + expect="SOS enter: li='SOS mode', qa startswith 'Morse:', buttons hidden, " + "sos+seek disabled; Off exit restores li='0 / 10', qa='Quick Actions', buttons back") + + +# ════════════════════════════════════════════════════════════════════════════ +# C. Morse dialog input sequence (3+ steps), depth 1 +# ════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_morse_dialog_flow", + "interaction_morse_dialog_flow_vlm")) +def test_morse_dialog_input_flow(): + """3-step sequence inside the Morse dialog: + 1) open dialog, + 2) tap Flash with EMPTY input -> validation error appears AND dialog stays, + 3) type a message, tap Flash -> the dialog DISMISSES. + Each step depends on the prior surface being live; a shell that ignores the + empty-Flash tap would dismiss immediately at step 2 and fail.""" + restart_app() + wait_for_foreground() + if node_by_id(ui(), "morse_button") is None: + record("interaction_morse_dialog_flow", False, + "feature_missing: no morse_button on the main surface", + depth=1, jump_kind="transition", + expect="empty Flash -> error + dialog open; typed Flash -> dialog gone") + vlm_assert("interaction_morse_dialog_flow", + "Is a dialog with a single-line text input field (hint about a message) " + "and a 'Flash' button visible on screen?", + RD, expect="YES", depth=1, jump_kind="transition", tag="layout") + return + if not and_enter_morse_dialog(): + record("interaction_morse_dialog_flow", False, + "setup_failed: could not open the Morse dialog", + depth=1, jump_kind="transition", + expect="empty Flash -> error + dialog open; typed Flash -> dialog gone") + vlm_assert("interaction_morse_dialog_flow", + "Is a dialog with a single-line text input field (hint about a message) " + "and a 'Flash' button visible on screen?", + RD, expect="YES", depth=1, jump_kind="transition", tag="layout") + return + dialog_open = node_by_id(ui(), "text_input_text") is not None + # VLM #4: the morse input dialog is on screen + vlm_assert("interaction_morse_dialog_flow", + "Is a dialog with a single-line text input field (hint about a message) " + "and a 'Flash' button visible on screen?", + RD, expect="YES", depth=1, jump_kind="transition", tag="layout") + # step 2: empty Flash -> error, dialog persists + tap_node(node_by_id(ui(), "button1")) + settle("tap") + n = ui() + still_open = node_by_id(n, "text_input_text") is not None + err = find_node_ci(n, "Please enter your message") is not None + # step 3: type + Flash -> dialog dismisses + field = node_by_id(ui(), "text_input_text") + typed = False + if field: + typed = type_text(field, "A") + cur = node_by_id(ui(), "text_input_text") + if cur is not None and cur.get("text") != "A": + type_text(field, "A", method="ime") + hide_keyboard() + tap_node(node_by_id(ui(), "button1")) + settle("tap") + dismissed = node_by_id(ui(), "text_input_text") is None + ok = dialog_open and still_open and err and dismissed + record("interaction_morse_dialog_flow", ok, + "" if ok else f"behavior_wrong: open={dialog_open}, emptyStillOpen={still_open}, " + f"error={err}, typed={typed}, dismissedAfterFlash={dismissed}", + depth=1, jump_kind="transition", + expect="empty Flash keeps dialog open with error 'Please enter your message'; " + "typed 'A' + Flash dismisses the dialog") + + +# ════════════════════════════════════════════════════════════════════════════ +# D. Interval dialog TIME<->BPM mode-switch round-trip (3 states), depth 1 +# ════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_interval_mode_roundtrip", + "interaction_interval_mode_roundtrip_vlm")) +def test_interval_mode_roundtrip(): + """Open Interval dialog (TIME default: input '500', suffix 'ms'), tap BPM + (input '100', 'ms' gone), tap TIME (back to '500'/'ms'). Asserts the full + 3-state round-trip — each switch depends on the prior mode being live.""" + restart_app() + wait_for_foreground() + if node_by_id(ui(), "interval_button") is None: + record("interaction_interval_mode_roundtrip", False, + "feature_missing: no interval_button on the main surface", + depth=1, jump_kind="transition", + expect="TIME '500'/'ms' -> BPM '100'/none -> TIME '500'/'ms'") + vlm_assert("interaction_interval_mode_roundtrip", + "Does the numeric input show 100 with no 'ms' suffix beside it?", + RD, expect="YES", depth=1, jump_kind="transition", tag="content") + return + if not and_enter_interval_dialog(): + record("interaction_interval_mode_roundtrip", False, + "setup_failed: could not open the Interval dialog", + depth=1, jump_kind="transition", + expect="TIME '500'/'ms' -> BPM '100'/none -> TIME '500'/'ms'") + vlm_assert("interaction_interval_mode_roundtrip", + "Does the numeric input show 100 with no 'ms' suffix beside it?", + RD, expect="YES", depth=1, jump_kind="transition", tag="content") + return + + def snap(): + n = ui() + return ((node_by_id(n, "number_input_text") or {}).get("text"), + (node_by_id(n, "textinput_suffix_text") or {}).get("text")) + + t_num, t_suf = snap() # TIME default: 500 / ms + tap_node(node_by_id(ui(), "bpm_button")) + settle("tap") + b_num, b_suf = snap() # BPM: 100 / None + # VLM #5: BPM shows 100 with no ms suffix + vlm_assert("interaction_interval_mode_roundtrip", + "Does the numeric input show 100 with no 'ms' suffix beside it?", + RD, expect="YES", depth=1, jump_kind="transition", tag="content") + tap_node(node_by_id(ui(), "time_button")) + settle("tap") + r_num, r_suf = snap() # back to TIME: 500 / ms + ok = (t_num == "500" and t_suf == "ms" + and b_num == "100" and b_suf is None + and r_num == "500" and r_suf == "ms") + record("interaction_interval_mode_roundtrip", ok, + "" if ok else f"behavior_wrong: TIME=({t_num},{t_suf}) BPM=({b_num},{b_suf}) " + f"TIME2=({r_num},{r_suf})", + depth=1, jump_kind="transition", + expect="TIME('500','ms') -> BPM('100',no suffix) -> TIME('500','ms') round-trip") + + +# ════════════════════════════════════════════════════════════════════════════ +# E. PERSISTENCE across process death (this lane OWNS data/setting persistence) +# ════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_context_awareness_persists",)) +def test_context_awareness_persists(): + """Toggle 'Context awareness' OFF->ON in Settings, force-stop + relaunch, + reopen Settings, assert the switch is STILL checked. An in-memory-only + recreation cannot survive the process death.""" + clear_data() + launch_app() + wait_for_foreground() + if not and_enter_settings(): + record("interaction_context_awareness_persists", False, + "setup_failed: could not open Settings", + depth=1, jump_kind="transition", + expect="'Context awareness' switch checked=true after relaunch") + return + sw = switch_for_title(ui(), "Context awareness") + if sw is None: + record("interaction_context_awareness_persists", False, + "feature_missing: no 'Context awareness' switch in Settings", + depth=1, jump_kind="transition", + expect="'Context awareness' switch checked=true after relaunch") + return + was_off = sw.get("checked") == "false" + tap_node(sw) + settle("tap") + sw2 = switch_for_title(ui(), "Context awareness") + turned_on = (sw2 or {}).get("checked") == "true" + # kill the process and relaunch + force_stop_and_relaunch() + wait_for_foreground() + and_reset_depth() + if not and_enter_settings(): + record("interaction_context_awareness_persists", False, + "setup_failed: could not reopen Settings after relaunch", + depth=1, jump_kind="transition", + expect="'Context awareness' switch checked=true after relaunch") + return + sw3 = switch_for_title(ui(), "Context awareness") + persisted = (sw3 or {}).get("checked") == "true" + ok = was_off and turned_on and persisted + record("interaction_context_awareness_persists", ok, + "" if ok else f"behavior_wrong: wasOff={was_off}, turnedOn={turned_on}, " + f"stillOnAfterRestart={persisted}", + depth=1, jump_kind="transition", + expect="'Context awareness' OFF->ON then survives force_stop_and_relaunch (checked=true)") + + +@and_test(expects=("interaction_preferred_level_dialog_live_value", + "interaction_preferred_level_persists")) +def test_preferred_level_value_persists(): + """Two consequences on the 'Preferred level' preference: + 1) inside the slider dialog (depth 2), tapping the track sets the live + 'New: ' to the exact value the tap position maps to; + 2) after OK + force-stop + relaunch, the Settings summary STILL ends with + the SAME ': ' and is NOT the untouched default ': 10'. + A concrete VALUE surviving process death — an in-memory recreation fails (2).""" + LIVE = "interaction_preferred_level_dialog_live_value" + PERSIST = "interaction_preferred_level_persists" + clear_data() + launch_app() + wait_for_foreground() + if not and_enter_settings(): + record(LIVE, False, "setup_failed: could not open Settings", + depth=2, jump_kind="value", expect="dialog 'New:' shows the tapped value '2'") + record(PERSIST, False, "setup_failed: could not open Settings", + depth=1, jump_kind="value", + expect="'Preferred level' summary keeps its set value after relaunch") + return + if find_node(ui(), text="Preferred level") is None: + record(LIVE, False, "feature_missing: no 'Preferred level' row in Settings", + depth=2, jump_kind="value", expect="dialog 'New:' shows the tapped value '2'") + record(PERSIST, False, "feature_missing: no 'Preferred level' row in Settings", + depth=1, jump_kind="value", + expect="'Preferred level' summary keeps its set value after relaunch") + return + default_summary = pref_level_summary(ui()) or "" + if not and_enter_preferred_level_dialog(): + record(LIVE, False, "setup_failed: could not open the Set preferred level dialog", + depth=2, jump_kind="value", expect="dialog 'New:' shows the tapped value '2'") + record(PERSIST, False, "setup_failed: could not open the Set preferred level dialog", + depth=2, jump_kind="value", + expect="'Preferred level' summary keeps its set value after relaunch") + return + # The slider is a custom view with no distinct node; tap along its track strip + # (derived from the container + 'New:' label bounds) to set a distinct value. + d = ui() + conts = [x for x in d if x.get("class", "").endswith("LinearLayout") + and "_bounds" in x and x["_bounds"][1] > 1000] + news = [x for x in d if x.get("text", "").startswith("New:") and "_bounds" in x] + before_new = new_val_in_dialog(d) # default "10" + changed_new = None + if conts and news: + cont = min(conts, key=lambda c: (c["_bounds"][2] - c["_bounds"][0])) + cx1, _, cx2, cy2 = cont["_bounds"] + sy = (news[0]["_bounds"][3] + cy2) // 2 + # f=0.2 of the track -> value 2 (distinct from the default 10) + tap(int(cx1 + 0.2 * (cx2 - cx1)), sy) + changed_new = new_val_in_dialog(ui()) + # depth-2 value: the live "New:" readout reflects the tapped position (10 -> 2) + live_ok = (before_new == "10" and changed_new == "2") + record(LIVE, live_ok, + "" if live_ok else f"behavior_wrong: 'New:' was {before_new!r}, after tapping " + f"track f=0.2 became {changed_new!r} (expected '2')", + depth=2, jump_kind="value", + expect="dialog 'New:' 10 -> '2' after tapping the slider track at fraction 0.2") + tap_node(node_by_id(ui(), "button1")) # OK + settle("tap") + set_summary = pref_level_summary(ui()) or "" + set_value = None + m = re.search(r":\s*(\d+)\s*$", set_summary) + if m: + set_value = m.group(1) + # kill the process and relaunch + force_stop_and_relaunch() + wait_for_foreground() + and_reset_depth() + if not and_enter_settings(): + record(PERSIST, False, + "setup_failed: could not reopen Settings after relaunch", + depth=1, jump_kind="value", + expect="'Preferred level' summary keeps its set value after relaunch") + return + after_summary = pref_level_summary(ui()) or "" + changed_from_default = (set_summary != default_summary + and not set_summary.rstrip().endswith(": 10")) + persisted = (bool(set_value) and after_summary == set_summary) + ok = changed_from_default and persisted + record(PERSIST, ok, + "" if ok else f"behavior_wrong: default={default_summary[-12:]!r}, " + f"newInDialog={changed_new!r}, set={set_summary[-12:]!r}, " + f"afterRestart={after_summary[-12:]!r}", + depth=1, jump_kind="value", + expect=f"'Preferred level' summary ends ': {set_value}' both before and after " + f"force_stop_and_relaunch (and not the default ': 10')") + + +TESTS = [ + # A. multi-step level sequences (depth 0) + test_seq_max_half_min_off, + test_seq_off_max_off_half, + test_seq_min_then_max_override, + test_button_and_seekbar_drive_same_state, + test_seekbar_min_fill_vlm, + test_seekbar_mid_fill_vlm, + # B. SOS enter/exit sequence (depth 0) + test_sos_enter_then_exit, + # C. Morse dialog input sequence (depth 1) + test_morse_dialog_input_flow, + # D. Interval dialog mode round-trip (depth 1) + test_interval_mode_roundtrip, + # E. persistence across process death (depth 1 / depth 2 value) + test_context_awareness_persists, + test_preferred_level_value_persists, +] + +if __name__ == "__main__": + if not device_online(): + print("device offline — the adb tunnel may have dropped") + run_suite(TESTS, "interaction") diff --git a/android/cyb3rko-flashdim/tests/test_android_navigation.py b/android/cyb3rko-flashdim/tests/test_android_navigation.py new file mode 100644 index 0000000000000000000000000000000000000000..dea541ea551c875970a7ea73f42648640b87a063 --- /dev/null +++ b/android/cyb3rko-flashdim/tests/test_android_navigation.py @@ -0,0 +1,425 @@ +#!/usr/bin/env python3 +"""NAVIGATION-lane behavioral suite for FlashDim. + +Owns surface REACHABILITY and BACK-STACK integrity: tapping a nav trigger +(toolbar action, quick-action button, preference row) lands on the intended +surface, and BACK unwinds it hop by hop. This lane is the SOLE owner of +jump_kind="reach" and of the depth>=2 chains — every jump is PROVEN with +and_reach(before, after, target, source): the TARGET surface's discriminating +element APPEARED *and* the SOURCE surface's element DISAPPEARED. A screen that was +in the dump all along was never reached, and a dead shell that never opens the +dialog FAILS. + +CEDES: dialog CONTENT strings -> text; state flips (radio/switch) -> states; +displayed values (level, counter) -> computation; tree SHAPE counts -> structure. +Here we assert only that we crossed a surface boundary and that BACK returns us. + +All target/source strings below were observed live on the original app: + home --morse_button--> "Flash morse code" (Off disappears) + home --interval_button--> "Interval Flash" (Off disappears) + home --icon_credits_action->"Show Icon Credits" (Off disappears) [About] + home --links_action--> "Repository on GitHub" (Off disappears) [Links] + home --settings_action--> "Flashlight controls" (Off disappears) [Settings] + About --Show Icon Credits--> "Open Pictogrammers" (Show Icon Credits gone) [d2] + Settings --Preferred level-->"Set preferred level" (Context awareness gone) [d2] + Settings --about row--> "Repository on GitHub" (Flashlight controls gone)[d2] +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else "/workspace/testgen/eval/results" + + +# ────────────────────────────────────────────────────────────────────────────── +# Depth-family helpers. A declared depth>=1 / jump_kind="reach" must be backed by +# a real and_enter_*/and_reach_* call so the depth audit sees genuine navigation +# (never a relaunch). The and_reach_* helpers return the reach VERDICT (bool) and +# count one surface via and_reach_surface(); the and_enter_* helpers open a +# surface and return its fresh node list for chaining. +# ────────────────────────────────────────────────────────────────────────────── + +def _home(): + """Restart to a settled MainActivity and return its node list.""" + restart_app() + wait_for_foreground() + return ui() + + +def and_reach_morse_dialog(home): + """home --morse_button--> Morse dialog. Verdict: title appears, Off gone.""" + n = node_by_id(home, "morse_button") + return bool(n) and and_reach_surface(n, "Flash morse code", "Off") + + +def and_reach_interval_dialog(home): + """home --interval_button--> Interval dialog.""" + n = node_by_id(home, "interval_button") + return bool(n) and and_reach_surface(n, "Interval Flash", "Off") + + +def and_reach_about_dialog(home): + """home --icon_credits_action--> About dialog (button 'Show Icon Credits').""" + n = node_by_id(home, "icon_credits_action") + return bool(n) and and_reach_surface(n, "Show Icon Credits", "Off") + + +def and_reach_links_dialog(home): + """home --links_action--> Links dialog (row 'Repository on GitHub').""" + n = node_by_id(home, "links_action") + return bool(n) and and_reach_surface(n, "Repository on GitHub", "Off") + + +def and_enter_about_dialog(home): + """Open the About dialog and return its fresh node list (for chaining).""" + if not and_reach_about_dialog(home): + return None + return ui() + + +def and_reach_icon_credits(about): + """About --Show Icon Credits--> Icon Credits dialog (button 'Open + Pictogrammers'); the 'Show Icon Credits' button disappears.""" + n = node_by_id(about, "button1") # "Show Icon Credits" + return bool(n) and and_reach_surface(n, "Open Pictogrammers", "Show Icon Credits") + + +def and_reach_settings(home): + """home --settings_action--> SettingsActivity. Verdict: 'Flashlight controls' + category appears, home 'Quick Actions' label disappears (home 'Off' cannot be + the source: the Settings summaries contain the substring 'off').""" + n = node_by_id(home, "settings_action") + return bool(n) and and_reach_surface(n, "Flashlight controls", "Quick Actions") + + +def and_enter_settings(home): + """Open Settings and return its fresh node list (for chaining).""" + if not and_reach_settings(home): + return None + return ui() + + +def and_reach_preferred_level(settings): + """Settings --Preferred level row--> 'Set preferred level' dialog; the + 'Context awareness' row disappears (its own title, not the row we tapped, + because 'Set preferred level' contains 'preferred level' as a substring).""" + row = find_node_ci(settings, "Preferred level") + return bool(row) and and_reach_surface(row, "Set preferred level", "Context awareness") + + +def and_reach_settings_links(settings): + """Settings --about row ('by Cyb3rKo')--> Links dialog. 'Repository on GitHub' + appears; the 'Flashlight controls' category disappears.""" + row = find_node_ci(settings, "by Cyb3rKo") or find_node_ci(settings, "FlashDim Dev") + return bool(row) and and_reach_surface(row, "Repository on GitHub", "Flashlight controls") + + +def _home_restored(): + """True iff we are back on the MainActivity home surface (Off button visible + and NOT on a blank/dead screen).""" + nodes = ui() + return (node_by_id(nodes, "off_button") is not None + and find_node_ci(nodes, "Quick Actions") is not None) + + +# ══════════════════════════════════════════════════════════════════════════════ +# DEPTH-1 reach: each top-level destination reached from home. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_morse", "nav_reach_morse_vlm")) +def test_reach_morse(): + home = _home() + ok = and_reach_morse_dialog(home) + record("nav_reach_morse", ok, + "" if ok else "feature_missing: Morse dialog ('Flash morse code') did " + "not appear / home 'Off' did not disappear after tapping morse_button", + depth=1, jump_kind="reach", + expect="'Flash morse code' dialog title visible; home 'Off' button gone") + vlm_assert("nav_reach_morse", + "Is a dialog titled 'Flash morse code' shown with a single-line " + "text input field above a 'Flash' button?", + RESULTS_DIR, tag="layout") + + +@and_test(expects=("nav_reach_interval",)) +def test_reach_interval(): + home = _home() + ok = and_reach_interval_dialog(home) + record("nav_reach_interval", ok, + "" if ok else "feature_missing: Interval dialog ('Interval Flash') did " + "not appear / home 'Off' did not disappear after tapping interval_button", + depth=1, jump_kind="reach", + expect="'Interval Flash' dialog title visible; home 'Off' button gone") + + +@and_test(expects=("nav_reach_interval_vlm",)) +def test_reach_interval_vlm(): + home = _home() + ok = and_reach_interval_dialog(home) + record("nav_reach_interval_probe", ok, + "" if ok else "setup_failed: could not open Interval dialog for VLM", + depth=1, jump_kind="reach", + expect="'Interval Flash' dialog reached for screenshot") + vlm_assert("nav_reach_interval", + "Is a dialog shown with two side-by-side radio toggles labelled " + "'TIME' and 'BPM' and a numeric input field?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("nav_reach_links", "nav_reach_links_vlm")) +def test_reach_links(): + home = _home() + ok = and_reach_links_dialog(home) + record("nav_reach_links", ok, + "" if ok else "feature_missing: Links dialog ('Repository on GitHub') " + "did not appear / home 'Off' did not disappear after tapping links_action", + depth=1, jump_kind="reach", + expect="'Repository on GitHub' row visible; home 'Off' button gone") + vlm_assert("nav_reach_links", + "Is a dialog titled 'Links' shown listing several rows, each row " + "having a button labelled 'Visit' on its right side?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("nav_reach_about",)) +def test_reach_about(): + home = _home() + ok = and_reach_about_dialog(home) + record("nav_reach_about", ok, + "" if ok else "feature_missing: About dialog ('Show Icon Credits' " + "button) did not appear / home 'Off' did not disappear after tapping " + "icon_credits_action", + depth=1, jump_kind="reach", + expect="'Show Icon Credits' button visible; home 'Off' button gone") + + +@and_test(expects=("nav_reach_settings", "nav_reach_settings_vlm")) +def test_reach_settings(): + home = _home() + ok = and_reach_settings(home) + # A single-Activity app cannot discriminate by activity, but FlashDim uses a + # real SettingsActivity, so corroborate the surface jump with it. + on_settings = "SettingsActivity" in get_current_activity() + record("nav_reach_settings", ok and on_settings, + "" if ok and on_settings else "feature_missing: Settings surface " + "('Flashlight controls') did not appear / SettingsActivity not resumed", + depth=1, jump_kind="reach", + expect="'Flashlight controls' category visible in SettingsActivity; " + "home 'Quick Actions' label gone") + vlm_assert("nav_reach_settings", + "Is a settings screen shown as a vertical scrollable list of " + "labelled rows, several rows having an on/off toggle switch on the " + "right, with a back arrow at the top-left?", + RESULTS_DIR, tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# DEPTH-2 chains (owned by this lane). Each chains two and_enter/and_reach hops. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_icon_credits_d2", "nav_reach_icon_credits_d2_vlm")) +def test_reach_icon_credits_depth2(): + home = _home() + about = and_enter_about_dialog(home) # hop 1: home -> About + deep = about is not None and and_reach_icon_credits(about) # hop 2 -> Icon Credits + record("nav_reach_icon_credits_d2", deep, + "" if deep else "feature_missing: Icon Credits dialog ('Open " + "Pictogrammers') not reached from About via 'Show Icon Credits'", + depth=2, jump_kind="reach", + expect="'Open Pictogrammers' button visible; 'Show Icon Credits' gone " + "(home -> About -> Icon Credits)") + vlm_assert("nav_reach_icon_credits_d2", + "Is a dialog titled 'Icon Credits' shown, listing icon credit lines " + "and a button reading 'Open Pictogrammers'?", + RESULTS_DIR, tag="content") + + +@and_test(expects=("nav_reach_preferred_level_d2", "nav_reach_preferred_level_d2_vlm")) +def test_reach_preferred_level_depth2(): + home = _home() + settings = and_enter_settings(home) # hop 1: home -> Settings + deep = settings is not None and and_reach_preferred_level(settings) # hop 2 + record("nav_reach_preferred_level_d2", deep, + "" if deep else "feature_missing: 'Set preferred level' dialog not " + "reached from Settings via the 'Preferred level' row", + depth=2, jump_kind="reach", + expect="'Set preferred level' dialog visible; 'Context awareness' row " + "gone (home -> Settings -> preferred-level dialog)") + vlm_assert("nav_reach_preferred_level_d2", + "In the centered pop-up dialog, is there a wide horizontal " + "light-purple / lavender bar with a row of small evenly-spaced dots " + "along it?", + RESULTS_DIR, tag="shape") + + +@and_test(expects=("nav_reach_settings_links_d2",)) +def test_reach_settings_links_depth2(): + home = _home() + settings = and_enter_settings(home) # hop 1: home -> Settings + deep = settings is not None and and_reach_settings_links(settings) # hop 2 + record("nav_reach_settings_links_d2", deep, + "" if deep else "feature_missing: Links dialog not reached from the " + "Settings 'about' row (home -> Settings -> Links)", + depth=2, jump_kind="reach", + expect="'Repository on GitHub' visible; 'Flashlight controls' category " + "gone (home -> Settings -> Links)") + + +# ══════════════════════════════════════════════════════════════════════════════ +# BACK-STACK integrity: BACK returns to where we came from, hop by hop. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_back_morse_to_home",)) +def test_back_from_morse_returns_home(): + home = _home() + deep = and_reach_morse_dialog(home) + # one BACK pops the dialog; home 'Off'/'Quick Actions' must be restored and it + # must NOT be a blank/dead screen. + back_ok = deep and and_back() == 0 and _home_restored() + record("nav_back_morse_to_home", back_ok, + "" if back_ok else "behavior_wrong: BACK from the Morse dialog did not " + "restore the home surface (Off / Quick Actions not visible)", + depth=1, jump_kind="reach", + expect="home 'Off' button + 'Quick Actions' restored after one BACK") + + +@and_test(expects=("nav_back_settings_to_home",)) +def test_back_from_settings_returns_home(): + home = _home() + deep = and_reach_settings(home) + back_ok = deep and and_back() == 0 and _home_restored() + on_home = "MainActivity" in get_current_activity() + record("nav_back_settings_to_home", back_ok and on_home, + "" if back_ok and on_home else "behavior_wrong: BACK from Settings did " + "not return to the home MainActivity surface", + depth=1, jump_kind="reach", + expect="MainActivity home restored (Off visible) after one BACK from " + "Settings") + + +@and_test(expects=("nav_up_arrow_settings_to_home",)) +def test_up_arrow_from_settings_returns_home(): + home = _home() + deep = and_reach_settings(home) + # The toolbar Up affordance (content-desc 'Navigate up') is the intended way + # back from Settings; assert it lands on home. + up = find_node(ui(), content_desc="Navigate up") if deep else None + tapped = up is not None and tap_node(up) + if tapped: + settle("launch") + and_reset_depth() # the Up affordance popped the surface (no BACK keypress) + up_ok = tapped and _home_restored() and "MainActivity" in get_current_activity() + record("nav_up_arrow_settings_to_home", up_ok, + "" if up_ok else "behavior_wrong: the Settings toolbar Up arrow did not " + "return to the home MainActivity surface", + depth=1, jump_kind="reach", + expect="MainActivity home restored after tapping the 'Navigate up' arrow") + + +@and_test(expects=("nav_backstack_icon_credits_unwinds",)) +def test_backstack_icon_credits_unwinds(): + """Back-stack from the DEEPEST surface to home. We descend two hops + (home -> About -> Icon Credits, depth 2). OBSERVED on the original: About and + Icon Credits share one AlertDialog instance (its content is swapped in place), + so a single BACK from the deepest surface dismisses the whole dialog straight + to home rather than re-showing About. Assert that observed unwind: BACK from + Icon Credits restores home (Off + Quick Actions) and it is NOT a blank screen, + and the deepest surface's 'Open Pictogrammers' is gone.""" + home = _home() + about = and_enter_about_dialog(home) + deep = about is not None and and_reach_icon_credits(about) # depth 2 + unwound = False + if deep: + and_back() # pop the shared dialog + after = ui() + unwound = (_home_restored() + and find_node_ci(after, "Open Pictogrammers") is None + and "MainActivity" in get_current_activity()) + ok = deep and unwound + record("nav_backstack_icon_credits_unwinds", ok, + "" if ok else "behavior_wrong: BACK from the depth-2 Icon Credits " + "surface did not return to the home MainActivity (Off / Quick Actions)", + depth=2, jump_kind="reach", + expect="one BACK from Icon Credits (depth 2) restores home ('Off' + " + "'Quick Actions'); 'Open Pictogrammers' gone") + + +@and_test(expects=("nav_backstack_preferred_level_unwinds",)) +def test_backstack_preferred_level_unwinds(): + """home -> Settings -> Set-preferred-level dialog, then BACK -> Settings, + BACK -> home.""" + home = _home() + settings = and_enter_settings(home) + deep = settings is not None and and_reach_preferred_level(settings) # depth 2 + # pop 1: dialog -> Settings (the 'Context awareness' row reappears; the dialog + # title 'Set preferred level' is gone). + pop1 = False + if deep: + and_back() + mid = ui() + pop1 = (find_node_ci(mid, "Context awareness") is not None + and find_node_ci(mid, "Set preferred level") is None) + # pop 2: Settings -> home. + pop2 = False + if pop1: + and_back() + pop2 = _home_restored() and "MainActivity" in get_current_activity() + ok = deep and pop1 and pop2 + record("nav_backstack_preferred_level_unwinds", ok, + "" if ok else "behavior_wrong: BACK did not unwind the preferred-level " + "dialog -> Settings -> home one hop at a time", + depth=2, jump_kind="reach", + expect="BACK #1 restores Settings ('Context awareness'); BACK #2 " + "restores home MainActivity ('Off')") + + +@and_test(expects=("nav_back_links_to_home",)) +def test_back_from_links_returns_home(): + home = _home() + deep = and_reach_links_dialog(home) + back_ok = deep and and_back() == 0 and _home_restored() + record("nav_back_links_to_home", back_ok, + "" if back_ok else "behavior_wrong: BACK from the Links dialog did not " + "restore the home surface", + depth=1, jump_kind="reach", + expect="home 'Off' + 'Quick Actions' restored after one BACK from Links") + + +@and_test(expects=("nav_back_about_to_home",)) +def test_back_from_about_returns_home(): + home = _home() + deep = and_reach_about_dialog(home) + back_ok = deep and and_back() == 0 and _home_restored() + record("nav_back_about_to_home", back_ok, + "" if back_ok else "behavior_wrong: BACK from the About dialog did not " + "restore the home surface", + depth=1, jump_kind="reach", + expect="home 'Off' + 'Quick Actions' restored after one BACK from About") + + +TESTS = [ + # depth-1 reach + test_reach_morse, + test_reach_interval, + test_reach_interval_vlm, + test_reach_links, + test_reach_about, + test_reach_settings, + # depth-2 chains + test_reach_icon_credits_depth2, + test_reach_preferred_level_depth2, + test_reach_settings_links_depth2, + # back-stack integrity + test_back_from_morse_returns_home, + test_back_from_settings_returns_home, + test_up_arrow_from_settings_returns_home, + test_backstack_icon_credits_unwinds, + test_backstack_preferred_level_unwinds, + test_back_from_links_returns_home, + test_back_from_about_returns_home, +] + +if __name__ == "__main__": + run_suite(TESTS, "navigation") diff --git a/android/cyb3rko-flashdim/tests/test_android_states.py b/android/cyb3rko-flashdim/tests/test_android_states.py new file mode 100644 index 0000000000000000000000000000000000000000..2af5ebf8d91fa76063ec5999a50b6a67e67b2806 --- /dev/null +++ b/android/cyb3rko-flashdim/tests/test_android_states.py @@ -0,0 +1,851 @@ +#!/usr/bin/env python3 +"""STATES lane — FlashDim. + +CHECKED / ENABLED / SELECTED / FOCUSED transitions PAIRED with their app-authored +consequence, page-level state machines, conditional enable/disable, and SETTINGS +persistence across process death. This lane is the sole owner of `checked` and of +focus. + +Every test is BEFORE -> interact -> AFTER: observe the widget state from a fresh +ui(), interact through the real user path, re-dump, assert the state FLIPPED, and +where the app authors a consequence assert that too. All expected values were +observed on the running original before this file was authored. + +Run: + ADB_PATH=/opt/android/platform-tools/adb DEVICE_SERIAL=emulator-5554 \ + python3 test_android_states.py +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ── Home helper (FlashDim's task back-stack can survive force_stop, so a bare +# restart_app() may resume on SettingsActivity — back out until home is showing). +def _go_home(): + for _ in range(5): + if node_by_id(ui(), "level_indicator") is not None: + return True + back() + settle("tap") + return node_by_id(ui(), "level_indicator") is not None + + +def _home_ready(): + """Fresh app on the home screen. Returns the home nodes or None.""" + restart_app() + wait_for_foreground() + if not _go_home(): + return None + return ui() + + +def _clean_home(): + """Wiped app on the home screen (known defaults). Returns nodes or None.""" + clear_data() + launch_app() + wait_for_foreground() + if not _go_home(): + return None + return ui() + + +# ── Settings helpers ──────────────────────────────────────────────────────────── +def and_enter_settings(): + """Open SettingsActivity from home. Backs a depth>=1 declaration. + + Returns the settings nodes, or None if the settings action could not be + reached / the surface did not change. + """ + nodes = ui() + trigger = node_by_id(nodes, "settings_action") + if trigger is None: + return None + before = and_showing(nodes) + if not tap_node(trigger): + return None + settle("launch") + after = and_showing() + if not surface_changed(before, after): + return None + and_enter("settings") + return ui() + + +def _switch_for(title_text, nodes=None): + """The Switch widget whose vertical centre is closest to the preference row + titled `title_text` (within ~80px). All switches share resource-id + `switchWidget`, so they are disambiguated by y-proximity to their title.""" + nodes = ui() if nodes is None else nodes + row = next((n for n in nodes if n.get("text") == title_text), None) + if row is None: + row = find_node_ci(nodes, title_text) + if row is None or "_bounds" not in row: + return None + ry = (row["_bounds"][1] + row["_bounds"][3]) // 2 + best, best_d = None, 10 ** 9 + for n in nodes: + if "Switch" in n.get("class", "") and "_bounds" in n: + sy = (n["_bounds"][1] + n["_bounds"][3]) // 2 + d = abs(sy - ry) + if d < best_d: + best_d, best = d, n + return best if best_d < 80 else None + + +def _dismiss_restart_dialog(): + """Vibration toggles can pop a 'Restart app?' dialog — dismiss with 'Later' + so the test never leaves a modal on screen. No-op if none is present.""" + later = find_node_ci(ui(), "Later") + if later is not None: + tap_node(later) + settle("tap") + + +# ══════════════════════════════════════════════════════════════════════════════ +# A. Settings switch CHECKED transitions (depth 1, backed by and_enter_settings) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_instant_flash_toggle", "states_switch_on_visual_vlm")) +def test_instant_flash_checked_transition(): + """'Instant flash' default OFF -> tap -> ON (checked false->true).""" + NAME = "states_instant_flash_toggle" + if _clean_home() is None: + record(NAME, False, "setup_failed: could not reach home", depth=1, + jump_kind="transition", expect="checked false->true") + return + if and_enter_settings() is None: + record(NAME, False, "setup_failed: could not open Settings", depth=1, + jump_kind="transition", expect="checked false->true") + return + sw = _switch_for("Instant flash") + if sw is None: + record(NAME, False, "feature_missing: no 'Instant flash' switch", depth=1, + jump_kind="transition", expect="checked false->true") + return + before = sw.get("checked") + tap_node(sw) + after = (_switch_for("Instant flash") or {}).get("checked") + ok = before == "false" and after == "true" + record(NAME, ok, "" if ok else + f"behavior_wrong: 'Instant flash' checked did not go false->true " + f"(before={before} after={after})", + depth=1, jump_kind="transition", expect="checked false->true") + # Paired VLM: the switch is now visually in the ON position. + vlm_assert("states_switch_on_visual", "In the settings list, is the toggle " + "switch on the 'Instant flash' row in the ON position — its thumb " + "pushed to the RIGHT with a filled/coloured track (not grey)?", + sys.argv[2], expect="YES", depth=1, jump_kind="transition", + tag="position") + + +@and_test(expects=("states_context_awareness_toggle", "states_switch_off_visual_vlm")) +def test_context_awareness_checked_transition(): + """'Context awareness' default OFF -> tap -> ON. Also VLM-checks a DIFFERENT + switch ('Quick settings toggle link') that is left OFF, for the OFF visual.""" + NAME = "states_context_awareness_toggle" + if _clean_home() is None: + record(NAME, False, "setup_failed: could not reach home", depth=1, + jump_kind="transition", expect="checked false->true") + return + if and_enter_settings() is None: + record(NAME, False, "setup_failed: could not open Settings", depth=1, + jump_kind="transition", expect="checked false->true") + return + sw = _switch_for("Context awareness") + if sw is None: + record(NAME, False, "feature_missing: no 'Context awareness' switch", + depth=1, jump_kind="transition", expect="checked false->true") + return + before = sw.get("checked") + tap_node(sw) + after = (_switch_for("Context awareness") or {}).get("checked") + ok = before == "false" and after == "true" + record(NAME, ok, "" if ok else + f"behavior_wrong: 'Context awareness' checked not false->true " + f"(before={before} after={after})", + depth=1, jump_kind="transition", expect="checked false->true") + # VLM: a switch we did NOT touch stays visually OFF ('Quick settings toggle + # link' is checked=false on a clean install). + vlm_assert("states_switch_off_visual", "Look at the 'Quick settings toggle " + "link' row's toggle switch: is it in the OFF position — thumb to " + "the LEFT over a grey/uncoloured track?", sys.argv[2], + expect="YES", depth=1, jump_kind="transition", tag="position") + + +@and_test(expects=("states_toggle_mode_off",)) +def test_quick_toggle_mode_checked_transition(): + """'Quick settings toggle mode' starts ON (checked=true) -> tap -> OFF.""" + NAME = "states_toggle_mode_off" + if _clean_home() is None: + record(NAME, False, "setup_failed: could not reach home", depth=1, + jump_kind="transition", expect="checked true->false") + return + if and_enter_settings() is None: + record(NAME, False, "setup_failed: could not open Settings", depth=1, + jump_kind="transition", expect="checked true->false") + return + sw = _switch_for("Quick settings toggle mode") + if sw is None: + record(NAME, False, "feature_missing: no 'Quick settings toggle mode' " + "switch", depth=1, jump_kind="transition", + expect="checked true->false") + return + before = sw.get("checked") + tap_node(sw) + after = (_switch_for("Quick settings toggle mode") or {}).get("checked") + ok = before == "true" and after == "false" + record(NAME, ok, "" if ok else + f"behavior_wrong: toggle mode checked not true->false " + f"(before={before} after={after})", + depth=1, jump_kind="transition", expect="checked true->false") + + +# ── Conditional enable/disable (a paired consequence: flip A, B's enabled flips) +@and_test(expects=("states_extension_enabled_by_instant", + "states_extension_disabled_visual_vlm")) +def test_instant_flash_enables_extension(): + """'Instant flash extension' is DISABLED (enabled=false) until 'Instant + flash' is ON. Assert extension enabled=false initially, toggle 'Instant + flash' ON, then assert extension enabled becomes true.""" + NAME = "states_extension_enabled_by_instant" + if _clean_home() is None: + record(NAME, False, "setup_failed: could not reach home", depth=1, + jump_kind="transition", expect="extension enabled false->true") + return + if and_enter_settings() is None: + record(NAME, False, "setup_failed: could not open Settings", depth=1, + jump_kind="transition", expect="extension enabled false->true") + return + ext = _switch_for("Instant flash extension") + inst = _switch_for("Instant flash") + if ext is None or inst is None: + record(NAME, False, "feature_missing: extension or instant switch absent", + depth=1, jump_kind="transition", + expect="extension enabled false->true") + return + # VLM first, while the extension row is still disabled/dimmed. + vlm_assert("states_extension_disabled_visual", "Does the 'Instant flash " + "extension' row (its title, summary and toggle) appear " + "greyed-out / dimmed compared to the fully-black rows above and " + "below it, indicating it is disabled?", sys.argv[2], + expect="YES", depth=1, jump_kind="transition", tag="color") + ext_before = ext.get("enabled") + tap_node(inst) # turn Instant flash ON + ext2 = _switch_for("Instant flash extension") + ext_after = (ext2 or {}).get("enabled") + ok = ext_before == "false" and ext_after == "true" + record(NAME, ok, "" if ok else + f"behavior_wrong: extension enabled did not go false->true after " + f"enabling Instant flash (before={ext_before} after={ext_after})", + depth=1, jump_kind="transition", expect="extension enabled false->true") + + +@and_test(expects=("states_toggle_link_disabled_by_mode",)) +def test_toggle_mode_disables_link(): + """'Quick settings toggle link' depends on 'Quick settings toggle mode'. + Mode is ON by default so link starts enabled; toggling mode OFF must disable + the link (enabled true->false).""" + NAME = "states_toggle_link_disabled_by_mode" + if _clean_home() is None: + record(NAME, False, "setup_failed: could not reach home", depth=1, + jump_kind="transition", expect="link enabled true->false") + return + if and_enter_settings() is None: + record(NAME, False, "setup_failed: could not open Settings", depth=1, + jump_kind="transition", expect="link enabled true->false") + return + mode = _switch_for("Quick settings toggle mode") + link = _switch_for("Quick settings toggle link") + if mode is None or link is None: + record(NAME, False, "feature_missing: mode or link switch absent", + depth=1, jump_kind="transition", expect="link enabled true->false") + return + link_before = link.get("enabled") + tap_node(mode) # turn toggle mode OFF + link2 = _switch_for("Quick settings toggle link") + link_after = (link2 or {}).get("enabled") + ok = link_before == "true" and link_after == "false" + record(NAME, ok, "" if ok else + f"behavior_wrong: link enabled did not go true->false after turning " + f"toggle mode OFF (before={link_before} after={link_after})", + depth=1, jump_kind="transition", expect="link enabled true->false") + + +# ══════════════════════════════════════════════════════════════════════════════ +# B. SETTINGS PERSISTENCE across process death (depth 1, transition) — keystone +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_context_awareness_persists",)) +def test_context_awareness_persists_across_death(): + """Toggle 'Context awareness' OFF->ON, kill+relaunch the process, reopen + Settings, assert it is STILL checked=true. An in-memory-only recreation + fails this.""" + NAME = "states_context_awareness_persists" + if _clean_home() is None: + record(NAME, False, "setup_failed: could not reach home", depth=1, + jump_kind="transition", expect="checked stays true after relaunch") + return + if and_enter_settings() is None: + record(NAME, False, "setup_failed: could not open Settings", depth=1, + jump_kind="transition", expect="checked stays true after relaunch") + return + sw = _switch_for("Context awareness") + if sw is None: + record(NAME, False, "feature_missing: no 'Context awareness' switch", + depth=1, jump_kind="transition", + expect="checked stays true after relaunch") + return + if sw.get("checked") != "false": + record(NAME, False, "setup_failed: 'Context awareness' not OFF on a clean " + "install", depth=1, jump_kind="transition", + expect="checked stays true after relaunch") + return + tap_node(sw) + if (_switch_for("Context awareness") or {}).get("checked") != "true": + record(NAME, False, "behavior_wrong: 'Context awareness' did not turn ON " + "before the persistence probe", depth=1, jump_kind="transition", + expect="checked stays true after relaunch") + return + force_stop_and_relaunch() + wait_for_foreground() + if not _go_home(): + record(NAME, False, "setup_failed: could not reach home after relaunch", + depth=1, jump_kind="transition", + expect="checked stays true after relaunch") + return + if and_enter_settings() is None: + record(NAME, False, "setup_failed: could not reopen Settings after " + "relaunch", depth=1, jump_kind="transition", + expect="checked stays true after relaunch") + return + after = (_switch_for("Context awareness") or {}).get("checked") + ok = after == "true" + record(NAME, ok, "" if ok else + f"behavior_wrong: 'Context awareness' did not persist across process " + f"death (checked={after} after relaunch)", + depth=1, jump_kind="transition", + expect="checked stays true after relaunch") + + +@and_test(expects=("states_instant_flash_persists",)) +def test_instant_flash_persists_across_death(): + """Toggle 'Instant flash' ON, kill+relaunch, reopen Settings, assert still + checked=true.""" + NAME = "states_instant_flash_persists" + if _clean_home() is None: + record(NAME, False, "setup_failed: could not reach home", depth=1, + jump_kind="transition", expect="checked stays true after relaunch") + return + if and_enter_settings() is None: + record(NAME, False, "setup_failed: could not open Settings", depth=1, + jump_kind="transition", expect="checked stays true after relaunch") + return + sw = _switch_for("Instant flash") + if sw is None: + record(NAME, False, "feature_missing: no 'Instant flash' switch", depth=1, + jump_kind="transition", expect="checked stays true after relaunch") + return + if sw.get("checked") != "false": + record(NAME, False, "setup_failed: 'Instant flash' not OFF on a clean " + "install", depth=1, jump_kind="transition", + expect="checked stays true after relaunch") + return + tap_node(sw) + if (_switch_for("Instant flash") or {}).get("checked") != "true": + record(NAME, False, "behavior_wrong: 'Instant flash' did not turn ON " + "before the persistence probe", depth=1, jump_kind="transition", + expect="checked stays true after relaunch") + return + force_stop_and_relaunch() + wait_for_foreground() + if not _go_home(): + record(NAME, False, "setup_failed: could not reach home after relaunch", + depth=1, jump_kind="transition", + expect="checked stays true after relaunch") + return + if and_enter_settings() is None: + record(NAME, False, "setup_failed: could not reopen Settings after " + "relaunch", depth=1, jump_kind="transition", + expect="checked stays true after relaunch") + return + after = (_switch_for("Instant flash") or {}).get("checked") + ok = after == "true" + record(NAME, ok, "" if ok else + f"behavior_wrong: 'Instant flash' did not persist across process " + f"death (checked={after} after relaunch)", + depth=1, jump_kind="transition", + expect="checked stays true after relaunch") + + +# ══════════════════════════════════════════════════════════════════════════════ +# C. Page-level state machine: SOS mode (home, depth 0, transition) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_sos_enter_disables_controls", + "states_sos_buttons_gone_vlm", + "states_sos_greyed_vlm")) +def test_sos_enter_state_machine(): + """Tap SOS: sos_button enabled true->false, seek_bar enabled true->false, + and the mid quick-buttons (Maximum/Half/Minimum) disappear. Same Activity + throughout (a state change, not a navigation).""" + NAME = "states_sos_enter_disables_controls" + nodes = _home_ready() + if nodes is None: + record(NAME, False, "setup_failed: could not reach home", depth=0, + jump_kind="transition", + expect="sos enabled true->false; mid buttons gone") + return + act0 = get_current_activity() + sos = node_by_id(nodes, "sos_button") + seek = node_by_id(nodes, "seek_bar") + if sos is None or seek is None: + record(NAME, False, "feature_missing: sos_button or seek_bar absent", + depth=0, jump_kind="transition", + expect="sos enabled true->false; mid buttons gone") + return + sos_before = sos.get("enabled") + seek_before = seek.get("enabled") + mid_before = all(node_by_id(nodes, r) is not None + for r in ("max_button", "half_button", "min_button")) + tap_node(sos) + fresh = ui() + act1 = get_current_activity() + sos_after = (node_by_id(fresh, "sos_button") or {}).get("enabled") + seek_after = (node_by_id(fresh, "seek_bar") or {}).get("enabled") + mid_after_gone = all(node_by_id(fresh, r) is None + for r in ("max_button", "half_button", "min_button")) + off_still = (node_by_id(fresh, "off_button") or {}).get("enabled") + ok = (act0 == act1 and sos_before == "true" and sos_after == "false" + and seek_before == "true" and seek_after == "false" + and mid_before and mid_after_gone and off_still == "true") + record(NAME, ok, "" if ok else + f"behavior_wrong: SOS enter did not disable controls / hide buttons " + f"(sos {sos_before}->{sos_after}, seek {seek_before}->{seek_after}, " + f"mid_gone={mid_after_gone}, off={off_still}, act {act0}=={act1})", + depth=0, jump_kind="transition", + expect="sos enabled true->false; seek disabled; mid buttons gone") + vlm_assert("states_sos_buttons_gone", "Are the 'Maximum', 'Half' and " + "'Minimum' brightness buttons NO LONGER visible, leaving only the " + "'SOS' and 'Off' buttons in the button area?", sys.argv[2], + expect="YES", depth=0, jump_kind="transition", tag="shape") + vlm_assert("states_sos_greyed", "Is the 'SOS' button visibly greyed-out / " + "dimmed (disabled) while the 'Off' button remains fully coloured " + "and active?", sys.argv[2], expect="YES", depth=0, + jump_kind="transition", tag="color") + + +@and_test(expects=("states_sos_exit_restores_controls",)) +def test_sos_exit_restores_state_machine(): + """From SOS mode, tap Off: sos_button enabled false->true, seek_bar + enabled false->true, mid buttons reappear, level_indicator back to '0 / 10'. + Asserts the enabled/visibility transitions restore.""" + NAME = "states_sos_exit_restores_controls" + nodes = _home_ready() + if nodes is None: + record(NAME, False, "setup_failed: could not reach home", depth=0, + jump_kind="transition", + expect="sos enabled false->true; mid buttons back") + return + act0 = get_current_activity() + sos = node_by_id(nodes, "sos_button") + if sos is None: + record(NAME, False, "feature_missing: sos_button absent", depth=0, + jump_kind="transition", + expect="sos enabled false->true; mid buttons back") + return + tap_node(sos) # enter SOS + in_sos = ui() + sos_in = (node_by_id(in_sos, "sos_button") or {}).get("enabled") + mid_gone = all(node_by_id(in_sos, r) is None + for r in ("max_button", "half_button", "min_button")) + off = node_by_id(in_sos, "off_button") + if off is None or sos_in != "false": + record(NAME, False, "setup_failed: SOS mode not established (sos_in=" + f"{sos_in}, off_present={off is not None})", depth=0, + jump_kind="transition", + expect="sos enabled false->true; mid buttons back") + return + tap_node(off) # exit SOS + fresh = ui() + act1 = get_current_activity() + sos_out = (node_by_id(fresh, "sos_button") or {}).get("enabled") + seek_out = (node_by_id(fresh, "seek_bar") or {}).get("enabled") + mid_back = all(node_by_id(fresh, r) is not None + for r in ("max_button", "half_button", "min_button")) + level_out = (node_by_id(fresh, "level_indicator") or {}).get("text") + ok = (act0 == act1 and sos_in == "false" and mid_gone + and sos_out == "true" and seek_out == "true" and mid_back + and level_out == "0 / 10") + record(NAME, ok, "" if ok else + f"behavior_wrong: exiting SOS did not restore controls " + f"(sos {sos_in}->{sos_out}, mid_gone={mid_gone}, mid_back={mid_back}, " + f"seek={seek_out}, level={level_out!r})", + depth=0, jump_kind="transition", + expect="sos enabled false->true; seek enabled; mid buttons back; " + "level '0 / 10'") + + +@and_test(expects=("states_sos_level_indicator",)) +def test_sos_level_indicator_consequence(): + """The SOS state machine's mode consequence on the level_indicator widget: + outside SOS it shows a numeric level readout ('N / 10'); entering SOS switches + it to the mode string 'SOS mode', and exiting switches it back to a numeric + readout. This is a state-driven CHANGE of the same indicator (the exact + numeric value is computation's; the mode flip is this lane's).""" + NAME = "states_sos_level_indicator" + nodes = _home_ready() + if nodes is None: + record(NAME, False, "setup_failed: could not reach home", depth=0, + jump_kind="transition", + expect="numeric readout -> 'SOS mode' -> numeric readout") + return + # Pin a known non-SOS state (the app restores the last brightness on launch, + # so the pre-value is otherwise nondeterministic — Off gives '0 / 10'). + off0 = node_by_id(nodes, "off_button") + if off0 is not None: + tap_node(off0) + nodes = ui() + li = node_by_id(nodes, "level_indicator") + sos = node_by_id(nodes, "sos_button") + if li is None or sos is None: + record(NAME, False, "feature_missing: level_indicator or sos_button " + "absent", depth=0, jump_kind="transition", + expect="numeric readout -> 'SOS mode' -> numeric readout") + return + before = li.get("text") + tap_node(sos) + during = (node_by_id(ui(), "level_indicator") or {}).get("text") + # restore for isolation + off = node_by_id(ui(), "off_button") + if off is not None: + tap_node(off) + after = (node_by_id(ui(), "level_indicator") or {}).get("text") + ok = (before != "SOS mode" and "/" in (before or "") + and during == "SOS mode" + and after != "SOS mode" and "/" in (after or "")) + record(NAME, ok, "" if ok else + f"behavior_wrong: level indicator did not switch numeric<->'SOS mode' " + f"(before={before!r} during={during!r} after={after!r})", + depth=0, jump_kind="transition", + expect="numeric readout -> 'SOS mode' -> numeric readout") + + +# ══════════════════════════════════════════════════════════════════════════════ +# D. Interval dialog RadioButton SELECTED transition (depth 1, backed by helper) +# ══════════════════════════════════════════════════════════════════════════════ + +def and_enter_interval_dialog(): + """Open the Interval Flash dialog from home. Backs a depth>=1 declaration. + Returns the dialog nodes, or None.""" + nodes = ui() + trigger = node_by_id(nodes, "interval_button") + if trigger is None: + return None + before = and_showing(nodes) + if not tap_node(trigger): + return None + after = and_showing() + if not surface_changed(before, after): + return None + and_enter("interval_dialog") + return ui() + + +@and_test(expects=("states_interval_radio_bpm", + "states_interval_time_selected_vlm", + "states_interval_bpm_selected_vlm")) +def test_interval_radio_selected_transition(): + """TIME radio starts selected (checked=true), BPM unselected. Tap BPM: BPM + checked false->true, TIME checked true->false, plus the app-authored + consequence (input '500'->'100' and the 'ms' suffix disappears).""" + NAME = "states_interval_radio_bpm" + if _home_ready() is None: + record(NAME, False, "setup_failed: could not reach home", depth=1, + jump_kind="transition", expect="BPM selected; TIME deselected") + return + nodes = and_enter_interval_dialog() + if nodes is None: + record(NAME, False, "setup_failed: could not open Interval dialog", + depth=1, jump_kind="transition", + expect="BPM selected; TIME deselected") + return + time_b = node_by_id(nodes, "time_button") + bpm_b = node_by_id(nodes, "bpm_button") + if time_b is None or bpm_b is None: + record(NAME, False, "feature_missing: TIME/BPM radio buttons absent", + depth=1, jump_kind="transition", + expect="BPM selected; TIME deselected") + return + time_before = time_b.get("checked") + bpm_before = bpm_b.get("checked") + num_before = (node_by_id(nodes, "number_input_text") or {}).get("text") + suffix_before = node_by_id(nodes, "textinput_suffix_text") is not None + # VLM: TIME currently selected. + vlm_assert("states_interval_time_selected", "In this dialog with 'TIME' and " + "'BPM' radio options, is 'TIME' the selected one — its radio " + "circle filled/coloured — while 'BPM' is unfilled?", sys.argv[2], + expect="YES", depth=1, jump_kind="transition", tag="shape") + tap_node(bpm_b) + fresh = ui() + time_after = (node_by_id(fresh, "time_button") or {}).get("checked") + bpm_after = (node_by_id(fresh, "bpm_button") or {}).get("checked") + num_after = (node_by_id(fresh, "number_input_text") or {}).get("text") + suffix_after = node_by_id(fresh, "textinput_suffix_text") is not None + radios_flipped = (time_before == "true" and bpm_before == "false" + and time_after == "false" and bpm_after == "true") + consequence = (num_before == "500" and num_after == "100" + and suffix_before and not suffix_after) + ok = radios_flipped and consequence + record(NAME, ok, "" if ok else + f"behavior_wrong: BPM radio flip / consequence failed " + f"(TIME {time_before}->{time_after}, BPM {bpm_before}->{bpm_after}, " + f"num {num_before!r}->{num_after!r}, suffix {suffix_before}->" + f"{suffix_after})", + depth=1, jump_kind="transition", + expect="BPM checked true, TIME false; input 500->100, 'ms' suffix gone") + # VLM: BPM now selected. + vlm_assert("states_interval_bpm_selected", "Now is 'BPM' the selected radio " + "option — its circle filled/coloured — while 'TIME' is unfilled?", + sys.argv[2], expect="YES", depth=1, jump_kind="transition", + tag="shape") + + +@and_test(expects=("states_interval_radio_time_restore",)) +def test_interval_radio_restore_transition(): + """After selecting BPM, tapping TIME restores TIME selected (checked + false->true) and BPM deselected (checked true->false) — the reverse + transition of the same radio group.""" + NAME = "states_interval_radio_time_restore" + if _home_ready() is None: + record(NAME, False, "setup_failed: could not reach home", depth=1, + jump_kind="transition", expect="TIME re-selected; BPM deselected") + return + nodes = and_enter_interval_dialog() + if nodes is None: + record(NAME, False, "setup_failed: could not open Interval dialog", + depth=1, jump_kind="transition", + expect="TIME re-selected; BPM deselected") + return + bpm_b = node_by_id(nodes, "bpm_button") + time_b = node_by_id(nodes, "time_button") + if bpm_b is None or time_b is None: + record(NAME, False, "feature_missing: TIME/BPM radio buttons absent", + depth=1, jump_kind="transition", + expect="TIME re-selected; BPM deselected") + return + tap_node(bpm_b) # go to BPM + mid = ui() + bpm_mid = (node_by_id(mid, "bpm_button") or {}).get("checked") + time_mid = (node_by_id(mid, "time_button") or {}).get("checked") + tb2 = node_by_id(mid, "time_button") + tap_node(tb2) # back to TIME + fresh = ui() + time_after = (node_by_id(fresh, "time_button") or {}).get("checked") + bpm_after = (node_by_id(fresh, "bpm_button") or {}).get("checked") + ok = (bpm_mid == "true" and time_mid == "false" + and time_after == "true" and bpm_after == "false") + record(NAME, ok, "" if ok else + f"behavior_wrong: TIME not restored as selected " + f"(mid TIME={time_mid} BPM={bpm_mid}; after TIME={time_after} " + f"BPM={bpm_after})", + depth=1, jump_kind="transition", + expect="TIME checked false->true, BPM checked true->false") + + +# ══════════════════════════════════════════════════════════════════════════════ +# E. Home level buttons — SELECTED / focus & seekbar-fill VLM (depth 0) +# The level indicator is a computed value (computation's); here we assert the +# STATE consequence a level change produces on the canvas-drawn seekbar fill. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_max_level_fill_vlm",)) +def test_max_level_seekbar_fill(): + """Tap Maximum: the level indicator reads '10 / 10' (state precondition) and + the canvas-drawn seekbar shows ALL segments filled (VLM — not in the tree).""" + NAME = "states_max_level_fill" + nodes = _home_ready() + if nodes is None: + vlm_assert(NAME, "n/a", sys.argv[2], expect="YES", depth=0, + jump_kind="transition", tag="color") + return + mx = node_by_id(nodes, "max_button") + if mx is not None: + tap_node(mx) + vlm_assert(NAME, "Look at the vertical segmented brightness bar on the left. " + "Is it COMPLETELY filled — every one of its ~10 segments in the " + "light/highlight colour with none left dark?", sys.argv[2], + expect="YES", depth=0, jump_kind="transition", tag="color") + + +@and_test(expects=("states_min_level_fill_vlm",)) +def test_min_level_seekbar_fill(): + """Tap Minimum: only the single bottom segment of the seekbar is highlighted; + the upper ~9 are dark (VLM).""" + NAME = "states_min_level_fill" + nodes = _home_ready() + if nodes is None: + vlm_assert(NAME, "n/a", sys.argv[2], expect="YES", depth=0, + jump_kind="transition", tag="position") + return + mn = node_by_id(nodes, "min_button") + if mn is not None: + tap_node(mn) + vlm_assert(NAME, "Look at the vertical segmented brightness bar. Is ONLY the " + "single bottom segment highlighted/lit while all the segments " + "above it are dark grey?", sys.argv[2], expect="YES", depth=0, + jump_kind="transition", tag="position") + + +@and_test(expects=("states_half_level_fill_vlm",)) +def test_half_level_seekbar_fill(): + """Tap Half: roughly the bottom half (~5 of 10) of the seekbar segments are + highlighted, the top half dark (VLM).""" + NAME = "states_half_level_fill" + nodes = _home_ready() + if nodes is None: + vlm_assert(NAME, "n/a", sys.argv[2], expect="YES", depth=0, + jump_kind="transition", tag="size") + return + hf = node_by_id(nodes, "half_button") + if hf is not None: + tap_node(hf) + vlm_assert(NAME, "Look at the vertical segmented brightness bar. Are roughly " + "the bottom HALF (about 5 of ~10) of its segments highlighted and " + "the top half dark?", sys.argv[2], expect="YES", depth=0, + jump_kind="transition", tag="size") + + +@and_test(expects=("states_off_level_fill_vlm",)) +def test_off_level_seekbar_fill(): + """Tap Off: the seekbar shows NO segments highlighted (all dark) — the empty + state of the fill (VLM).""" + NAME = "states_off_level_fill" + nodes = _home_ready() + if nodes is None: + vlm_assert(NAME, "n/a", sys.argv[2], expect="YES", depth=0, + jump_kind="transition", tag="color") + return + # go up first then Off, so the transition to empty is real + mx = node_by_id(nodes, "max_button") + if mx is not None: + tap_node(mx) + off = node_by_id(ui(), "off_button") + if off is not None: + tap_node(off) + vlm_assert(NAME, "Look at the vertical segmented brightness bar. Are ALL of " + "its segments dark/unfilled with NONE highlighted?", sys.argv[2], + expect="YES", depth=0, jump_kind="transition", tag="color") + + +@and_test(expects=("states_brightness_button_active_vlm",)) +def test_brightness_buttons_active_style(): + """After tapping Maximum, the three brightness buttons (Maximum/Half/Minimum) + render as filled light-coloured pills while SOS/Morse/Interval stay greyed + tonal buttons — the active-group visual state (VLM).""" + NAME = "states_brightness_button_active" + nodes = _home_ready() + if nodes is None: + vlm_assert(NAME, "n/a", sys.argv[2], expect="YES", depth=0, + jump_kind="transition", tag="color") + return + mx = node_by_id(nodes, "max_button") + if mx is not None: + tap_node(mx) + vlm_assert(NAME, "Do the three brightness buttons 'Maximum', 'Half' and " + "'Minimum' appear as filled LIGHT-coloured pills, while the 'SOS', " + "'Morse' and 'Interval' buttons are darker/greyed tonal buttons?", + sys.argv[2], expect="YES", depth=0, jump_kind="transition", + tag="color") + + +# ══════════════════════════════════════════════════════════════════════════════ +# F. Focus — this lane owns `focused` +# ══════════════════════════════════════════════════════════════════════════════ + +def and_enter_morse_dialog(): + """Open the Flash-morse-code dialog from home. Backs a depth>=1 declaration. + Returns the dialog nodes, or None.""" + nodes = ui() + trigger = node_by_id(nodes, "morse_button") + if trigger is None: + return None + before = and_showing(nodes) + if not tap_node(trigger): + return None + after = and_showing() + if not surface_changed(before, after): + return None + and_enter("morse_dialog") + return ui() + + +@and_test(expects=("states_morse_input_focus",)) +def test_morse_input_receives_focus(): + """Tapping the Morse message field puts focus on it: focused false->true on + the message EditText (this lane owns `focused`).""" + NAME = "states_morse_input_focus" + if _home_ready() is None: + record(NAME, False, "setup_failed: could not reach home", depth=1, + jump_kind="transition", expect="message field focused false->true") + return + nodes = and_enter_morse_dialog() + if nodes is None: + record(NAME, False, "setup_failed: could not open Morse dialog", depth=1, + jump_kind="transition", expect="message field focused false->true") + return + field = node_by_id(nodes, "text_input_text") + if field is None: + field = next((n for n in nodes if "EditText" in n.get("class", "")), None) + if field is None: + record(NAME, False, "feature_missing: no message EditText in Morse dialog", + depth=1, jump_kind="transition", + expect="message field focused false->true") + return + focus_before = field.get("focused") + tap_node(field) + settle("keyboard") + refreshed = find_closest_match(ui(), field) or {} + focus_after = refreshed.get("focused") + ok = focus_before != "true" and focus_after == "true" + record(NAME, ok, "" if ok else + f"behavior_wrong: message field did not gain focus " + f"(before={focus_before} after={focus_after})", + depth=1, jump_kind="transition", + expect="message field focused false->true") + hide_keyboard() + + +# ══════════════════════════════════════════════════════════════════════════════ + +TESTS = [ + # A. settings switch checked transitions + conditional enable/disable + test_instant_flash_checked_transition, + test_context_awareness_checked_transition, + test_quick_toggle_mode_checked_transition, + test_instant_flash_enables_extension, + test_toggle_mode_disables_link, + # B. persistence across process death (keystone) + test_context_awareness_persists_across_death, + test_instant_flash_persists_across_death, + # C. SOS state machine + test_sos_enter_state_machine, + test_sos_exit_restores_state_machine, + test_sos_level_indicator_consequence, + # D. interval radio selected transition + test_interval_radio_selected_transition, + test_interval_radio_restore_transition, + # E. seekbar fill / brightness active-group (VLM) + test_max_level_seekbar_fill, + test_min_level_seekbar_fill, + test_half_level_seekbar_fill, + test_off_level_seekbar_fill, + test_brightness_buttons_active_style, + # F. focus + test_morse_input_receives_focus, +] + +if __name__ == "__main__": + run_suite(TESTS, "states") diff --git a/android/cyb3rko-flashdim/tests/test_android_structure.py b/android/cyb3rko-flashdim/tests/test_android_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..3cc3d68d7f57b6508cf5b53a6b8a49e29f928d41 --- /dev/null +++ b/android/cyb3rko-flashdim/tests/test_android_structure.py @@ -0,0 +1,524 @@ +#!/usr/bin/env python3 +"""STRUCTURE-lane behavioral suite for FlashDim. + +Owns: (1) the launch GATE (MainActivity + its top-level surfaces exist) and +(2) tree-SHAPE deltas — a trigger changes the child-count / subtree presence of +the tree. Content (strings), state (checked/enabled), reachability, and computed +values are CEDED to their own lanes; here we only assert SHAPE (counts, subtree +appears/disappears), and always reverse a delta to show it restores. +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else "/workspace/testgen/eval/results" + + +# ────────────────────────────────────────────────────────────────────────────── +# Depth-family helpers. A declared depth>=1 must be backed by a real +# and_enter_*/and_reach_* call so the depth audit sees genuine navigation. +# Each returns the "before" (home) node list so the test can compare shapes. +# ────────────────────────────────────────────────────────────────────────────── + +def _home_ready(): + """Restart to a settled MainActivity and return its node list.""" + restart_app() + wait_for_foreground() + return ui() + + +def and_enter_morse_dialog(home): + """Tap morse_button, wait for the AlertDialog subtree, cross one surface.""" + n = node_by_id(home, "morse_button") + if not tap_node(n): + return None + settle("tap") + and_enter("morse_dialog") + return ui() + + +def and_enter_interval_dialog(home): + """Tap interval_button → Interval AlertDialog subtree; cross one surface.""" + n = node_by_id(home, "interval_button") + if not tap_node(n): + return None + settle("tap") + and_enter("interval_dialog") + return ui() + + +def and_enter_links_dialog(home): + """Toolbar links_action → Links AlertDialog subtree; cross one surface.""" + n = node_by_id(home, "links_action") + if not tap_node(n): + return None + settle("tap") + and_enter("links_dialog") + return ui() + + +def and_enter_about_dialog(home): + """Toolbar icon_credits_action → About AlertDialog subtree; cross one surface.""" + n = node_by_id(home, "icon_credits_action") + if not tap_node(n): + return None + settle("tap") + and_enter("about_dialog") + return ui() + + +def and_enter_settings(home): + """Toolbar settings_action → SettingsActivity; cross one surface.""" + n = node_by_id(home, "settings_action") + if not tap_node(n): + return None + settle("launch") + and_enter("settings") + return ui() + + +def _visible_button_keys(nodes): + """Set of on-screen Button/CompoundButton identity keys — the SHAPE of the + button set. Uses node_key so we compare identities, not raw strings order.""" + s = get_screen_info() + out = set() + for n in nodes: + cls = n.get("class", "") + if "Button" not in cls: + continue + 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 + + +# ────────────────────────────────────────────────────────────────────────────── +# GATE — pure existence of the top-level surfaces (jump_kind="none", depth 0). +# Kept to <=2 tests; the rest are shape deltas. +# ────────────────────────────────────────────────────────────────────────────── + +@and_test(expects=("structure_gate_launch",)) +def test_gate_launch(): + """App launches to MainActivity with its two anchor surfaces: the button + container (>=7 Button descendants) AND the custom seek_bar view.""" + home = _home_ready() + fg = wait_for_foreground() + container = node_by_id(home, "button_container") + n_buttons = len(_visible_button_keys(home)) + seek = node_by_id(home, "seek_bar") + ok = bool(fg and container and n_buttons >= 7 and seek) + msg = "" + if not fg: + msg = "setup_failed: app did not reach the foreground" + elif not container: + msg = "feature_missing: button_container not present on home" + elif n_buttons < 7: + msg = f"behavior_wrong: expected >=7 buttons on home, saw {n_buttons}" + elif not seek: + msg = "feature_missing: seek_bar not present on home" + record("structure_gate_launch", ok, msg, depth=0, jump_kind="none") + + +@and_test(expects=("structure_gate_toolbar",)) +def test_gate_toolbar(): + """The top app bar hosts its three action controls (link / settings / info), + matched by content-desc, not by internal id or string casing.""" + home = _home_ready() + bar = node_by_id(home, "top_app_bar") + links = node_by_id(home, "links_action") + settings = node_by_id(home, "settings_action") + credits = node_by_id(home, "icon_credits_action") + present = sum(1 for x in (links, settings, credits) if x) + ok = bool(bar and present == 3) + msg = ("" if ok else + f"feature_missing: top app bar host+3 actions incomplete " + f"(bar={bool(bar)}, actions={present}/3)") + record("structure_gate_toolbar", ok, msg, depth=0, jump_kind="none") + + +# ────────────────────────────────────────────────────────────────────────────── +# SHAPE DELTAS — in-place (depth 0) and dialog/activity (depth>=1, backed). +# ────────────────────────────────────────────────────────────────────────────── + +@and_test(expects=("structure_sos_shrinks_buttons", "structure_sos_shrinks_buttons_vlm")) +def test_sos_shrinks_button_set(): + """SOS mode is a MODE SWITCH that removes a whole class of buttons: tapping + sos_button hides morse/interval/max/half/min, so the visible-Button set + SHRINKS; tapping off_button restores it. Pure in-place shape delta, depth 0.""" + home = _home_ready() + before = _visible_button_keys(home) + n0 = len(before) + + ok_tap = tap_node(node_by_id(home, "sos_button")) + settle("tap") + mid_nodes = ui() + during = _visible_button_keys(mid_nodes) + n1 = len(during) + shrank = ok_tap and n1 < n0 + + # Reverse: Off exits SOS and the button set must grow back to the original. + off = node_by_id(mid_nodes, "off_button") + ok_off = tap_node(off) + settle("tap") + after = _visible_button_keys(ui()) + n2 = len(after) + restored = ok_off and n2 == n0 + + ok = bool(shrank and restored) + if not ok_tap: + msg = "setup_failed: sos_button not tappable" + elif not shrank: + msg = f"behavior_wrong: button set did not shrink on SOS ({n0}->{n1})" + elif not restored: + msg = f"behavior_wrong: button set not restored on Off ({n0}->{n1}->{n2})" + else: + msg = "" + record("structure_sos_shrinks_buttons", ok, msg, depth=0, jump_kind="transition", + expect=f"visible Button count {n0}->{n1} on SOS, restored to {n0} on Off") + + # VLM: in SOS the left button column collapses to exactly two rounded + # buttons ("SOS" greyed, "Off" highlighted) with an empty gap below — a + # self-contained count/position fact visible in this single frame. + home2 = _home_ready() + tap_node(node_by_id(home2, "sos_button")) + settle("tap") + vlm_assert("structure_sos_shrinks_buttons", + "On the LEFT side of this screen, are there exactly two rounded " + "buttons stacked at the top (one labelled 'SOS' and one labelled " + "'Off'), with empty space below them?", RESULTS_DIR, tag="position") + + +@and_test(expects=("structure_morse_dialog_editext",)) +def test_morse_dialog_adds_edittext(): + """Morse dialog adds a NEW window layer: home has 0 EditText; the dialog + subtree contributes an alert title + exactly one EditText. Reverse with BACK + and assert the EditText count returns to 0. depth 1, backed by helper.""" + home = _home_ready() + et_before = len(find_by_class(home, "EditText")) + + dlg = and_enter_morse_dialog(home) + if dlg is None: + record("structure_morse_dialog_editext", False, + "setup_failed: morse_button not tappable", depth=1, + jump_kind="transition", expect="EditText 0->1 in Morse dialog") + return + et_in = len(find_by_class(dlg, "EditText")) + title = node_by_id(dlg, "alertTitle") + added = et_in >= et_before + 1 and title is not None + + # Reverse: dismiss the dialog; the EditText subtree must be gone. + and_back() + settle("tap") + et_after = len(find_by_class(ui(), "EditText")) + restored = et_after == et_before + + ok = bool(added and restored) + if not added: + msg = (f"behavior_wrong: Morse dialog did not add an EditText " + f"(home={et_before}, dialog={et_in}, title={bool(title)})") + elif not restored: + msg = f"behavior_wrong: EditText not removed on BACK ({et_before}->{et_in}->{et_after})" + else: + msg = "" + record("structure_morse_dialog_editext", ok, msg, depth=1, jump_kind="transition", + expect=f"EditText {et_before}->{et_in} + alertTitle in Morse dialog, restored to {et_before}") + + +@and_test(expects=("structure_interval_radiobuttons",)) +def test_interval_dialog_adds_radiobuttons(): + """Interval dialog introduces a class of widget absent from home: home has 0 + RadioButtons; the dialog subtree has exactly 2 (TIME / BPM). Assert the + RadioButton count went 0->2, then BACK restores it to 0. depth 1, backed.""" + home = _home_ready() + rb_before = len(find_by_class(home, "RadioButton")) + + dlg = and_enter_interval_dialog(home) + if dlg is None: + record("structure_interval_radiobuttons", False, + "setup_failed: interval_button not tappable", depth=1, + jump_kind="transition", expect="RadioButton 0->2 in Interval dialog") + return + rb_in = len(find_by_class(dlg, "RadioButton")) + added = rb_in == rb_before + 2 + + and_back() + settle("tap") + rb_after = len(find_by_class(ui(), "RadioButton")) + restored = rb_after == rb_before + + ok = bool(added and restored) + if not added: + msg = (f"behavior_wrong: Interval dialog RadioButton count " + f"{rb_before}->{rb_in}, expected +2") + elif not restored: + msg = f"behavior_wrong: RadioButtons not removed on BACK ({rb_before}->{rb_in}->{rb_after})" + else: + msg = "" + record("structure_interval_radiobuttons", ok, msg, depth=1, jump_kind="transition", + expect=f"RadioButton {rb_before}->{rb_in} in Interval dialog, restored to {rb_before}") + + +@and_test(expects=("structure_interval_mode_suffix",)) +def test_interval_mode_toggles_suffix_subtree(): + """Within the Interval dialog, switching TIME->BPM removes the 'ms' suffix + node — a subtree-presence delta inside an already-open surface. Assert the + suffix node is present in TIME mode and gone in BPM mode, then restored. + depth 1 (backed by and_enter_interval_dialog).""" + home = _home_ready() + dlg = and_enter_interval_dialog(home) + if dlg is None: + record("structure_interval_mode_suffix", False, + "setup_failed: interval_button not tappable", depth=1, + jump_kind="transition", expect="suffix node present in TIME, gone in BPM") + return + suffix_time = node_by_id(dlg, "textinput_suffix_text") + present_time = suffix_time is not None + + ok_bpm = tap_node(node_by_id(dlg, "bpm_button")) + settle("tap") + bpm_nodes = ui() + suffix_bpm = node_by_id(bpm_nodes, "textinput_suffix_text") + gone_bpm = suffix_bpm is None + + # Reverse back to TIME: the suffix node must reappear. + ok_time = tap_node(node_by_id(bpm_nodes, "time_button")) + settle("tap") + suffix_back = node_by_id(ui(), "textinput_suffix_text") + restored = suffix_back is not None + + ok = bool(present_time and ok_bpm and gone_bpm and ok_time and restored) + if not present_time: + msg = "behavior_wrong: 'ms' suffix node missing in default TIME mode" + elif not gone_bpm: + msg = "behavior_wrong: 'ms' suffix node still present after switching to BPM" + elif not restored: + msg = "behavior_wrong: 'ms' suffix node did not return on switching back to TIME" + else: + msg = "" + record("structure_interval_mode_suffix", ok, msg, depth=1, jump_kind="transition", + expect="suffix subtree present in TIME -> absent in BPM -> restored in TIME") + + +@and_test(expects=("structure_links_dialog_visit_buttons",)) +def test_links_dialog_adds_visit_buttons(): + """Links dialog is a new window layer with 3 'Visit' row buttons that are not + on home. Assert the count of 'Visit'-labelled buttons went 0->3, BACK->0. + depth 1, backed by and_enter_links_dialog.""" + home = _home_ready() + + def _visit_count(nodes): + return len(find_nodes(nodes, text="Visit")) + + v_before = _visit_count(home) + dlg = and_enter_links_dialog(home) + if dlg is None: + record("structure_links_dialog_visit_buttons", False, + "setup_failed: links_action not tappable", depth=1, + jump_kind="transition", expect="'Visit' buttons 0->3 in Links dialog") + return + v_in = _visit_count(dlg) + added = v_in >= 3 and v_in > v_before + + and_back() + settle("tap") + v_after = _visit_count(ui()) + restored = v_after == v_before + + ok = bool(added and restored) + if not added: + msg = f"behavior_wrong: Links dialog 'Visit' buttons {v_before}->{v_in}, expected >=3" + elif not restored: + msg = f"behavior_wrong: 'Visit' buttons not removed on BACK ({v_before}->{v_in}->{v_after})" + else: + msg = "" + record("structure_links_dialog_visit_buttons", ok, msg, depth=1, jump_kind="transition", + expect=f"'Visit' button count {v_before}->{v_in} in Links dialog, restored to {v_before}") + + +@and_test(expects=("structure_about_dialog_appears",)) +def test_about_dialog_appears(): + """About dialog adds a window layer over home: it contributes an alert title + plus its own action buttons (button1/button3). Assert the alert panel + its + id-addressable buttons appear, then BACK removes it (home button set returns). + depth 1, backed.""" + home = _home_ready() + home_btns = len(_visible_button_keys(home)) + + dlg = and_enter_about_dialog(home) + if dlg is None: + record("structure_about_dialog_appears", False, + "setup_failed: icon_credits_action not tappable", depth=1, + jump_kind="transition", expect="alertTitle + >=2 dialog buttons appear") + return + title = node_by_id(dlg, "alertTitle") + # Count the dialog's OWN action buttons by id — home's underlying buttons + # stay in the tree behind the dialog and would inflate a raw class count. + dlg_btns = sum(1 for rid in ("button1", "button2", "button3") + if node_by_id(dlg, rid)) + appeared = title is not None and dlg_btns >= 2 + + and_back() + settle("tap") + after_btns = len(_visible_button_keys(ui())) + restored = after_btns == home_btns + + ok = bool(appeared and restored) + if not appeared: + msg = (f"behavior_wrong: About dialog panel incomplete " + f"(title={bool(title)}, dialog buttons={dlg_btns})") + elif not restored: + msg = f"behavior_wrong: dialog not dismissed on BACK (home buttons {home_btns}->{after_btns})" + else: + msg = "" + record("structure_about_dialog_appears", ok, msg, depth=1, jump_kind="transition", + expect=f"alertTitle + {dlg_btns} dialog buttons appear over home, removed on BACK") + + +@and_test(expects=("structure_settings_shape_flip",)) +def test_settings_activity_shape_flip(): + """Opening Settings flips the whole tree shape: home's button_container and + seek_bar are gone, replaced by a scrollable preference list (RecyclerView) + with many TextView title/summary rows. Assert the container disappears and a + scroll container with many rows appears; BACK restores home. depth 1, backed.""" + home = _home_ready() + home_container = node_by_id(home, "button_container") + + st = and_enter_settings(home) + if st is None: + record("structure_settings_shape_flip", False, + "setup_failed: settings_action not tappable", depth=1, + jump_kind="transition", + expect="button_container gone, scrollable preference list present") + return + st_container = node_by_id(st, "button_container") + scroller = (find_by_class(st, "RecyclerView") + or find_by_class(st, "ScrollView") + or find_by_class(st, "ListView")) + n_text = len(find_by_class(st, "TextView")) + flipped = st_container is None and bool(scroller) and n_text >= 8 + + and_back() + settle("launch") + home_again = node_by_id(ui(), "button_container") + restored = home_again is not None + + ok = bool(home_container is not None and flipped and restored) + if home_container is None: + msg = "setup_failed: button_container not on home before opening Settings" + elif not flipped: + msg = (f"behavior_wrong: Settings shape flip incomplete " + f"(container_gone={st_container is None}, scroller={bool(scroller)}, " + f"textviews={n_text})") + elif not restored: + msg = "behavior_wrong: home button_container did not return after leaving Settings" + else: + msg = "" + record("structure_settings_shape_flip", ok, msg, depth=1, jump_kind="transition", + expect="home button_container gone -> scrollable preference list " + f"({n_text} TextViews) in Settings, container restored on BACK") + + +@and_test(expects=("structure_settings_switch_rows",)) +def test_settings_has_many_switch_rows(): + """The Settings preference list has a class of widget the home tree never + shows: multiple Switch controls. Home has 0 Switches; Settings has several. + Assert Switch count 0 (home) -> many (Settings). depth 1, backed.""" + home = _home_ready() + sw_home = len(find_by_class(home, "Switch")) + + st = and_enter_settings(home) + if st is None: + record("structure_settings_switch_rows", False, + "setup_failed: settings_action not tappable", depth=1, + jump_kind="transition", expect="Switch count 0 (home) -> >=3 (Settings)") + return + sw_settings = len(find_by_class(st, "Switch")) + ok = sw_home == 0 and sw_settings >= 3 + msg = ("" if ok else + f"behavior_wrong: Switch count home={sw_home} settings={sw_settings}, " + f"expected 0 -> >=3") + record("structure_settings_switch_rows", ok, msg, depth=1, jump_kind="transition", + expect=f"Switch count {sw_home} (home) -> {sw_settings} (Settings)") + + +# ────────────────────────────────────────────────────────────────────────────── +# Remaining VLM records (spatial layout, unreadable from the dump). depth 0, +# jump_kind="none" — these describe the static rendered home surface. +# Total VLM records in this file = 5 (SOS layout above + the four below). +# ────────────────────────────────────────────────────────────────────────────── + +@and_test(expects=("structure_home_layout_vlm",)) +def test_home_layout_vlm(): + """Home layout is a two-column split: rounded action/brightness buttons fill + the LEFT half, and the segmented level indicator fills the RIGHT half.""" + _home_ready() + vlm_assert("structure_home_layout", + "Is the screen split into two columns, with a stack of rounded " + "buttons (SOS, Morse, Maximum, Off) filling the LEFT half and a " + "separate column of stacked rounded blocks on the RIGHT half?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("structure_toolbar_icons_vlm",)) +def test_toolbar_icons_vlm(): + """Toolbar: three icon buttons in the top-right (chain/link, sliders, info).""" + _home_ready() + vlm_assert("structure_toolbar_icons", + "Are there three separate icon buttons grouped in the top-right " + "corner of the top app bar (a link/chain icon, a sliders icon, and " + "an info circle icon)?", RESULTS_DIR, tag="position") + + +@and_test(expects=("structure_seekbar_segments_vlm",)) +def test_seekbar_segments_vlm(): + """Seekbar shape: a tall vertical bar divided into ~10 stacked rounded + segments. Set Max first so the segments are lit and clearly delineated.""" + home = _home_ready() + tap_node(node_by_id(home, "max_button")) + settle("tap") + vlm_assert("structure_seekbar_segments", + "On the right side of the screen, is there a tall vertical bar that " + "is divided into roughly ten stacked rounded segments?", + RESULTS_DIR, tag="shape") + + +@and_test(expects=("structure_button_pills_vlm",)) +def test_button_pill_shapes_vlm(): + """Button shapes: Maximum/Half/Minimum/Off are large rounded pill shapes + stacked vertically.""" + _home_ready() + vlm_assert("structure_button_pills", + "Are the brightness buttons (Maximum, Half, Minimum, Off) drawn as " + "large rounded pill/capsule shapes stacked vertically in a column?", + RESULTS_DIR, tag="shape") + + +TESTS = [ + test_gate_launch, + test_gate_toolbar, + test_sos_shrinks_button_set, + test_morse_dialog_adds_edittext, + test_interval_dialog_adds_radiobuttons, + test_interval_mode_toggles_suffix_subtree, + test_links_dialog_adds_visit_buttons, + test_about_dialog_appears, + test_settings_activity_shape_flip, + test_settings_has_many_switch_rows, + test_home_layout_vlm, + test_toolbar_icons_vlm, + test_seekbar_segments_vlm, + test_button_pill_shapes_vlm, +] + +if __name__ == "__main__": + run_suite(TESTS, "structure") diff --git a/android/cyb3rko-flashdim/tests/test_android_text.py b/android/cyb3rko-flashdim/tests/test_android_text.py new file mode 100644 index 0000000000000000000000000000000000000000..f50898a845f84d2cf4cb91737b46a88f4e1919db --- /dev/null +++ b/android/cyb3rko-flashdim/tests/test_android_text.py @@ -0,0 +1,776 @@ +#!/usr/bin/env python3 +"""TEXT lane behavioral suite for FlashDim. + +Sole owner of exact-string equality: this file asserts the CONTENT strings that +an interaction PRODUCES or REVEALS — dynamic status text, validation error +messages, dialog titles opened by an action, dynamically-formatted labels, +produced suffix/counter content. It cedes the computed numeric level VALUE +("N / 10" arithmetic) to the computation lane. + +Every dynamic string is asserted ABSENT before the trigger and PRESENT after, +so a dead layout-clone that only shows static launch labels FAILS. + +Run: + ADB_PATH=/opt/android/platform-tools/adb DEVICE_SERIAL=emulator-5554 \ + python3 test_android_text.py com.cyb3rko.flashdim.dev +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else "results" + + +# ───────────────────────────────────────────────────────────────────────────── +# Helpers +# ───────────────────────────────────────────────────────────────────────────── +def all_text(nodes): + """Every non-empty text on the surface, pipe-joined, for substring probes.""" + return " | ".join(n.get("text", "") for n in nodes if n.get("text")) + + +def norm(s): + """Normalise a produced string for tolerant-but-word-faithful comparison. + + The uiautomator dump serialises embedded newlines as the literal entity + ` `; collapse that (and real newlines/whitespace) so the WORDS decide + the match, never the line breaks.""" + return " ".join((s or "").replace(" ", " ").split()).casefold() + + +def _go_home(): + """FlashDim's task back-stack survives force_stop, so restart_app() can + resume on SettingsActivity. Back out until home's level_indicator shows.""" + for _ in range(4): + if node_by_id(ui(), "level_indicator"): + return True + back() + settle("tap") + return node_by_id(ui(), "level_indicator") is not None + + +def _home(): + """Fresh app on the home surface. Own entry point for every test.""" + restart_app() + wait_for_foreground() + return _go_home() + + +def _home_clean(): + """Home surface on freshly-wiped data (for the settings default summary).""" + clear_data() + restart_app() + wait_for_foreground() + return _go_home() + + +# ───────────────────────────────────────────────────────────────────────────── +# Depth backers — one and_enter_() per dialog/activity we cross. +# ───────────────────────────────────────────────────────────────────────────── +def and_enter_morse_dialog(): + """home → tap morse_button → 'Flash morse code' AlertDialog. Returns node + of the message EditText (text_input_text) or None on failure.""" + tap_node(node_by_id(ui(), "morse_button")) + settle("tap") + and_enter("morse_dialog") + return node_by_id(ui(), "text_input_text") + + +def and_enter_interval_dialog(): + """home → tap interval_button → 'Interval Flash' AlertDialog. Returns True + once the dialog title is present.""" + tap_node(node_by_id(ui(), "interval_button")) + settle("tap") + and_enter("interval_dialog") + at = node_by_id(ui(), "alertTitle") + return bool(at and norm(at.get("text")) == norm("Interval Flash")) + + +def and_enter_about_dialog(): + """home → toolbar Icon Credits → 'About' AlertDialog. Returns True once the + About title is present.""" + tap_node(find_node(ui(), content_desc="Icon Credits")) + settle("tap") + and_enter("about_dialog") + at = node_by_id(ui(), "alertTitle") + return bool(at and norm(at.get("text")) == norm("About")) + + +def and_enter_links_dialog(): + """home → toolbar Visit-on-GitHub → 'Links' AlertDialog. Returns True once + the Links title is present.""" + tap_node(find_node(ui(), content_desc="Visit on GitHub")) + settle("tap") + and_enter("links_dialog") + at = node_by_id(ui(), "alertTitle") + return bool(at and norm(at.get("text")) == norm("Links")) + + +def and_enter_settings(): + """home → toolbar Settings → SettingsActivity. Returns True once a settings + row is present.""" + tap_node(find_node(ui(), content_desc="Settings")) + settle("tap") + and_enter("settings") + return find_node_ci(ui(), "Preferred level") is not None + + +# ═════════════════════════════════════════════════════════════════════════════ +# SECTION A — Home dynamic status text produced by a tap (depth 0, transition). +# ═════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_sos_mode_indicator",)) +def test_sos_mode_indicator(): + """Tapping SOS flips level_indicator from a numeric level to the produced + literal 'SOS mode'. Absent before, present after.""" + if not _home(): + record("text_sos_mode_indicator", False, + "setup_failed: home surface not reached", + depth=0, jump_kind="transition", expect="level_indicator == 'SOS mode'") + return + before = node_by_id(ui(), "level_indicator") + if not before: + record("text_sos_mode_indicator", False, + "setup_failed: level_indicator missing on home", + depth=0, jump_kind="transition", expect="level_indicator == 'SOS mode'") + return + absent = norm(before.get("text")) != norm("SOS mode") + sos = node_by_id(ui(), "sos_button") + if not sos: + record("text_sos_mode_indicator", False, + "feature_missing: no sos_button on home", + depth=0, jump_kind="transition", expect="level_indicator == 'SOS mode'") + return + tap_node(sos) + settle("tap") + after = node_by_id(ui(), "level_indicator") + present = bool(after and norm(after.get("text")) == norm("SOS mode")) + ok = absent and present + record("text_sos_mode_indicator", ok, + "" if ok else "behavior_wrong: level_indicator did not become 'SOS mode' after SOS tap", + depth=0, jump_kind="transition", expect="level_indicator text == 'SOS mode'") + + +@and_test(expects=("text_sos_quick_actions_morse",)) +def test_sos_quick_actions_morse(): + """SOS also rewrites quick_actions_view from 'Quick Actions' to a produced + 'Morse:\\nS (...)' block. Assert it starts with 'Morse:' and carries the + dynamically-formatted letter portion 'S (' — content it PRODUCED.""" + if not _home(): + record("text_sos_quick_actions_morse", False, + "setup_failed: home surface not reached", + depth=0, jump_kind="transition", expect="quick_actions_view starts 'Morse:' + 'S ('") + return + qa = node_by_id(ui(), "quick_actions_view") + if not qa: + record("text_sos_quick_actions_morse", False, + "setup_failed: quick_actions_view missing on home", + depth=0, jump_kind="transition", expect="quick_actions_view starts 'Morse:' + 'S ('") + return + absent = "morse:" not in norm(qa.get("text")) + sos = node_by_id(ui(), "sos_button") + if not sos: + record("text_sos_quick_actions_morse", False, + "feature_missing: no sos_button on home", + depth=0, jump_kind="transition", expect="quick_actions_view starts 'Morse:' + 'S ('") + return + tap_node(sos) + settle("tap") + after = node_by_id(ui(), "quick_actions_view") + txt = norm(after.get("text")) if after else "" + # produced content: header 'Morse:' + the dynamically-formatted letter 'S (' + present = txt.startswith("morse:") and "s (" in txt + ok = absent and present + record("text_sos_quick_actions_morse", ok, + "" if ok else "behavior_wrong: quick_actions_view did not show produced 'Morse:' + letter after SOS", + depth=0, jump_kind="transition", + expect="quick_actions_view produced 'Morse:' header with letter 'S ('") + + +@and_test(expects=("text_quick_actions_restored_off",)) +def test_quick_actions_restored_off(): + """After SOS makes quick_actions_view a Morse block, tapping Off restores it + to exactly 'Quick Actions'. Assert the Morse content is PRESENT first, then + ABSENT and 'Quick Actions' back — a produced-string flip in both directions.""" + if not _home(): + record("text_quick_actions_restored_off", False, + "setup_failed: home surface not reached", + depth=0, jump_kind="transition", expect="quick_actions_view == 'Quick Actions' after Off") + return + sos = node_by_id(ui(), "sos_button") + if not sos: + record("text_quick_actions_restored_off", False, + "feature_missing: no sos_button on home", + depth=0, jump_kind="transition", expect="quick_actions_view == 'Quick Actions' after Off") + return + tap_node(sos) + settle("tap") + mid = node_by_id(ui(), "quick_actions_view") + in_morse = bool(mid and "morse:" in norm(mid.get("text"))) + off = node_by_id(ui(), "off_button") + if not off: + record("text_quick_actions_restored_off", False, + "feature_missing: no off_button on home", + depth=0, jump_kind="transition", expect="quick_actions_view == 'Quick Actions' after Off") + return + tap_node(off) + settle("tap") + after = node_by_id(ui(), "quick_actions_view") + restored = bool(after and norm(after.get("text")) == norm("Quick Actions")) + ok = in_morse and restored + record("text_quick_actions_restored_off", ok, + "" if ok else "behavior_wrong: quick_actions_view did not restore to 'Quick Actions' after Off", + depth=0, jump_kind="transition", + expect="quick_actions_view restored to 'Quick Actions' after Off") + + +@and_test(expects=("text_indicator_restored_off",)) +def test_indicator_restored_off(): + """SOS sets level_indicator to 'SOS mode'; tapping Off restores it to the + numeric '0 / 10'. Assert 'SOS mode' is PRESENT after SOS then ABSENT after + Off (the string content flip, not the number itself).""" + if not _home(): + record("text_indicator_restored_off", False, + "setup_failed: home surface not reached", + depth=0, jump_kind="transition", expect="level_indicator no longer 'SOS mode' after Off") + return + sos = node_by_id(ui(), "sos_button") + if not sos: + record("text_indicator_restored_off", False, + "feature_missing: no sos_button on home", + depth=0, jump_kind="transition", expect="level_indicator no longer 'SOS mode' after Off") + return + tap_node(sos) + settle("tap") + mid = node_by_id(ui(), "level_indicator") + in_sos = bool(mid and norm(mid.get("text")) == norm("SOS mode")) + off = node_by_id(ui(), "off_button") + if not off: + record("text_indicator_restored_off", False, + "feature_missing: no off_button on home", + depth=0, jump_kind="transition", expect="level_indicator no longer 'SOS mode' after Off") + return + tap_node(off) + settle("tap") + after = node_by_id(ui(), "level_indicator") + restored = bool(after and norm(after.get("text")) != norm("SOS mode") + and after.get("text", "").strip() != "") + ok = in_sos and restored + record("text_indicator_restored_off", ok, + "" if ok else "behavior_wrong: level_indicator did not leave 'SOS mode' after Off", + depth=0, jump_kind="transition", + expect="level_indicator content left 'SOS mode' after Off") + + +# ═════════════════════════════════════════════════════════════════════════════ +# SECTION B — Morse dialog validation error messages (depth 1). The strongest +# text tests: exact produced error strings triggered by tapping Flash. +# ═════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_morse_error_empty",)) +def test_morse_error_empty(): + """Tap Flash with an empty message → TextInputLayout produces the exact + error 'Please enter your message'. Absent on open, present after Flash.""" + if not _home(): + record("text_morse_error_empty", False, + "setup_failed: home surface not reached", + depth=1, jump_kind="transition", expect="error 'Please enter your message'") + return + field = and_enter_morse_dialog() + if not field: + record("text_morse_error_empty", False, + "setup_failed: morse dialog / message field not reached", + depth=1, jump_kind="transition", expect="error 'Please enter your message'") + return + absent = "please enter your message" not in norm(all_text(ui())) + flash = node_by_id(ui(), "button1") or find_node_ci(ui(), "Flash") + if not flash: + record("text_morse_error_empty", False, + "feature_missing: no Flash button in morse dialog", + depth=1, jump_kind="transition", expect="error 'Please enter your message'") + return + tap_node(flash) + settle("tap") + present = "please enter your message" in norm(all_text(ui())) + ok = absent and present + record("text_morse_error_empty", ok, + "" if ok else "behavior_wrong: empty-message Flash did not produce 'Please enter your message'", + depth=1, jump_kind="transition", expect="error text == 'Please enter your message'") + + +@and_test(expects=("text_morse_error_invalid_chars",)) +def test_morse_error_invalid_chars(): + """Type invalid characters ('!!!') then tap Flash → exact error + 'Use characters a–z, A–Z, 0–9 and space' (note EN DASH U+2013). Absent + before, present after.""" + if not _home(): + record("text_morse_error_invalid_chars", False, + "setup_failed: home surface not reached", + depth=1, jump_kind="transition", + expect="error 'Use characters a–z, A–Z, 0–9 and space'") + return + field = and_enter_morse_dialog() + if not field: + record("text_morse_error_invalid_chars", False, + "setup_failed: morse dialog / message field not reached", + depth=1, jump_kind="transition", + expect="error 'Use characters a–z, A–Z, 0–9 and space'") + return + expected = "Use characters a–z, A–Z, 0–9 and space" + absent = norm(expected) not in norm(all_text(ui())) + type_text(field, "!!!") + flash = node_by_id(ui(), "button1") or find_node_ci(ui(), "Flash") + if not flash: + record("text_morse_error_invalid_chars", False, + "feature_missing: no Flash button in morse dialog", + depth=1, jump_kind="transition", expect="error " + repr(expected)) + return + tap_node(flash) + settle("tap") + present = norm(expected) in norm(all_text(ui())) + ok = absent and present + record("text_morse_error_invalid_chars", ok, + "" if ok else "behavior_wrong: invalid-char Flash did not produce the a–z/A–Z/0–9 error", + depth=1, jump_kind="transition", + expect="error text == 'Use characters a–z, A–Z, 0–9 and space'") + + +@and_test(expects=("text_morse_hint_on_open",)) +def test_morse_hint_on_open(): + """The message field's hint 'Your Message' is produced-on-open dialog + content (absent on home, present once the dialog is up). depth 1.""" + if not _home(): + record("text_morse_hint_on_open", False, + "setup_failed: home surface not reached", + depth=1, jump_kind="transition", expect="morse hint 'Your Message'") + return + absent = "your message" not in norm(all_text(ui())) + field = and_enter_morse_dialog() + if not field: + record("text_morse_hint_on_open", False, + "setup_failed: morse dialog not reached", + depth=1, jump_kind="transition", expect="morse hint 'Your Message'") + return + present = "your message" in norm(all_text(ui())) + ok = absent and present + record("text_morse_hint_on_open", ok, + "" if ok else "behavior_wrong: 'Your Message' hint not shown when morse dialog opened", + depth=1, jump_kind="transition", expect="hint text == 'Your Message'") + + +# ═════════════════════════════════════════════════════════════════════════════ +# SECTION C — Interval dialog produced text (depth 1). +# ═════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_interval_seizure_warning", "text_interval_seizure_warning_vlm")) +def test_interval_seizure_warning(): + """Opening the interval dialog produces the seizure-warning line + '⚠️ Seizure Warning: Flashing light'. Match the core words 'Seizure + Warning' + 'Flashing light' (emoji/bold render outside the text run). + Absent on home, present in the dialog. depth 1.""" + if not _home(): + record("text_interval_seizure_warning", False, + "setup_failed: home surface not reached", + depth=1, jump_kind="transition", expect="'Seizure Warning' + 'Flashing light'") + return + absent = "seizure warning" not in norm(all_text(ui())) + if not and_enter_interval_dialog(): + record("text_interval_seizure_warning", False, + "setup_failed: interval dialog not reached", + depth=1, jump_kind="transition", expect="'Seizure Warning' + 'Flashing light'") + return + warn = node_by_id(ui(), "seizure_warning") + txt = norm(warn.get("text")) if warn else norm(all_text(ui())) + present = "seizure warning" in txt and "flashing light" in txt + ok = absent and present + record("text_interval_seizure_warning", ok, + "" if ok else "behavior_wrong: seizure warning line not produced when interval dialog opened", + depth=1, jump_kind="transition", + expect="seizure_warning contains 'Seizure Warning' and 'Flashing light'") + # VLM: the warning renders a yellow caution-triangle emoji that never reaches + # the view-tree text — a rendered-shape property only the VLM can confirm. + vlm_assert("text_interval_seizure_warning", + "In this Interval Flash dialog, is there a yellow/orange " + "triangular caution warning icon immediately to the LEFT of the " + "bold words 'Seizure Warning'?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", tag="shape") + + +@and_test(expects=("text_interval_suffix_ms_time_mode",)) +def test_interval_suffix_ms_time_mode(): + """In TIME mode the input carries the produced suffix 'ms'; switching to + BPM the 'ms' suffix disappears. Assert suffix == 'ms' in TIME and its + ABSENCE after BPM — a produced-content change. depth 1.""" + if not _home(): + record("text_interval_suffix_ms_time_mode", False, + "setup_failed: home surface not reached", + depth=1, jump_kind="transition", expect="suffix 'ms' in TIME, gone in BPM") + return + if not and_enter_interval_dialog(): + record("text_interval_suffix_ms_time_mode", False, + "setup_failed: interval dialog not reached", + depth=1, jump_kind="transition", expect="suffix 'ms' in TIME, gone in BPM") + return + suffix = node_by_id(ui(), "textinput_suffix_text") + in_time = bool(suffix and norm(suffix.get("text")) == norm("ms")) + bpm = node_by_id(ui(), "bpm_button") or find_node_ci(ui(), "BPM") + if not bpm: + record("text_interval_suffix_ms_time_mode", False, + "feature_missing: no BPM toggle in interval dialog", + depth=1, jump_kind="transition", expect="suffix 'ms' in TIME, gone in BPM") + return + tap_node(bpm) + settle("tap") + suffix2 = node_by_id(ui(), "textinput_suffix_text") + gone = (suffix2 is None) or (norm(suffix2.get("text")) != norm("ms")) + ok = in_time and gone + record("text_interval_suffix_ms_time_mode", ok, + "" if ok else "behavior_wrong: suffix 'ms' not produced in TIME mode or not removed in BPM mode", + depth=1, jump_kind="transition", + expect="suffix text == 'ms' in TIME mode, absent after BPM") + + +@and_test(expects=("text_interval_counter_time_vs_bpm",)) +def test_interval_counter_time_vs_bpm(): + """The character counter is produced content: '3/5' in TIME, '3/3' after + BPM. Assert the exact '3/5' string in TIME then '3/3' after switching.""" + if not _home(): + record("text_interval_counter_time_vs_bpm", False, + "setup_failed: home surface not reached", + depth=1, jump_kind="transition", expect="counter '3/5' TIME then '3/3' BPM") + return + if not and_enter_interval_dialog(): + record("text_interval_counter_time_vs_bpm", False, + "setup_failed: interval dialog not reached", + depth=1, jump_kind="transition", expect="counter '3/5' TIME then '3/3' BPM") + return + counter = node_by_id(ui(), "textinput_counter") + in_time = bool(counter and norm(counter.get("text")) == norm("3/5")) + bpm = node_by_id(ui(), "bpm_button") or find_node_ci(ui(), "BPM") + if not bpm: + record("text_interval_counter_time_vs_bpm", False, + "feature_missing: no BPM toggle in interval dialog", + depth=1, jump_kind="transition", expect="counter '3/5' TIME then '3/3' BPM") + return + tap_node(bpm) + settle("tap") + counter2 = node_by_id(ui(), "textinput_counter") + in_bpm = bool(counter2 and norm(counter2.get("text")) == norm("3/3")) + ok = in_time and in_bpm + record("text_interval_counter_time_vs_bpm", ok, + "" if ok else "behavior_wrong: counter not '3/5' in TIME and '3/3' in BPM", + depth=1, jump_kind="transition", + expect="counter text == '3/5' in TIME, '3/3' after BPM") + + +@and_test(expects=("text_interval_value_not_allowed",)) +def test_interval_value_not_allowed(): + """Switch to BPM (range 10–200), clear the input and type '5' (below min), + tap Flash → the produced error 'Value not allowed'. Absent before, present + after. depth 1.""" + if not _home(): + record("text_interval_value_not_allowed", False, + "setup_failed: home surface not reached", + depth=1, jump_kind="transition", expect="error 'Value not allowed'") + return + if not and_enter_interval_dialog(): + record("text_interval_value_not_allowed", False, + "setup_failed: interval dialog not reached", + depth=1, jump_kind="transition", expect="error 'Value not allowed'") + return + bpm = node_by_id(ui(), "bpm_button") or find_node_ci(ui(), "BPM") + if not bpm: + record("text_interval_value_not_allowed", False, + "feature_missing: no BPM toggle in interval dialog", + depth=1, jump_kind="transition", expect="error 'Value not allowed'") + return + tap_node(bpm) + settle("tap") + absent = "value not allowed" not in norm(all_text(ui())) + inp = node_by_id(ui(), "number_input_text") + if not inp: + record("text_interval_value_not_allowed", False, + "setup_failed: number input not found in interval dialog", + depth=1, jump_kind="transition", expect="error 'Value not allowed'") + return + # focus + clear the existing value, then type an out-of-range one + tap_node(inp) + settle("keyboard") + for _ in range(6): + press_key("KEYCODE_DEL") + settle("text") + type_text(node_by_id(ui(), "number_input_text"), "5") + flash = node_by_id(ui(), "flash_button") or find_node_ci(ui(), "Flash") + if not flash: + record("text_interval_value_not_allowed", False, + "feature_missing: no Flash button in interval dialog", + depth=1, jump_kind="transition", expect="error 'Value not allowed'") + return + tap_node(flash) + settle("tap") + present = "value not allowed" in norm(all_text(ui())) + ok = absent and present + # stop any flashing that may have started, keep isolation clean + stop = node_by_id(ui(), "stop_button") + if stop: + tap_node(stop) + settle("tap") + record("text_interval_value_not_allowed", ok, + "" if ok else "behavior_wrong: out-of-range BPM value did not produce 'Value not allowed'", + depth=1, jump_kind="transition", expect="error text == 'Value not allowed'") + + +# ═════════════════════════════════════════════════════════════════════════════ +# SECTION D — Dialog titles / descriptions revealed by an action (depth 1–2). +# ═════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_about_dialog_title", "text_about_dialog_title_vlm")) +def test_about_dialog_title(): + """Tapping the toolbar Icon-Credits action reveals the About dialog whose + alertTitle == 'About'. Absent on home, present in the dialog. depth 1.""" + if not _home(): + record("text_about_dialog_title", False, + "setup_failed: home surface not reached", + depth=1, jump_kind="transition", expect="alertTitle == 'About'") + return + absent_before = find_node_ci(ui(), "Show Icon Credits") is None + if not and_enter_about_dialog(): + record("text_about_dialog_title", False, + "feature_missing: About dialog / title 'About' not revealed", + depth=1, jump_kind="transition", expect="alertTitle == 'About'") + return + at = node_by_id(ui(), "alertTitle") + present = bool(at and norm(at.get("text")) == norm("About")) + ok = absent_before and present + record("text_about_dialog_title", ok, + "" if ok else "behavior_wrong: About dialog title 'About' not produced by Icon-Credits action", + depth=1, jump_kind="transition", expect="alertTitle text == 'About'") + # VLM: the About body is a multi-line device/version block that renders as + # free-form drawn text rows — confirm the produced multi-line info block. + vlm_assert("text_about_dialog_title", + "In this About dialog, is there a multi-line block of " + "device/version information showing labels such as 'Version', " + "'Model' and 'OS' on separate lines?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", tag="layout") + + +@and_test(expects=("text_icon_credits_dialog_title",)) +def test_icon_credits_dialog_title(): + """About → tap 'Show Icon Credits' → a second dialog whose alertTitle == + 'Icon Credits'. Depth 2, backed by and_enter_about_dialog() then the tap. + Assert the title 'Icon Credits' is ABSENT in the About dialog and PRESENT + in the second dialog.""" + if not _home(): + record("text_icon_credits_dialog_title", False, + "setup_failed: home surface not reached", + depth=2, jump_kind="transition", expect="second alertTitle == 'Icon Credits'") + return + if not and_enter_about_dialog(): + record("text_icon_credits_dialog_title", False, + "setup_failed: About dialog not reached", + depth=2, jump_kind="transition", expect="second alertTitle == 'Icon Credits'") + return + at1 = node_by_id(ui(), "alertTitle") + absent = bool(at1 and norm(at1.get("text")) != norm("Icon Credits")) + btn = node_by_id(ui(), "button1") or find_node_ci(ui(), "Show Icon Credits") + if not btn: + record("text_icon_credits_dialog_title", False, + "feature_missing: no 'Show Icon Credits' button in About dialog", + depth=2, jump_kind="transition", expect="second alertTitle == 'Icon Credits'") + return + tap_node(btn) + settle("tap") + and_enter("icon_credits_dialog") + at2 = node_by_id(ui(), "alertTitle") + present = bool(at2 and norm(at2.get("text")) == norm("Icon Credits")) + ok = absent and present + record("text_icon_credits_dialog_title", ok, + "" if ok else "behavior_wrong: 'Show Icon Credits' did not open a dialog titled 'Icon Credits'", + depth=2, jump_kind="transition", expect="second-dialog alertTitle text == 'Icon Credits'") + + +@and_test(expects=("text_links_dialog_title",)) +def test_links_dialog_title(): + """Toolbar Visit-on-GitHub action reveals the Links dialog whose alertTitle + == 'Links'. Absent on home, present in the dialog. depth 1.""" + if not _home(): + record("text_links_dialog_title", False, + "setup_failed: home surface not reached", + depth=1, jump_kind="transition", expect="alertTitle == 'Links'") + return + absent_before = "repository on github" not in norm(all_text(ui())) + if not and_enter_links_dialog(): + record("text_links_dialog_title", False, + "feature_missing: Links dialog / title 'Links' not revealed", + depth=1, jump_kind="transition", expect="alertTitle == 'Links'") + return + at = node_by_id(ui(), "alertTitle") + present = bool(at and norm(at.get("text")) == norm("Links")) + ok = absent_before and present + record("text_links_dialog_title", ok, + "" if ok else "behavior_wrong: Links dialog title 'Links' not produced by GitHub action", + depth=1, jump_kind="transition", expect="alertTitle text == 'Links'") + + +@and_test(expects=("text_links_github_desc",)) +def test_links_github_desc(): + """Inside the Links dialog the GitHub row description is produced content + == 'Repository on GitHub'. Absent on home, present in the dialog. depth 1.""" + if not _home(): + record("text_links_github_desc", False, + "setup_failed: home surface not reached", + depth=1, jump_kind="transition", expect="github_desc == 'Repository on GitHub'") + return + absent = "repository on github" not in norm(all_text(ui())) + if not and_enter_links_dialog(): + record("text_links_github_desc", False, + "setup_failed: Links dialog not reached", + depth=1, jump_kind="transition", expect="github_desc == 'Repository on GitHub'") + return + desc = node_by_id(ui(), "github_desc") + txt = norm(desc.get("text")) if desc else norm(all_text(ui())) + present = "repository on github" in txt + ok = absent and present + record("text_links_github_desc", ok, + "" if ok else "behavior_wrong: Links GitHub row description 'Repository on GitHub' not produced", + depth=1, jump_kind="transition", expect="github_desc text == 'Repository on GitHub'") + + +@and_test(expects=("text_links_matrix_desc",)) +def test_links_matrix_desc(): + """Inside the Links dialog the Matrix row description is produced content + == 'Matrix chat room (questions, feedback, discussions)'. depth 1.""" + if not _home(): + record("text_links_matrix_desc", False, + "setup_failed: home surface not reached", + depth=1, jump_kind="transition", + expect="matrix_desc == 'Matrix chat room (questions, feedback, discussions)'") + return + expected = "Matrix chat room (questions, feedback, discussions)" + absent = norm(expected) not in norm(all_text(ui())) + if not and_enter_links_dialog(): + record("text_links_matrix_desc", False, + "setup_failed: Links dialog not reached", + depth=1, jump_kind="transition", expect="matrix_desc == " + repr(expected)) + return + desc = node_by_id(ui(), "matrix_desc") + txt = norm(desc.get("text")) if desc else norm(all_text(ui())) + present = norm(expected) in txt + ok = absent and present + record("text_links_matrix_desc", ok, + "" if ok else "behavior_wrong: Links Matrix row description not produced exactly", + depth=1, jump_kind="transition", + expect="matrix_desc text == 'Matrix chat room (questions, feedback, discussions)'") + + +# ═════════════════════════════════════════════════════════════════════════════ +# SECTION E — Settings summary produced text (depth 1). +# ═════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("text_settings_preferred_level_summary",)) +def test_settings_preferred_level_summary(): + """The 'Preferred level' summary is dynamically formatted with the current + level appended: it contains 'Dim level' and ends with ': 10' on fresh data. + Absent on home, present in Settings. depth 1.""" + if not _home_clean(): + record("text_settings_preferred_level_summary", False, + "setup_failed: home surface not reached after clear_data", + depth=1, jump_kind="transition", expect="Preferred-level summary contains 'Dim level', ends ': 10'") + return + absent = "dim level" not in norm(all_text(ui())) + if not and_enter_settings(): + record("text_settings_preferred_level_summary", False, + "feature_missing: Settings / 'Preferred level' not reached", + depth=1, jump_kind="transition", expect="Preferred-level summary contains 'Dim level', ends ': 10'") + return + # the summary is the TextView that carries the produced 'Dim level ... : N' + n = ui() + summary = None + for x in n: + t = norm(x.get("text")) + if "dim level" in t: + summary = x.get("text", "") + break + present = (summary is not None + and "dim level" in norm(summary) + and summary.rstrip().endswith(": 10")) + ok = absent and present + record("text_settings_preferred_level_summary", ok, + "" if ok else "behavior_wrong: Preferred-level summary did not produce 'Dim level...: 10'", + depth=1, jump_kind="transition", + expect="Preferred-level summary contains 'Dim level' and ends ': 10'") + + +@and_test(expects=("text_settings_about_row_summary",)) +def test_settings_about_row_summary(): + """The Settings about-row shows produced title/summary 'FlashDim Dev' / + 'by Cyb3rKo'. Assert the summary 'by Cyb3rKo' is ABSENT on home and PRESENT + once Settings is open. depth 1.""" + if not _home(): + record("text_settings_about_row_summary", False, + "setup_failed: home surface not reached", + depth=1, jump_kind="transition", expect="about-row summary 'by Cyb3rKo'") + return + absent = "by cyb3rko" not in norm(all_text(ui())) + if not and_enter_settings(): + record("text_settings_about_row_summary", False, + "feature_missing: Settings not reached", + depth=1, jump_kind="transition", expect="about-row summary 'by Cyb3rKo'") + return + present = "by cyb3rko" in norm(all_text(ui())) + ok = absent and present + record("text_settings_about_row_summary", ok, + "" if ok else "behavior_wrong: Settings about-row summary 'by Cyb3rKo' not produced", + depth=1, jump_kind="transition", expect="about-row summary text == 'by Cyb3rKo'") + + +@and_test(expects=("text_settings_instant_flash_summary",)) +def test_settings_instant_flash_summary(): + """The 'Instant flash' preference shows the produced summary 'Activate + flashlight on app startup'. Absent on home, present in Settings. depth 1.""" + if not _home(): + record("text_settings_instant_flash_summary", False, + "setup_failed: home surface not reached", + depth=1, jump_kind="transition", expect="summary 'Activate flashlight on app startup'") + return + expected = "Activate flashlight on app startup" + absent = norm(expected) not in norm(all_text(ui())) + if not and_enter_settings(): + record("text_settings_instant_flash_summary", False, + "feature_missing: Settings not reached", + depth=1, jump_kind="transition", expect="summary " + repr(expected)) + return + present = norm(expected) in norm(all_text(ui())) + ok = absent and present + record("text_settings_instant_flash_summary", ok, + "" if ok else "behavior_wrong: 'Instant flash' summary 'Activate flashlight on app startup' not produced", + depth=1, jump_kind="transition", + expect="summary text == 'Activate flashlight on app startup'") + + +TESTS = [ + # Section A — home dynamic status (depth 0) + test_sos_mode_indicator, + test_sos_quick_actions_morse, + test_quick_actions_restored_off, + test_indicator_restored_off, + # Section B — morse validation errors (depth 1) + test_morse_error_empty, + test_morse_error_invalid_chars, + test_morse_hint_on_open, + # Section C — interval produced text (depth 1) + test_interval_seizure_warning, + test_interval_suffix_ms_time_mode, + test_interval_counter_time_vs_bpm, + test_interval_value_not_allowed, + # Section D — dialog titles / descriptions (depth 1–2) + test_about_dialog_title, + test_icon_credits_dialog_title, + test_links_dialog_title, + test_links_github_desc, + test_links_matrix_desc, + # Section E — settings summaries (depth 1) + test_settings_preferred_level_summary, + test_settings_about_row_summary, + test_settings_instant_flash_summary, +] + +if __name__ == "__main__": + run_suite(TESTS, "text") diff --git a/android/cyb3rko-flashdim/tests/test_manifest.json b/android/cyb3rko-flashdim/tests/test_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..075246f05e3b59ba0a5494b7f0f255c0c74b1264 --- /dev/null +++ b/android/cyb3rko-flashdim/tests/test_manifest.json @@ -0,0 +1,767 @@ +{ + "manifest_version": 1, + "kit_api_version": 1, + "task_id": "flashdim", + "baseline_model": "claude-opus-4-8", + "baseline_package": "com.cyb3rko.flashdim.dev", + "total": 116, + "manifest_sha": "144e0ec0b1ab", + "tests": [ + { + "name": "computation::computation_half_button", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_max_button", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_min_button", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_off_button", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_pref_slider_high", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_pref_slider_low", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_pref_slider_monotonic", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_seek_bottom_zero", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_seek_frac_seven", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_seek_frac_three", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_seek_low_one", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_seek_low_one_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_seek_mid_half", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_seek_mid_half_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_seek_monotonic", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_seek_top_max", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_seek_top_max_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_button_seekbar_same_state", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_button_seekbar_same_state_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_context_awareness_persists", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_interval_mode_roundtrip", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_interval_mode_roundtrip_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_morse_dialog_flow", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_morse_dialog_flow_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_preferred_level_dialog_live_value", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_preferred_level_persists", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_seekbar_mid_fill_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_seekbar_min_fill_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_seq_max_half_min_off", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_seq_min_then_max_override", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_seq_toggle_through", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_sos_enter_exit", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_sos_enter_exit_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_back_about_to_home", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_back_links_to_home", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_back_morse_to_home", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_back_settings_to_home", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_icon_credits_unwinds", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_preferred_level_unwinds", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_about", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_icon_credits_d2", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_icon_credits_d2_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_interval", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_interval_probe", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_interval_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_links", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_links_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_morse", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_morse_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_preferred_level_d2", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_preferred_level_d2_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_settings", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_settings_links_d2", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_settings_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_up_arrow_settings_to_home", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "states::states_brightness_button_active_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_context_awareness_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_context_awareness_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_extension_disabled_visual_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_extension_enabled_by_instant", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_half_level_fill_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_instant_flash_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_instant_flash_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_interval_bpm_selected_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_interval_radio_bpm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_interval_radio_time_restore", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_interval_time_selected_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_max_level_fill_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_min_level_fill_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_morse_input_focus", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_off_level_fill_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_sos_buttons_gone_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_sos_enter_disables_controls", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_sos_exit_restores_controls", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_sos_greyed_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_sos_level_indicator", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_switch_off_visual_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_switch_on_visual_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_toggle_link_disabled_by_mode", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_toggle_mode_off", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "structure::structure_about_dialog_appears", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_button_pills_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_launch", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_toolbar", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_home_layout_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_interval_mode_suffix", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_interval_radiobuttons", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_links_dialog_visit_buttons", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_morse_dialog_editext", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_seekbar_segments_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_shape_flip", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_switch_rows", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_sos_shrinks_buttons", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_sos_shrinks_buttons_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_toolbar_icons_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "text::text_about_dialog_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_about_dialog_title_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_icon_credits_dialog_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_indicator_restored_off", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_interval_counter_time_vs_bpm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_interval_seizure_warning", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_interval_seizure_warning_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_interval_suffix_ms_time_mode", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_interval_value_not_allowed", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_links_dialog_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_links_github_desc", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_links_matrix_desc", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_morse_error_empty", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_morse_error_invalid_chars", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_morse_hint_on_open", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_quick_actions_restored_off", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_about_row_summary", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_instant_flash_summary", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_preferred_level_summary", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_sos_mode_indicator", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_sos_quick_actions_morse", + "module": "text", + "baseline_status": "passed" + } + ], + "ignored": [], + "vlm_assertions": [ + { + "name": "computation::computation_seek_top_max_vlm", + "module": "computation", + "tag": "color" + }, + { + "name": "computation::computation_seek_mid_half_vlm", + "module": "computation", + "tag": "position" + }, + { + "name": "computation::computation_seek_low_one_vlm", + "module": "computation", + "tag": "color" + }, + { + "name": "interaction::interaction_button_seekbar_same_state_vlm", + "module": "interaction", + "tag": "shape" + }, + { + "name": "interaction::interaction_seekbar_min_fill_vlm", + "module": "interaction", + "tag": "shape" + }, + { + "name": "interaction::interaction_seekbar_mid_fill_vlm", + "module": "interaction", + "tag": "shape" + }, + { + "name": "interaction::interaction_sos_enter_exit_vlm", + "module": "interaction", + "tag": "position" + }, + { + "name": "interaction::interaction_morse_dialog_flow_vlm", + "module": "interaction", + "tag": "layout" + }, + { + "name": "interaction::interaction_interval_mode_roundtrip_vlm", + "module": "interaction", + "tag": "content" + }, + { + "name": "navigation::nav_reach_morse_vlm", + "module": "navigation", + "tag": "layout" + }, + { + "name": "navigation::nav_reach_interval_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_reach_links_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_reach_settings_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::nav_reach_icon_credits_d2_vlm", + "module": "navigation", + "tag": "content" + }, + { + "name": "navigation::nav_reach_preferred_level_d2_vlm", + "module": "navigation", + "tag": "shape" + }, + { + "name": "states::states_switch_on_visual_vlm", + "module": "states", + "tag": "position" + }, + { + "name": "states::states_switch_off_visual_vlm", + "module": "states", + "tag": "position" + }, + { + "name": "states::states_extension_disabled_visual_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_sos_buttons_gone_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_sos_greyed_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_interval_time_selected_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_interval_bpm_selected_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_max_level_fill_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_min_level_fill_vlm", + "module": "states", + "tag": "position" + }, + { + "name": "states::states_half_level_fill_vlm", + "module": "states", + "tag": "size" + }, + { + "name": "states::states_off_level_fill_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_brightness_button_active_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "structure::structure_sos_shrinks_buttons_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_home_layout_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_toolbar_icons_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_seekbar_segments_vlm", + "module": "structure", + "tag": "shape" + }, + { + "name": "structure::structure_button_pills_vlm", + "module": "structure", + "tag": "shape" + }, + { + "name": "text::text_interval_seizure_warning_vlm", + "module": "text", + "tag": "shape" + }, + { + "name": "text::text_about_dialog_title_vlm", + "module": "text", + "tag": "layout" + } + ], + "vlm_total": 34, + "n_vlm_unverified": 0, + "vlm_log_found": true +} \ No newline at end of file diff --git a/android/cyb3rko-flashdim/vlm_assertions.json b/android/cyb3rko-flashdim/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..8cdc3fd5e8ac1d7d45b79380676b93ba97e4b3db --- /dev/null +++ b/android/cyb3rko-flashdim/vlm_assertions.json @@ -0,0 +1,703 @@ +{ + "schema_version": 2, + "instance_id": "android/cyb3rko-flashdim", + "grading": { + "mode": "inline", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 34, + "with_verdict": 34, + "calibrated": 0, + "usable": null, + "scored_records": 34, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "structure_sos_shrinks_buttons_vlm", + "screenshot": "structure_sos_shrinks_buttons_vlm.png", + "assertion": "On the LEFT side of this screen, are there exactly two rounded buttons stacked at the top (one labelled 'SOS' and one labelled 'Off'), with empty space below them?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_sos_shrinks_buttons", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_home_layout_vlm", + "screenshot": "structure_home_layout_vlm.png", + "assertion": "Is the screen split into two columns, with a stack of rounded buttons (SOS, Morse, Maximum, Off) filling the LEFT half and a separate column of stacked rounded blocks on the RIGHT half?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_home_layout", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_toolbar_icons_vlm", + "screenshot": "structure_toolbar_icons_vlm.png", + "assertion": "Are there three separate icon buttons grouped in the top-right corner of the top app bar (a link/chain icon, a sliders icon, and an info circle icon)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_toolbar_icons", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_seekbar_segments_vlm", + "screenshot": "structure_seekbar_segments_vlm.png", + "assertion": "On the right side of the screen, is there a tall vertical bar that is divided into roughly ten stacked rounded segments?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "structure_seekbar_segments", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_button_pills_vlm", + "screenshot": "structure_button_pills_vlm.png", + "assertion": "Are the brightness buttons (Maximum, Half, Minimum, Off) drawn as large rounded pill/capsule shapes stacked vertically in a column?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "structure_button_pills", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_morse_vlm", + "screenshot": "nav_reach_morse_vlm.png", + "assertion": "Is a dialog titled 'Flash morse code' shown with a single-line text input field above a 'Flash' button?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "nav_reach_morse", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_interval_vlm", + "screenshot": "nav_reach_interval_vlm.png", + "assertion": "Is a dialog shown with two side-by-side radio toggles labelled 'TIME' and 'BPM' and a numeric input field?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_reach_interval", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_links_vlm", + "screenshot": "nav_reach_links_vlm.png", + "assertion": "Is a dialog titled 'Links' shown listing several rows, each row having a button labelled 'Visit' on its right side?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_reach_links", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_settings_vlm", + "screenshot": "nav_reach_settings_vlm.png", + "assertion": "Is a settings screen shown as a vertical scrollable list of labelled rows, several rows having an on/off toggle switch on the right, with a back arrow at the top-left?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "nav_reach_settings", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_icon_credits_d2_vlm", + "screenshot": "nav_reach_icon_credits_d2_vlm.png", + "assertion": "Is a dialog titled 'Icon Credits' shown, listing icon credit lines and a button reading 'Open Pictogrammers'?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "nav_reach_icon_credits_d2", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_preferred_level_d2_vlm", + "screenshot": "nav_reach_preferred_level_d2_vlm.png", + "assertion": "In the centered pop-up dialog, is there a wide horizontal light-purple / lavender bar with a row of small evenly-spaced dots along it?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "nav_reach_preferred_level_d2", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_button_seekbar_same_state_vlm", + "screenshot": "interaction_button_seekbar_same_state_vlm.png", + "assertion": "Is the vertical segmented bar completely filled (all ~10 segments highlighted) and does the level read 10 / 10?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "interaction_button_seekbar_same_state", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_seekbar_min_fill_vlm", + "screenshot": "interaction_seekbar_min_fill_vlm.png", + "assertion": "Is only the bottom-most segment of the vertical bar highlighted while the rest are dark?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "interaction_seekbar_min_fill", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_seekbar_mid_fill_vlm", + "screenshot": "interaction_seekbar_mid_fill_vlm.png", + "assertion": "Is the vertical segmented bar filled about halfway from the bottom (roughly the lower half of the segments highlighted, the upper half dark)?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "interaction_seekbar_mid_fill", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_sos_enter_exit_vlm", + "screenshot": "interaction_sos_enter_exit_vlm.png", + "assertion": "Have the Maximum/Half/Minimum buttons disappeared, leaving only SOS and Off in the left column?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "interaction_sos_enter_exit", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_morse_dialog_flow_vlm", + "screenshot": "interaction_morse_dialog_flow_vlm.png", + "assertion": "Is a dialog with a single-line text input field (hint about a message) and a 'Flash' button visible on screen?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "interaction_morse_dialog_flow", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_interval_mode_roundtrip_vlm", + "screenshot": "interaction_interval_mode_roundtrip_vlm.png", + "assertion": "Does the numeric input show 100 with no 'ms' suffix beside it?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "interaction_interval_mode_roundtrip", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_seek_top_max_vlm", + "screenshot": "computation_seek_top_max_vlm.png", + "assertion": "In this flashlight app, the vertical segmented bar on the right side is at its maximum level. Are ALL of its segments (roughly ten stacked bars, top to bottom) filled/highlighted in the bright accent color rather than dark gray?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "computation_seek_top_max", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_seek_mid_half_vlm", + "screenshot": "computation_seek_mid_half_vlm.png", + "assertion": "In this flashlight app, the vertical segmented bar on the right is set to roughly half. Is the bar filled/highlighted from the BOTTOM up to about the MIDDLE (about half of the stacked segments bright, the upper half dark)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "computation_seek_mid_half", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_seek_low_one_vlm", + "screenshot": "computation_seek_low_one_vlm.png", + "assertion": "In this flashlight app, the vertical segmented bar on the right is set to its lowest non-zero level. Is ONLY the single bottom segment highlighted in the bright accent color while all segments above it are dark gray?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "computation_seek_low_one", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_switch_on_visual_vlm", + "screenshot": "states_switch_on_visual_vlm.png", + "assertion": "In the settings list, is the toggle switch on the 'Instant flash' row in the ON position — its thumb pushed to the RIGHT with a filled/coloured track (not grey)?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "states_switch_on_visual", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_switch_off_visual_vlm", + "screenshot": "states_switch_off_visual_vlm.png", + "assertion": "Look at the 'Quick settings toggle link' row's toggle switch: is it in the OFF position — thumb to the LEFT over a grey/uncoloured track?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "states_switch_off_visual", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_extension_disabled_visual_vlm", + "screenshot": "states_extension_disabled_visual_vlm.png", + "assertion": "Does the 'Instant flash extension' row (its title, summary and toggle) appear greyed-out / dimmed compared to the fully-black rows above and below it, indicating it is disabled?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_extension_disabled_visual", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_sos_buttons_gone_vlm", + "screenshot": "states_sos_buttons_gone_vlm.png", + "assertion": "Are the 'Maximum', 'Half' and 'Minimum' brightness buttons NO LONGER visible, leaving only the 'SOS' and 'Off' buttons in the button area?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_sos_buttons_gone", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_sos_greyed_vlm", + "screenshot": "states_sos_greyed_vlm.png", + "assertion": "Is the 'SOS' button visibly greyed-out / dimmed (disabled) while the 'Off' button remains fully coloured and active?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_sos_greyed", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_interval_time_selected_vlm", + "screenshot": "states_interval_time_selected_vlm.png", + "assertion": "In this dialog with 'TIME' and 'BPM' radio options, is 'TIME' the selected one — its radio circle filled/coloured — while 'BPM' is unfilled?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_interval_time_selected", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_interval_bpm_selected_vlm", + "screenshot": "states_interval_bpm_selected_vlm.png", + "assertion": "Now is 'BPM' the selected radio option — its circle filled/coloured — while 'TIME' is unfilled?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_interval_bpm_selected", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_max_level_fill_vlm", + "screenshot": "states_max_level_fill_vlm.png", + "assertion": "Look at the vertical segmented brightness bar on the left. Is it COMPLETELY filled — every one of its ~10 segments in the light/highlight colour with none left dark?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_max_level_fill", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_min_level_fill_vlm", + "screenshot": "states_min_level_fill_vlm.png", + "assertion": "Look at the vertical segmented brightness bar. Is ONLY the single bottom segment highlighted/lit while all the segments above it are dark grey?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "states_min_level_fill", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_half_level_fill_vlm", + "screenshot": "states_half_level_fill_vlm.png", + "assertion": "Look at the vertical segmented brightness bar. Are roughly the bottom HALF (about 5 of ~10) of its segments highlighted and the top half dark?", + "form": "question", + "expected": true, + "aspect": "size", + "modality": null, + "links_to": "states_half_level_fill", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_off_level_fill_vlm", + "screenshot": "states_off_level_fill_vlm.png", + "assertion": "Look at the vertical segmented brightness bar. Are ALL of its segments dark/unfilled with NONE highlighted?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_off_level_fill", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_brightness_button_active_vlm", + "screenshot": "states_brightness_button_active_vlm.png", + "assertion": "Do the three brightness buttons 'Maximum', 'Half' and 'Minimum' appear as filled LIGHT-coloured pills, while the 'SOS', 'Morse' and 'Interval' buttons are darker/greyed tonal buttons?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_brightness_button_active", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_interval_seizure_warning_vlm", + "screenshot": "text_interval_seizure_warning_vlm.png", + "assertion": "In this Interval Flash dialog, is there a yellow/orange triangular caution warning icon immediately to the LEFT of the bold words 'Seizure Warning'?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "text_interval_seizure_warning", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_about_dialog_title_vlm", + "screenshot": "text_about_dialog_title_vlm.png", + "assertion": "In this About dialog, is there a multi-line block of device/version information showing labels such as 'Version', 'Model' and 'OS' on separate lines?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "text_about_dialog_title", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + } + ], + "merged_from_files": 1, + "source_shapes": { + "list": 1 + } +} \ No newline at end of file diff --git a/android/dijia1124-plusplusbattery/LICENSE b/android/dijia1124-plusplusbattery/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3fd04dd27b99068ba48fd2bf0df89449d0add9af --- /dev/null +++ b/android/dijia1124-plusplusbattery/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Runhui Zhou + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/android/dijia1124-plusplusbattery/instance.json b/android/dijia1124-plusplusbattery/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..d4766b74c1b09dba1ee0589d1401dd23c2e48dbe --- /dev/null +++ b/android/dijia1124-plusplusbattery/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "android/dijia1124-plusplusbattery", + "platform": "android", + "repo": "https://github.com/dijia1124/plusplusbattery", + "commit": "a0053f88aceb75570756ee31b2b5adadd4d0fe90", + "patches": [], + "package": "com.dijia1124.plusplusbattery", + "license": null +} diff --git a/android/dijia1124-plusplusbattery/reference/launch.sh b/android/dijia1124-plusplusbattery/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8 --- /dev/null +++ b/android/dijia1124-plusplusbattery/reference/launch.sh @@ -0,0 +1,9 @@ +#!/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 1 diff --git a/android/dijia1124-plusplusbattery/tests/android_computation_eval.json b/android/dijia1124-plusplusbattery/tests/android_computation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..7e5c966487fb89f8723f2f802dd1774da9123f55 --- /dev/null +++ b/android/dijia1124-plusplusbattery/tests/android_computation_eval.json @@ -0,0 +1,196 @@ +{ + "module": "computation", + "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": 2, + "liveness": 0, + "interactive": 16, + "depth_ge1": 11, + "depth_ge2": 0, + "value": 16, + "vlm_fine": 0 + }, + "results": [ + { + "test": "computation_current_divide_10p1", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Battery Current 90000 mA" + }, + { + "test": "computation_current_divide_10p2", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Battery Current 9000 mA" + }, + { + "test": "computation_current_divide_10p3", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Battery Current 900 mA" + }, + { + "test": "computation_current_divide_10p4", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Battery Current 90 mA" + }, + { + "test": "computation_current_divide_10p5", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Battery Current 9 mA" + }, + { + "test": "computation_current_divide_10p5_vlm", + "passed": true, + "message": "VLM: Q='Look at the 'Battery Current' row. Is its value a SMALL number of just one or two characters (for example '9'), rather than a long six-digit number like '900000'?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Look at the 'Battery Current' row. Is its value a SMALL number of just one or two characters (for example '9'), rather than a long six-digit number like '900000'?", + "tag": "content" + }, + { + "test": "computation_current_multiply_10p1", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Battery Current 9000000 mA" + }, + { + "test": "computation_power_baseline", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "Battery Power 4500 W" + }, + { + "test": "computation_power_divide_10p2", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Battery Power 45 W" + }, + { + "test": "computation_power_divide_10p3", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Battery Power 4.50 W" + }, + { + "test": "computation_power_divide_10p3_vlm", + "passed": true, + "message": "VLM: Q='Look at the 'Battery Power' row. Is its value a SMALL decimal number like '4.50', rather than a large number like '4500'?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Look at the 'Battery Power' row. Is its value a SMALL decimal number like '4.50', rather than a large number like '4500'?", + "tag": "content" + }, + { + "test": "computation_power_divide_10p4", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Battery Power 0.45 W" + }, + { + "test": "computation_power_divide_10p3_dual", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Battery Power 9 W at Divide 10^3 + Dual ON" + }, + { + "test": "computation_power_dual_only", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "Battery Power 9000 W with Dual Cell ON" + }, + { + "test": "computation_temp_c_to_f", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "Battery Temperature 77.0°F" + }, + { + "test": "computation_temp_f_to_c", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "Battery Temperature 25.0°C" + }, + { + "test": "computation_current_divide_then_reset", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Battery Current 900000 mA after Divide 10^3 then Reset" + }, + { + "test": "computation_temp_swap_round_trip", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "Battery Temperature 25.0°C after two swaps" + } + ] +} \ No newline at end of file diff --git a/android/dijia1124-plusplusbattery/tests/android_interaction_eval.json b/android/dijia1124-plusplusbattery/tests/android_interaction_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..bc4c85c5116f61d6e1e1a978462a2fd2940bb50f --- /dev/null +++ b/android/dijia1124-plusplusbattery/tests/android_interaction_eval.json @@ -0,0 +1,219 @@ +{ + "module": "interaction", + "total": 20, + "passed": 20, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 13, + "passed": 13, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 7, + "passed": 7, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.5385, + "audit": { + "kit_api_version": 1, + "existence": 3, + "liveness": 0, + "interactive": 17, + "depth_ge1": 10, + "depth_ge2": 3, + "value": 0, + "vlm_fine": 1 + }, + "results": [ + { + "test": "interaction_multiplier_persists_process_death", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Battery Current 900 mA survives process death" + }, + { + "test": "interaction_multiplier_persists_process_death_vlm", + "passed": true, + "message": "VLM: Q='In the battery info list, does the Battery Current row show a SMALL number like 900 (about three digits) rather than a large number like 900000 (six digits)?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the battery info list, does the Battery Current row show a SMALL number like 900 (about three digits) rather than a large number like 900000 (six digits)?", + "tag": "content" + }, + { + "test": "interaction_temp_unit_persists_process_death", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Battery Temperature 77.0°F survives process death" + }, + { + "test": "interaction_dark_mode_persists_process_death_vlm", + "passed": true, + "message": "VLM: Q='Is this Settings screen rendered with a DARK theme, i.e. a mostly BLACK or very dark background behind the toggle rows?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is this Settings screen rendered with a DARK theme, i.e. a mostly BLACK or very dark background behind the toggle rows?", + "tag": "color" + }, + { + "test": "interaction_show_fab_off_no_fab_vlm", + "passed": true, + "message": "VLM: Q='Is the bottom-right corner of the screen EMPTY, with NO round floating action button (no wrench button) there?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is the bottom-right corner of the screen EMPTY, with NO round floating action button (no wrench button) there?", + "tag": "layout" + }, + { + "test": "interaction_show_fab_persists_cross_surface", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Dashboard 'Open menu' FAB gone after OFF+relaunch, back after ON" + }, + { + "test": "interaction_show_fab_on_fab_back_vlm", + "passed": true, + "message": "VLM: Q='Is a round floating action button with a wrench icon visible in the BOTTOM-RIGHT of the screen?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a round floating action button with a wrench icon visible in the BOTTOM-RIGHT of the screen?", + "tag": "layout" + }, + { + "test": "interaction_monitor_checkbox_row_unchecked_vlm", + "passed": true, + "message": "VLM: Q='In this list of labelled checkboxes, is at least ONE checkbox UNCHECKED (empty box) while the others are CHECKED (filled with a check mark)?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In this list of labelled checkboxes, is at least ONE checkbox UNCHECKED (empty box) while the others are CHECKED (filled with a check mark)?", + "tag": "content" + }, + { + "test": "interaction_monitor_checkbox_persists_nav", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "entry box #1 off after Back+re-enter; the other 8 boxes still on" + }, + { + "test": "interaction_monitor_checkbox_persists_process_death", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "entry box #2 off after relaunch; the other 8 boxes still on" + }, + { + "test": "interaction_calibrate_sequence_integrity", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Current 9000 mA after Divide 10^2, 900000 mA after Reset" + }, + { + "test": "interaction_dual_power_doubled_vlm", + "passed": true, + "message": "VLM: Q='Does the Battery Power row show a SMALL number (only a few characters, such as 9 or 9.00) rather than a large number like 4500?' A=YES expect=YES", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Does the Battery Power row show a SMALL number (only a few characters, such as 9 or 9.00) rather than a large number like 4500?", + "tag": "content" + }, + { + "test": "interaction_multiplier_then_dual_power", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Power 4.50 W at Divide 10^3, 9 W with Dual Cell ON" + }, + { + "test": "interaction_three_card_state_integrity", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "temp 77.0°F + Dual Yes + Current 900 mA all intact together" + }, + { + "test": "interaction_radio_selection_sequence", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Divide radio checked on reopen; Multiply radio checked after Reset+reopen" + }, + { + "test": "interaction_follow_system_dark_dependency", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "dark switch enabled=false while follow ON, enabled=true when OFF" + }, + { + "test": "interaction_temp_swap_idempotent", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "temp 25.0°C->77.0°F->25.0°C across two swaps" + }, + { + "test": "interaction_dual_toggle_idempotent", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Dual Cell No->Yes->No across two toggles" + }, + { + "test": "interaction_fab_expanded_stack_vlm", + "passed": true, + "message": "VLM: Q='Are there several stacked action buttons (a vertical column of labelled pill-shaped buttons such as 'Enable root mode' and 'Manage custom entries') shown above the bottom-right floating button?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Are there several stacked action buttons (a vertical column of labelled pill-shaped buttons such as 'Enable root mode' and 'Manage custom entries') shown above the bottom-right floating button?", + "tag": "layout" + }, + { + "test": "interaction_fab_expand_collapse", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "FAB 'Open menu' -> 'Close menu' -> 'Open menu' round-trip" + } + ] +} \ No newline at end of file diff --git a/android/dijia1124-plusplusbattery/tests/android_navigation_eval.json b/android/dijia1124-plusplusbattery/tests/android_navigation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..b81f009606caca108877e0a3f170f4f1d9fa4d50 --- /dev/null +++ b/android/dijia1124-plusplusbattery/tests/android_navigation_eval.json @@ -0,0 +1,264 @@ +{ + "module": "navigation", + "total": 25, + "passed": 25, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 18, + "passed": 18, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 7, + "passed": 7, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.3889, + "audit": { + "kit_api_version": 1, + "existence": 7, + "liveness": 0, + "interactive": 18, + "depth_ge1": 18, + "depth_ge2": 12, + "value": 0, + "vlm_fine": 5 + }, + "results": [ + { + "test": "nav_reach_dashboard_to_monitor", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "'Battery Monitor' title appears; Dashboard 'Open menu' FAB gone" + }, + { + "test": "nav_reach_monitor_to_history", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "History toolbar 'Export' appears; Monitor 'Battery Monitor' gone" + }, + { + "test": "nav_reach_history_to_settings", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "'Follow system theme' appears; History 'Export' toolbar gone" + }, + { + "test": "nav_reach_settings_to_dashboard", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Dashboard 'Open menu' FAB appears; 'Follow system theme' gone" + }, + { + "test": "nav_reach_dashboard_to_settings", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "'Follow system theme' appears; Dashboard 'Open menu' FAB gone" + }, + { + "test": "nav_roundtrip_dashboard_settings_dashboard", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "hop1 Settings 'Follow system theme' appears; hop2 back on Dashboard with 'Open menu' FAB, 'Follow system theme' gone" + }, + { + "test": "nav_roundtrip_history_dashboard_history", + "passed": true, + "message": "", + "depth": 3, + "jump_kind": "reach", + "tier": 2, + "expect": "History 'Export' toolbar reappears after the round-trip; Dashboard 'Open menu' FAB gone on the final hop" + }, + { + "test": "nav_reach_monitor_entry_settings", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "'Monitor Entry Settings' title appears; the Monitor tab's bottom-nav 'History' item is gone (nested screen)" + }, + { + "test": "nav_reach_monitor_entry_settings_vlm", + "passed": true, + "message": "VLM: Q='Does this screen show a vertical list of rows, each with a small square checkbox on the LEFT and a text label to its right?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does this screen show a vertical list of rows, each with a small square checkbox on the LEFT and a text label to its right?", + "tag": "layout" + }, + { + "test": "nav_reach_entry_settings_toolbar_vlm", + "passed": true, + "message": "VLM: Q='Is there a left-pointing back arrow rendered at the TOP-LEFT of the screen, to the left of a 'Monitor Entry Settings' title?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is there a left-pointing back arrow rendered at the TOP-LEFT of the screen, to the left of a 'Monitor Entry Settings' title?", + "tag": "position" + }, + { + "test": "nav_backstack_entry_settings_to_monitor", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "after one BACK: 'Battery Monitor' restored, the 'Please select the entries ...' instruction gone" + }, + { + "test": "nav_reach_floating_window_settings", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "'Floating Window Settings' title appears; the Monitor tab's bottom-nav 'History' item is gone (nested screen)" + }, + { + "test": "nav_reach_floating_toolbar_vlm", + "passed": true, + "message": "VLM: Q='Is there a left-pointing back arrow rendered at the TOP-LEFT of the screen, to the left of a 'Floating Window Settings' title?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is there a left-pointing back arrow rendered at the TOP-LEFT of the screen, to the left of a 'Floating Window Settings' title?", + "tag": "position" + }, + { + "test": "nav_backstack_floating_settings_to_monitor", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "after one BACK: 'Battery Monitor' restored, the 'Opacity: 0.75' header gone" + }, + { + "test": "nav_reach_about", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "'Version:' line appears; the Settings tab's bottom-nav 'Monitor' item is gone (nested screen)" + }, + { + "test": "nav_reach_about_toolbar_vlm", + "passed": true, + "message": "VLM: Q='Is there a left-pointing back arrow rendered at the TOP-LEFT of the screen, to the left of an 'About' title?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is there a left-pointing back arrow rendered at the TOP-LEFT of the screen, to the left of an 'About' title?", + "tag": "position" + }, + { + "test": "nav_backstack_about_to_settings", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "after About BACK: Settings tab restored (bottom-nav 'Monitor' returns), 'Version:' gone" + }, + { + "test": "nav_backstack_deep_unwind_to_dashboard", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "1st BACK: Monitor restored; 2nd BACK: Dashboard 'Open menu' FAB, Monitor title gone" + }, + { + "test": "nav_backstack_tab_back_to_dashboard", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "BACK from Settings tab lands on Dashboard ('Open menu' FAB appears, 'Follow system theme' gone)" + }, + { + "test": "nav_reach_calibrate_dialog", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "open: 'Calibrate via Multiplier' appears, FAB 'Open menu' gone; Close: FAB restored, dialog title gone" + }, + { + "test": "nav_reach_history_help_dialog", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "open: 'Close' appears, History 'Export' toolbar gone; Close: 'Export' toolbar restored, 'Close' gone" + }, + { + "test": "nav_reach_history_export_dialog", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "open: 'Export History' appears, History 'Help' toolbar gone; Cancel: 'Help' toolbar restored, 'Export History' gone" + }, + { + "test": "nav_history_tab_selected_vlm", + "passed": true, + "message": "VLM: Q='In the bottom navigation bar, is the 'History' item visually highlighted (its icon sits on a filled rounded pill) while the other three items are not?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the bottom navigation bar, is the 'History' item visually highlighted (its icon sits on a filled rounded pill) while the other three items are not?", + "tag": "color" + }, + { + "test": "nav_history_toolbar_actions_vlm", + "passed": true, + "message": "VLM: Q='Are there exactly two circular icon buttons at the TOP-RIGHT of the screen, level with a 'History' title on the left?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Are there exactly two circular icon buttons at the TOP-RIGHT of the screen, level with a 'History' title on the left?", + "tag": "layout" + }, + { + "test": "nav_back_to_dashboard_endstate_vlm", + "passed": true, + "message": "VLM: Q='Is a round floating action button showing a wrench icon rendered near the BOTTOM-RIGHT of the screen?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a round floating action button showing a wrench icon rendered near the BOTTOM-RIGHT of the screen?", + "tag": "position" + } + ] +} \ No newline at end of file diff --git a/android/dijia1124-plusplusbattery/tests/android_states_eval.json b/android/dijia1124-plusplusbattery/tests/android_states_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..7a9a7f398b1080aa9451a68a17bf856f1b606241 --- /dev/null +++ b/android/dijia1124-plusplusbattery/tests/android_states_eval.json @@ -0,0 +1,220 @@ +{ + "module": "states", + "total": 20, + "passed": 20, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 12, + "passed": 12, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 8, + "passed": 8, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.6667, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 20, + "depth_ge1": 20, + "depth_ge2": 6, + "value": 0, + "vlm_fine": 6 + }, + "results": [ + { + "test": "states_radio_divide", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Divide checked=true, Multiply checked=false after tapping Divide" + }, + { + "test": "states_radio_divide_vlm", + "passed": true, + "message": "VLM: Q='In this dialog there are two radio buttons in a row labelled 'Multiply' (left) and 'Divide' (right). Is the RIGHT radio button (next to 'Divide') the one that is filled (a solid dot inside its ring), while the left one is an empty ring?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: In this dialog there are two radio buttons in a row labelled 'Multiply' (left) and 'Divide' (right). Is the RIGHT radio button (next to 'Divide') the one that is filled (a solid dot inside its ring), while the left one is an empty ring?", + "tag": "shape" + }, + { + "test": "states_dark_enable_dependency", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Enable-dark-mode enabled=true and Follow-system checked=false" + }, + { + "test": "states_dark_enable_dependency_vlm", + "passed": true, + "message": "VLM: Q='This is a settings screen with a 'Follow system theme' toggle (which is ON) directly above an 'Enable dark mode' row. Does the 'Enable dark mode' switch look greyed-out / dimmed / disabled (faded compared with the toggles above it)?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: This is a settings screen with a 'Follow system theme' toggle (which is ON) directly above an 'Enable dark mode' row. Does the 'Enable dark mode' switch look greyed-out / dimmed / disabled (faded compared with the toggles above it)?", + "tag": "color" + }, + { + "test": "states_dark_mode_light_baseline_vlm", + "passed": true, + "message": "VLM: Q='Is this screen's background light/white (a light theme) with dark text?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is this screen's background light/white (a light theme) with dark text?", + "tag": "color" + }, + { + "test": "states_dark_mode_toggle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Enable-dark-mode checked=true; theme visibly dark" + }, + { + "test": "states_dark_mode_dark_vlm", + "passed": true, + "message": "VLM: Q='Is this app's background dark / near-black (a dark theme is active) with light-coloured text?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Is this app's background dark / near-black (a dark theme is active) with light-coloured text?", + "tag": "color" + }, + { + "test": "states_monitor_checkbox_vlm", + "passed": true, + "message": "VLM: Q='This screen lists battery entries each with a checkbox on the left. Is the checkbox next to 'Battery Level' (the first row) an EMPTY square with NO tick/checkmark inside it?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: This screen lists battery entries each with a checkbox on the left. Is the checkbox next to 'Battery Level' (the first row) an EMPTY square with NO tick/checkmark inside it?", + "tag": "shape" + }, + { + "test": "states_monitor_checkbox", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "CheckBox checked true->false then back to true" + }, + { + "test": "states_floating_text_stroke", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "'Text stroke' checked false->true" + }, + { + "test": "states_floating_text_shadow_vlm", + "passed": true, + "message": "VLM: Q='Does this screen show a settings toggle/switch on the right-hand side of a labelled row (for example a row labelled 'Text shadow' or 'Enable touch') — i.e. it renders real controls, not a blank screen?' A=YES expect=YES", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: Does this screen show a settings toggle/switch on the right-hand side of a labelled row (for example a row labelled 'Text shadow' or 'Enable touch') — i.e. it renders real controls, not a blank screen?", + "tag": "layout" + }, + { + "test": "states_floating_text_shadow", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "'Text shadow' checked false->true" + }, + { + "test": "states_floating_enable_touch", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "'Enable touch' checked true->false" + }, + { + "test": "states_daily_log_toggle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "'Automatic daily charge cycle log' checked false->true" + }, + { + "test": "states_daily_log_toggle_vlm", + "passed": true, + "message": "VLM: Q='On this settings screen, is the switch on the 'Automatic daily charge cycle log' row turned ON — its track filled with an accent colour and its thumb pushed to the RIGHT?' A=YES expect=YES", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM YES: On this settings screen, is the switch on the 'Automatic daily charge cycle log' row turned ON — its track filled with an accent colour and its thumb pushed to the RIGHT?", + "tag": "color" + }, + { + "test": "states_oplus_toggle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "'Show OPlus exclusive entries' checked true->false" + }, + { + "test": "states_showfab_toggle", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "'Show floating button on dashboard' checked true->false" + }, + { + "test": "states_showfab_consequence_vlm", + "passed": true, + "message": "VLM: Q='Is there a round floating action button in the bottom-right corner of this dashboard screen?' A=NO expect=NO", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "VLM NO: Is there a round floating action button in the bottom-right corner of this dashboard screen?", + "tag": "layout" + }, + { + "test": "states_showfab_consequence", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Dashboard FAB 'Open menu' present->absent when Show-FAB OFF, back on restore" + }, + { + "test": "states_setting_persists_process_death", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "'Automatic daily charge cycle log' checked=true survives force-stop+relaunch" + } + ] +} \ No newline at end of file diff --git a/android/dijia1124-plusplusbattery/tests/android_structure_eval.json b/android/dijia1124-plusplusbattery/tests/android_structure_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..b524a66e839789002c906d12f472c396b4278b4a --- /dev/null +++ b/android/dijia1124-plusplusbattery/tests/android_structure_eval.json @@ -0,0 +1,275 @@ +{ + "module": "structure", + "total": 26, + "passed": 26, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 17, + "passed": 17, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 9, + "passed": 9, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.5294, + "audit": { + "kit_api_version": 1, + "existence": 12, + "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_launch_vlm", + "passed": true, + "message": "VLM: Q='Does this screen show a vertical list of battery-info cards with a bottom navigation bar containing exactly 4 icons evenly spaced across the bottom edge?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does this screen show a vertical list of battery-info cards with a bottom navigation bar containing exactly 4 icons evenly spaced across the bottom edge?", + "tag": "shape" + }, + { + "test": "structure_gate_navhost", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_gate_title_and_cards", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_calibrate_dialog_shape_vlm", + "passed": true, + "message": "VLM: Q='Is there a rounded dialog box floating on top of the screen, with the app content behind it faded or greyed out?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is there a rounded dialog box floating on top of the screen, with the app content behind it faded or greyed out?", + "tag": "position" + }, + { + "test": "structure_calibrate_dialog_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "RadioButton class 0->2 when Calibrate opens, back to 0 on Close" + }, + { + "test": "structure_cyclecount_info_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "dashboard subtree (~88 nodes) replaced by a small modal (~13) with a Close button, restored on Close" + }, + { + "test": "structure_voltage_info_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "dashboard subtree replaced by a small modal with a Close button, restored on Close" + }, + { + "test": "structure_estfcc_info_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "dashboard subtree replaced by a small modal with a Close button, restored on Close" + }, + { + "test": "structure_history_help_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "History list subtree (~43) replaced by a Help modal (~13) with Close, restored on Close" + }, + { + "test": "structure_history_export_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Export confirm modal (Export/Cancel buttons) layered over the History list, restored on Cancel" + }, + { + "test": "structure_refresh_dialog_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Settings subtree (~83) replaced by the refresh modal (~20) with a Close button, restored on Close" + }, + { + "test": "structure_fab_expand_shape_vlm", + "passed": true, + "message": "VLM: Q='Above the bottom-right circular button, is there a vertical stack of labeled action buttons that expanded upward from that button?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Above the bottom-right circular button, is there a vertical stack of labeled action buttons that expanded upward from that button?", + "tag": "shape" + }, + { + "test": "structure_fab_expand_shape", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "FAB affordance 'Open menu'->'Close menu' with a menu-item subtree overlay, restored on collapse" + }, + { + "test": "structure_fab_position_vlm", + "passed": true, + "message": "VLM: Q='Is there a single round floating action button positioned in the bottom-right corner of the screen, just above the bottom navigation bar?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is there a single round floating action button positioned in the bottom-right corner of the screen, just above the bottom navigation bar?", + "tag": "position" + }, + { + "test": "structure_monitor_tab_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "checkable-View count 0 (Dashboard) -> 2 (Monitor); distinct subtree" + }, + { + "test": "structure_settings_tab_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "checkable-View count 0 (Dashboard) -> 6 (Settings); distinct subtree" + }, + { + "test": "structure_settings_tab_shape_vlm", + "passed": true, + "message": "VLM: Q='Is the settings content organized into multiple grouped section cards, each containing rows with a toggle switch on the right side?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is the settings content organized into multiple grouped section cards, each containing rows with a toggle switch on the right side?", + "tag": "layout" + }, + { + "test": "structure_history_tab_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "History adds an Export+Help toolbar subtree absent on the Dashboard" + }, + { + "test": "structure_history_tab_shape_vlm", + "passed": true, + "message": "VLM: Q='Are there two circular icon buttons in the top-right corner, with a list of history record entries below them?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Are there two circular icon buttons in the top-right corner, with a list of history record entries below them?", + "tag": "position" + }, + { + "test": "structure_monitor_entry_checkboxes", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "CheckBox class count = 9 on Monitor Entry Settings (0 on the tabs above it)" + }, + { + "test": "structure_monitor_entry_checkboxes_vlm", + "passed": true, + "message": "VLM: Q='Is this a vertical list of rows where each row has a filled checkbox at its far left followed by a text label?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is this a vertical list of rows where each row has a filled checkbox at its far left followed by a text label?", + "tag": "position" + }, + { + "test": "structure_floating_window_seekbars", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "SeekBar class count = 3 on Floating Window Settings" + }, + { + "test": "structure_floating_window_seekbars_vlm", + "passed": true, + "message": "VLM: Q='Does this screen show horizontal slider controls and a horizontal row of rounded color-option chips grouped inside cards?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does this screen show horizontal slider controls and a horizontal row of rounded color-option chips grouped inside cards?", + "tag": "shape" + }, + { + "test": "structure_about_shape", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "transition", + "tier": 2, + "expect": "About = Back + a scrollable text block, none of Settings' toggle Views" + }, + { + "test": "structure_about_shape_vlm", + "passed": true, + "message": "VLM: Q='Is this screen dominated by a single large block of paragraph text (version, repo, author and battery-field descriptions) rather than rows of controls?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is this screen dominated by a single large block of paragraph text (version, repo, author and battery-field descriptions) rather than rows of controls?", + "tag": "layout" + } + ] +} \ No newline at end of file diff --git a/android/dijia1124-plusplusbattery/tests/android_testgen_kit.py b/android/dijia1124-plusplusbattery/tests/android_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6 --- /dev/null +++ b/android/dijia1124-plusplusbattery/tests/android_testgen_kit.py @@ -0,0 +1,1910 @@ +#!/usr/bin/env python3 +"""Android TestGen Kit — the single source of every test helper, so a test's +NAVIGATION 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 package +name differs): always use the module-level PACKAGE (argv[1]). Never write a package +name, an .apk path, a /data/data path, or a pixel coordinate as a literal. + python3 android_testgen_kit.py lint_sources # flags all of those + +SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery): + python3 android_testgen_kit.py audit + python3 android_testgen_kit.py lint + python3 android_testgen_kit.py lint_sources + python3 android_testgen_kit.py audit_depth [results_dir] +""" +from __future__ import annotations + +import ast +import base64 +import functools +import glob +import hashlib +import json +import math +import os +import re +import shlex +import subprocess +import sys +import time +import urllib.error +import 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.0 +SETTLE = { + "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 /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 " list[dict]: + """XML -> list of attribute dicts, each with _bounds and _center.""" + nodes = [] + for m in re.finditer(r"]+?)/?>", 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} \n" + " android_testgen_kit.py audit_depth [results_dir]\n" + " android_testgen_kit.py score [manifest_dir]") diff --git a/android/dijia1124-plusplusbattery/tests/android_text_eval.json b/android/dijia1124-plusplusbattery/tests/android_text_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..04730fedb0306ef23426a29c6da50b7a9dc2af50 --- /dev/null +++ b/android/dijia1124-plusplusbattery/tests/android_text_eval.json @@ -0,0 +1,169 @@ +{ + "module": "text", + "total": 15, + "passed": 15, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 13, + "passed": 13, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 2, + "passed": 2, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.1538, + "audit": { + "kit_api_version": 1, + "existence": 2, + "liveness": 0, + "interactive": 13, + "depth_ge1": 11, + "depth_ge2": 3, + "value": 13, + "vlm_fine": 0 + }, + "results": [ + { + "test": "text_temp_label_after_swap", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "temperature label reads 77.0°F" + }, + { + "test": "text_temp_label_after_swap_vlm", + "passed": true, + "message": "VLM: Q='Look at the 'Battery Temperature' row. Does its value read exactly '77.0°F' (a Fahrenheit temperature), rather than a Celsius value like '25.0°C'?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Look at the 'Battery Temperature' row. Does its value read exactly '77.0°F' (a Fahrenheit temperature), rather than a Celsius value like '25.0°C'?", + "tag": "content" + }, + { + "test": "text_dual_value_after_toggle", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "Dual Cell value reads Yes" + }, + { + "test": "text_calibrate_dialog_title", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "dialog title 'Calibrate via Multiplier'" + }, + { + "test": "text_cycle_count_dialog_title", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "dialog title 'Charge Cycle Count'" + }, + { + "test": "text_voltage_dialog_title", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "dialog title 'Battery Voltage'" + }, + { + "test": "text_fcc_dialog_title", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "dialog title 'FCC Estimation'" + }, + { + "test": "text_history_help_dialog_title", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Help dialog title 'History'" + }, + { + "test": "text_history_export_dialog_title", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "dialog title 'Export History'" + }, + { + "test": "text_refresh_dialog_current_value", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "dialog shows 'Current value: 1000'" + }, + { + "test": "text_floating_opacity_header", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "header 'Opacity: 0.75'" + }, + { + "test": "text_floating_opacity_header_vlm", + "passed": true, + "message": "VLM: Q='Does this screen show a settings label that reads exactly 'Opacity: 0.75'?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does this screen show a settings label that reads exactly 'Opacity: 0.75'?", + "tag": "content" + }, + { + "test": "text_floating_size_header", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "header 'Size: 1.00'" + }, + { + "test": "text_floating_font_weight_header", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "header 'Font weight: 400'" + }, + { + "test": "text_about_version_label", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "About shows a 'Version:' label" + } + ] +} \ No newline at end of file diff --git a/android/dijia1124-plusplusbattery/tests/conftest.py b/android/dijia1124-plusplusbattery/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27 --- /dev/null +++ b/android/dijia1124-plusplusbattery/tests/conftest.py @@ -0,0 +1 @@ +pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"] diff --git a/android/dijia1124-plusplusbattery/tests/requirements.txt b/android/dijia1124-plusplusbattery/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c --- /dev/null +++ b/android/dijia1124-plusplusbattery/tests/requirements.txt @@ -0,0 +1,2 @@ +pytest +pillow diff --git a/android/dijia1124-plusplusbattery/tests/test_android_computation.py b/android/dijia1124-plusplusbattery/tests/test_android_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..fd70046fd440dfe72e450b1757e9ef9c29981ed7 --- /dev/null +++ b/android/dijia1124-plusplusbattery/tests/test_android_computation.py @@ -0,0 +1,635 @@ +#!/usr/bin/env python3 +"""COMPUTATION lane — PlusPlusBattery (Jetpack Compose battery info viewer). + +This lane owns the app's ARITHMETIC: input -> recomputed output. Every test drives +an INPUT (current multiplier, dual-cell toggle, temperature-unit swap) and asserts +the EXACT recomputed VALUE the running app renders on a Dashboard card. Because the +emulator reports FIXED battery values, exact-string equality is a valid oracle. + +The two engines exercised here (verified live against the original app): + + (1) Current multiplier: shown_current = 900000 * (Multiply ? 10^mag : 1/10^mag) + Open the Calibrate dialog (content-desc "Calibrate"); pick Multiply/Divide + (2 RadioButtons, Divide = the 2nd); pick the magnitude from the "10^0" + spinner. Integer results drop the decimal ("900 mA", never "900.00 mA"). + + (2) Power = current(mA) * voltage(mV) * dualMultiplier / 1_000_000, unit "W", + formatted "clean": integer -> no decimals, else 2dp. + baseline 900000*5000*1/1e6 = 4500 -> "4500 W" + Divide 10^3 (cur 900) 900*5000/1e6 = 4.5 -> "4.50 W" + Divide 10^2 (cur 9000) 9000*5000/1e6 = 45 -> "45 W" + Divide 10^4 (cur 90) 90*5000/1e6 = 0.45 -> "0.45 W" + Divide 10^3 + Dual ON (*2) = 9.0 -> "9 W" (integer -> no dp) + + (3) Temperature C<->F: tap "Swap Unit" -> "25.0°C" becomes "77.0°F" (C*9/5+32). + +ALL expected strings below were confirmed by running this file against the original +and reading the [PASS]/[FAIL] lines — never derived purely from the formula, because +the integer-vs-decimal formatting is easy to get wrong. + +Each test opens its own entry via restart_app(); after any multiplier / dual-cell / +unit change it RESTORES the default (Reset the multiplier, toggle dual off, swap the +unit back) so later tests and other lanes see raw 900000 / 4500 / 25.0°C. A VLM +screenshot, when a test has one, is captured while the changed value is STILL on the +card — before the restore. +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 +import android_testgen_kit as _kit # for the private depth counter only + +RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else os.path.dirname(os.path.abspath(__file__)) + + +# ── Observed constants (each read off the running original) ────────────────────── +CUR_DEFAULT = "900000 mA" # Battery Current, no multiplier +CUR_MUL1 = "9000000 mA" # Multiply 10^1 +CUR_DIV1 = "90000 mA" # Divide 10^1 +CUR_DIV2 = "9000 mA" # Divide 10^2 +CUR_DIV3 = "900 mA" # Divide 10^3 +CUR_DIV4 = "90 mA" # Divide 10^4 +CUR_DIV5 = "9 mA" # Divide 10^5 + +POW_DEFAULT = "4500 W" # baseline power +POW_DIV2 = "45 W" # Divide 10^2 (current 9000) -> integer, no dp +POW_DIV3 = "4.50 W" # Divide 10^3 (current 900) -> 2dp +POW_DIV4 = "0.45 W" # Divide 10^4 (current 90) -> 2dp +POW_DIV3_DUAL = "9 W" # Divide 10^3 + Dual ON (*2) -> integer, no dp +POW_DUAL = "9000 W" # baseline + Dual ON (*2) -> integer, no dp + +TEMP_C = "25.0°C" +TEMP_F = "77.0°F" + +DUAL_NO = "No" +DUAL_YES = "Yes" + +CD_CALIBRATE = "Calibrate" +CD_SWAP = "Swap Unit" +CD_DUAL = "Toggle Dual Battery" + +CAL_TITLE = "Calibrate via Multiplier" +CAL_CLOSE = "Close" +CAL_RESET = "Reset" +SPINNER_LABEL = "10^0" # the collapsed spinner's EditText text + + +# ══════════════════════════════════════════════════════════════════════════════ +# Small readers — read the recomputed value straight out of a FRESH dump. The +# card value TextViews are identified by their unit suffix (" mA" / " W" / "°"). +# ══════════════════════════════════════════════════════════════════════════════ + +def _dec_depth() -> int: + """Pop one surface from the kit's depth counter WITHOUT a hardware BACK — for a + dialog dismissed by its own Close/Reset affordance.""" + _kit._DEPTH = max(0, _kit._DEPTH - 1) + return _kit._DEPTH + + +def cur_value(nodes=None) -> str: + """The Battery Current label ("... mA"), or "" if absent this frame. The + Full-Charge-Capacity card can also read "N mAh"; that suffix is " mAh", so it + never collides with the current card's " mA".""" + nodes = ui() if nodes is None else nodes + for n in nodes: + t = n.get("text", "") + if t.endswith(" mA"): + return t + return "" + + +def power_value(nodes=None) -> str: + """The Battery Power label ("... W"), or "".""" + nodes = ui() if nodes is None else nodes + for n in nodes: + t = n.get("text", "") + if t.endswith(" W"): + return t + return "" + + +def temp_value(nodes=None) -> str: + """The Battery Temperature label ("25.0°C"/"77.0°F"), or "".""" + nodes = ui() if nodes is None else nodes + for n in nodes: + if "°" in n.get("text", ""): + return n["text"] + return "" + + +def dual_value(nodes=None) -> str: + """The Dual Cell value string ("No"/"Yes"), or "".""" + nodes = ui() if nodes is None else nodes + if find_node(nodes, text=DUAL_YES): + return DUAL_YES + if find_node(nodes, text=DUAL_NO): + return DUAL_NO + return "" + + +def read_first(reader, want: str = "", tries: int = 5) -> str: + """Poll `reader` across fresh dumps until it returns a non-empty value (or + `want` when given). The dashboard can re-dump empty for one frame right after a + dialog closes; this makes the read robust without ever fabricating a value.""" + val = "" + for _ in range(tries): + val = reader(ui()) + if val and (not want or val == want): + return val + settle("tap") + return val + + +def radio_buttons(nodes=None) -> list: + nodes = ui() if nodes is None else nodes + return [n for n in nodes if n.get("class", "").endswith("RadioButton")] + + +# ══════════════════════════════════════════════════════════════════════════════ +# depth-family helper — named and_enter_* so the depth auditor counts the declared +# depth=1 as backed by a real navigation call. Opens the Calibrate dialog and +# confirms its title appeared. +# ══════════════════════════════════════════════════════════════════════════════ + +def and_enter_calibrate(nodes=None) -> bool: + """Dashboard -> Calibrate dialog. Confirms the dialog title appeared, then + counts one surface via the kit's depth counter.""" + nodes = ui() if nodes is None else nodes + trig = find_node(nodes, content_desc=CD_CALIBRATE) + if trig is None or not tap_node(trig): + return False + if find_node(ui(), text=CAL_TITLE) is None: + return False + and_enter("calibrate_dialog") + return True + + +# ── Calibrate dialog sub-steps (an open dialog is assumed) ─────────────────────── + +def cal_pick_multiply() -> bool: + """Tap the 1st RadioButton (Multiply). True iff it is checked afterwards.""" + rb = radio_buttons() + if len(rb) < 2 or not tap_node(rb[0]): + return False + rb = radio_buttons() + return len(rb) >= 1 and rb[0].get("checked") == "true" + + +def cal_pick_divide() -> bool: + """Tap the 2nd RadioButton (Divide). True iff it is checked afterwards.""" + rb = radio_buttons() + if len(rb) < 2 or not tap_node(rb[1]): + return False + rb = radio_buttons() + return len(rb) >= 2 and rb[1].get("checked") == "true" + + +def cal_set_exponent(exp_text: str) -> bool: + """Open the spinner (collapsed it shows "10^0") and pick `exp_text` (e.g. + "10^3"). True iff the collapsed spinner then shows the chosen exponent.""" + ed = find_node(ui(), text=SPINNER_LABEL) + if ed is None or not tap_node(ed): + return False + item = find_node(ui(), text=exp_text) + if item is None or not tap_node(item): + return False + return find_node(ui(), text=exp_text) is not None + + +def cal_close() -> bool: + """Tap the dialog's Close button (tap_node — Close is a DANGEROUS_TEXT so + safe_tap would refuse; it only dismisses the dialog).""" + c = find_node(ui(), text=CAL_CLOSE) + return c is not None and tap_node(c) + + +def cal_reset() -> bool: + """Tap the dialog's Reset button (tap_node — Reset is a DANGEROUS_TEXT, but the + app's Reset only resets the multiplier PREFERENCE, never user data). OBSERVED: + Reset restores the value to 900000 mA AND dismisses the dialog.""" + r = find_node(ui(), text=CAL_RESET) + return r is not None and tap_node(r) + + +def apply_multiplier(mode: str, exp_text: str) -> bool: + """Open Calibrate, select Multiply/Divide, set the exponent, Close. Leaves the + Dashboard showing and pops the dialog off the depth counter. Returns True iff + every sub-step succeeded.""" + if not and_enter_calibrate(): + return False + pick = cal_pick_multiply() if mode == "multiply" else cal_pick_divide() + ok = pick and cal_set_exponent(exp_text) and cal_close() + _dec_depth() # dialog dismissed by Close + return ok + + +def restore_multiplier() -> None: + """Open Calibrate and Reset (restores 900000 AND closes), balancing depth.""" + if and_enter_calibrate(): + cal_reset() + _dec_depth() + read_first(cur_value, CUR_DEFAULT) + + +def restore_dual_off() -> None: + """Toggle Dual Cell back OFF if it is currently ON.""" + if dual_value(ui()) == DUAL_YES: + d = find_node(ui(), content_desc=CD_DUAL) + if d: + tap_node(d) + read_first(dual_value, DUAL_NO) + + +def restore_temp_c() -> None: + """Swap the temperature unit back to Celsius if it is currently Fahrenheit.""" + if temp_value(ui()) == TEMP_F: + sw = find_node(ui(), content_desc=CD_SWAP) + if sw: + tap_node(sw) + read_first(temp_value, TEMP_C) + + +def ready() -> bool: + """restart_app + wait; True once the Dashboard is up.""" + restart_app() + return wait_for_foreground() + + +# ══════════════════════════════════════════════════════════════════════════════ +# CURRENT MULTIPLIER — six exact-value cases across Divide 10^1..10^5 + Multiply +# 10^1. Each opens the Calibrate dialog (depth=1), applies the multiplier, and +# asserts the exact recomputed "N mA" string, then Resets back to 900000. +# ══════════════════════════════════════════════════════════════════════════════ + +def _current_case(name: str, mode: str, exp_text: str, expected: str, vlm=None): + """Shared body: assert Battery Current == `expected` after mode+exponent, with a + positive/negative pair (the answer must be ABSENT before and PRESENT after). An + optional `vlm` callback fires while the changed value is STILL on the card — + before the multiplier is Reset.""" + if not ready(): + record(name, False, "setup_failed: app did not reach foreground", + depth=1, jump_kind="value", expect=f"Battery Current {expected}") + return + before = read_first(cur_value, CUR_DEFAULT) + if find_node(ui(), content_desc=CD_CALIBRATE) is None: + record(name, False, + "feature_missing: no 'Calibrate' control on the Battery Current card", + depth=1, jump_kind="value", expect=f"Battery Current {expected}") + return + steps_ok = apply_multiplier(mode, exp_text) + if not steps_ok: + record(name, False, + f"setup_failed: could not apply {mode} {exp_text} in the Calibrate dialog", + depth=1, jump_kind="value", expect=f"Battery Current {expected}") + restore_multiplier() + return + after = read_first(cur_value, expected) + # positive/negative: expected value ABSENT at baseline, PRESENT after. + ok = (before == CUR_DEFAULT) and (after == expected) and (expected != CUR_DEFAULT) + record(name, ok, + "" if ok else + f"behavior_wrong: {mode} {exp_text} should give Battery Current " + f"{expected!r}; saw before={before!r} after={after!r}", + depth=1, jump_kind="value", expect=f"Battery Current {expected}") + if vlm: + vlm(name) # screenshot WHILE the divided value is on screen + restore_multiplier() + + +@and_test(expects=("computation_current_divide_10p1",)) +def test_current_divide_10p1(): + _current_case("computation_current_divide_10p1", "divide", "10^1", CUR_DIV1) + + +@and_test(expects=("computation_current_divide_10p2",)) +def test_current_divide_10p2(): + _current_case("computation_current_divide_10p2", "divide", "10^2", CUR_DIV2) + + +@and_test(expects=("computation_current_divide_10p3",)) +def test_current_divide_10p3(): + _current_case("computation_current_divide_10p3", "divide", "10^3", CUR_DIV3) + + +@and_test(expects=("computation_current_divide_10p4",)) +def test_current_divide_10p4(): + _current_case("computation_current_divide_10p4", "divide", "10^4", CUR_DIV4) + + +@and_test(expects=("computation_current_divide_10p5", "computation_current_divide_10p5_vlm")) +def test_current_divide_10p5(): + def _vlm(_name): + # VLM (content track): with Divide 10^5 applied, the Battery Current card + # renders a TINY value ("9 mA") instead of the six-digit default 900000 — + # visible proof the multiplier recomputation happened. Captured before the + # value is Reset, so the small number is actually on screen. + vlm_assert("computation_current_divide_10p5", + "Look at the 'Battery Current' row. Is its value a SMALL number of " + "just one or two characters (for example '9'), rather than a long " + "six-digit number like '900000'?", + RESULTS_DIR, depth=0, jump_kind="none", tag="content") + _current_case("computation_current_divide_10p5", "divide", "10^5", CUR_DIV5, vlm=_vlm) + + +@and_test(expects=("computation_current_multiply_10p1",)) +def test_current_multiply_10p1(): + _current_case("computation_current_multiply_10p1", "multiply", "10^1", CUR_MUL1) + + +# ══════════════════════════════════════════════════════════════════════════════ +# POWER — recomputed from the (possibly multiplied) current. Baseline is depth=0 +# (no dialog); the multiplier cases are depth=1. Every case asserts the exact "N W" +# string, watching the integer-vs-decimal "clean" formatting. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_power_baseline",)) +def test_power_baseline(): + if not ready(): + record("computation_power_baseline", False, + "setup_failed: app did not reach foreground", + depth=0, jump_kind="value", expect=f"Battery Power {POW_DEFAULT}") + return + got = read_first(power_value, POW_DEFAULT) + ok = got == POW_DEFAULT + record("computation_power_baseline", ok, + "" if ok else + f"behavior_wrong: baseline Battery Power should be {POW_DEFAULT!r} " + f"(900000*5000/1e6); saw {got!r}", + depth=0, jump_kind="value", expect=f"Battery Power {POW_DEFAULT}") + + +def _power_multiplier_case(name: str, exp_text: str, expected: str, vlm=None): + """Divide the current by 10^N, then assert the recomputed Battery Power. The + default power (4500 W) must be ABSENT and `expected` PRESENT after.""" + if not ready(): + record(name, False, "setup_failed: app did not reach foreground", + depth=1, jump_kind="value", expect=f"Battery Power {expected}") + return + before = read_first(power_value, POW_DEFAULT) + if find_node(ui(), content_desc=CD_CALIBRATE) is None: + record(name, False, + "feature_missing: no 'Calibrate' control on the Battery Current card", + depth=1, jump_kind="value", expect=f"Battery Power {expected}") + return + steps_ok = apply_multiplier("divide", exp_text) + if not steps_ok: + record(name, False, + f"setup_failed: could not apply divide {exp_text} in the Calibrate dialog", + depth=1, jump_kind="value", expect=f"Battery Power {expected}") + restore_multiplier() + return + after = read_first(power_value, expected) + ok = (before == POW_DEFAULT) and (after == expected) and (expected != POW_DEFAULT) + record(name, ok, + "" if ok else + f"behavior_wrong: divide {exp_text} should give Battery Power " + f"{expected!r}; saw before={before!r} after={after!r}", + depth=1, jump_kind="value", expect=f"Battery Power {expected}") + if vlm: + vlm(name) # screenshot WHILE the recomputed power is on screen + restore_multiplier() + + +@and_test(expects=("computation_power_divide_10p2",)) +def test_power_divide_10p2(): + _power_multiplier_case("computation_power_divide_10p2", "10^2", POW_DIV2) + + +@and_test(expects=("computation_power_divide_10p3", "computation_power_divide_10p3_vlm")) +def test_power_divide_10p3(): + def _vlm(_name): + # VLM (content track): with Divide 10^3 applied, the Battery Power card + # renders a small decimal ("4.50 W"), not the large default 4500. Captured + # before the multiplier is Reset. + vlm_assert("computation_power_divide_10p3", + "Look at the 'Battery Power' row. Is its value a SMALL decimal " + "number like '4.50', rather than a large number like '4500'?", + RESULTS_DIR, depth=0, jump_kind="none", tag="content") + _power_multiplier_case("computation_power_divide_10p3", "10^3", POW_DIV3, vlm=_vlm) + + +@and_test(expects=("computation_power_divide_10p4",)) +def test_power_divide_10p4(): + _power_multiplier_case("computation_power_divide_10p4", "10^4", POW_DIV4) + + +@and_test(expects=("computation_power_divide_10p3_dual",)) +def test_power_divide_10p3_dual(): + """Divide 10^3 then Dual Cell ON: power 4.50 doubles to a rendered "9 W" + (integer -> the ".00" is dropped).""" + if not ready(): + record("computation_power_divide_10p3_dual", False, + "setup_failed: app did not reach foreground", + depth=1, jump_kind="value", + expect=f"Battery Power {POW_DIV3_DUAL} at Divide 10^3 + Dual ON") + return + if find_node(ui(), content_desc=CD_CALIBRATE) is None: + record("computation_power_divide_10p3_dual", False, + "feature_missing: no 'Calibrate' control on the Battery Current card", + depth=1, jump_kind="value", + expect=f"Battery Power {POW_DIV3_DUAL} at Divide 10^3 + Dual ON") + return + calc_ok = apply_multiplier("divide", "10^3") + pow_div3 = read_first(power_value, POW_DIV3) + dual = find_node(ui(), content_desc=CD_DUAL) + dual_ok = dual is not None and tap_node(dual) + pow_dual = read_first(power_value, POW_DIV3_DUAL) + ok = (calc_ok and pow_div3 == POW_DIV3 and dual_ok + and pow_dual == POW_DIV3_DUAL and dual_value(ui()) == DUAL_YES) + record("computation_power_divide_10p3_dual", ok, + "" if ok else + f"behavior_wrong: Divide 10^3 should give Power {POW_DIV3}; Dual ON " + f"should double it to {POW_DIV3_DUAL}; saw pow3={pow_div3!r} " + f"powdual={pow_dual!r}", + depth=1, jump_kind="value", + expect=f"Battery Power {POW_DIV3_DUAL} at Divide 10^3 + Dual ON") + # RESTORE: dual OFF then Reset multiplier. + restore_dual_off() + restore_multiplier() + + +@and_test(expects=("computation_power_dual_only",)) +def test_power_dual_only(): + """Dual Cell ON at the DEFAULT multiplier doubles power 4500 -> "9000 W" + (integer -> no decimals). Depth 0 (no dialog).""" + if not ready(): + record("computation_power_dual_only", False, + "setup_failed: app did not reach foreground", + depth=0, jump_kind="value", + expect=f"Battery Power {POW_DUAL} with Dual Cell ON") + return + before = read_first(power_value, POW_DEFAULT) + dual = find_node(ui(), content_desc=CD_DUAL) + if dual is None: + record("computation_power_dual_only", False, + "feature_missing: no 'Toggle Dual Battery' control", + depth=0, jump_kind="value", + expect=f"Battery Power {POW_DUAL} with Dual Cell ON") + return + dual_ok = tap_node(dual) + after = read_first(power_value, POW_DUAL) + ok = (before == POW_DEFAULT) and dual_ok and (after == POW_DUAL) \ + and dual_value(ui()) == DUAL_YES + record("computation_power_dual_only", ok, + "" if ok else + f"behavior_wrong: Dual Cell ON should double Power {POW_DEFAULT} to " + f"{POW_DUAL}; saw before={before!r} after={after!r}", + depth=0, jump_kind="value", + expect=f"Battery Power {POW_DUAL} with Dual Cell ON") + restore_dual_off() + + +# ══════════════════════════════════════════════════════════════════════════════ +# TEMPERATURE C<->F — exact recomputed unit string. Both directions, depth 0. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_temp_c_to_f",)) +def test_temp_c_to_f(): + if not ready(): + record("computation_temp_c_to_f", False, + "setup_failed: app did not reach foreground", + depth=0, jump_kind="value", expect=f"Battery Temperature {TEMP_F}") + return + before = read_first(temp_value, TEMP_C) + sw = find_node(ui(), content_desc=CD_SWAP) + if sw is None or not tap_node(sw): + record("computation_temp_c_to_f", False, + "feature_missing: no 'Swap Unit' control on the temperature card", + depth=0, jump_kind="value", expect=f"Battery Temperature {TEMP_F}") + return + after = read_first(temp_value, TEMP_F) + ok = (before == TEMP_C) and (after == TEMP_F) + record("computation_temp_c_to_f", ok, + "" if ok else + f"behavior_wrong: swap should convert {TEMP_C} -> {TEMP_F} (C*9/5+32); " + f"saw before={before!r} after={after!r}", + depth=0, jump_kind="value", expect=f"Battery Temperature {TEMP_F}") + restore_temp_c() + + +@and_test(expects=("computation_temp_f_to_c",)) +def test_temp_f_to_c(): + """Second swap converts Fahrenheit back to the exact "25.0°C".""" + if not ready(): + record("computation_temp_f_to_c", False, + "setup_failed: app did not reach foreground", + depth=0, jump_kind="value", expect=f"Battery Temperature {TEMP_C}") + return + start = read_first(temp_value, TEMP_C) + sw = find_node(ui(), content_desc=CD_SWAP) + if sw is None or not tap_node(sw): + record("computation_temp_f_to_c", False, + "feature_missing: no 'Swap Unit' control on the temperature card", + depth=0, jump_kind="value", expect=f"Battery Temperature {TEMP_C}") + return + to_f = read_first(temp_value, TEMP_F) + sw = find_node(ui(), content_desc=CD_SWAP) + back_ok = sw is not None and tap_node(sw) + to_c = read_first(temp_value, TEMP_C) + ok = (start == TEMP_C) and (to_f == TEMP_F) and back_ok and (to_c == TEMP_C) + record("computation_temp_f_to_c", ok, + "" if ok else + f"behavior_wrong: second swap should convert {TEMP_F} -> {TEMP_C}; " + f"saw start={start!r} to_f={to_f!r} to_c={to_c!r}", + depth=0, jump_kind="value", expect=f"Battery Temperature {TEMP_C}") + restore_temp_c() + + +# ══════════════════════════════════════════════════════════════════════════════ +# ROUND-TRIP integrity — the computation is REVERSIBLE to the exact baseline. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_current_divide_then_reset",)) +def test_current_divide_then_reset(): + """Divide 10^3 -> Current 900 mA, then Reset -> Current back to EXACTLY + 900000 mA. depth=1 (the Calibrate dialog is entered twice).""" + if not ready(): + record("computation_current_divide_then_reset", False, + "setup_failed: app did not reach foreground", + depth=1, jump_kind="value", + expect=f"Battery Current {CUR_DEFAULT} after Divide 10^3 then Reset") + return + before = read_first(cur_value, CUR_DEFAULT) + if find_node(ui(), content_desc=CD_CALIBRATE) is None: + record("computation_current_divide_then_reset", False, + "feature_missing: no 'Calibrate' control on the Battery Current card", + depth=1, jump_kind="value", + expect=f"Battery Current {CUR_DEFAULT} after Divide 10^3 then Reset") + return + calc_ok = apply_multiplier("divide", "10^3") + mid = read_first(cur_value, CUR_DIV3) + # reopen dialog and Reset (restores AND closes) + reset_ok = False + if and_enter_calibrate(): + reset_ok = cal_reset() + _dec_depth() + final = read_first(cur_value, CUR_DEFAULT) + ok = (before == CUR_DEFAULT and calc_ok and mid == CUR_DIV3 + and reset_ok and final == CUR_DEFAULT) + record("computation_current_divide_then_reset", ok, + "" if ok else + f"behavior_wrong: expected {CUR_DEFAULT}->(Divide 10^3)->{CUR_DIV3}->" + f"(Reset)->{CUR_DEFAULT}; saw before={before!r} mid={mid!r} final={final!r}", + depth=1, jump_kind="value", + expect=f"Battery Current {CUR_DEFAULT} after Divide 10^3 then Reset") + restore_multiplier() + + +@and_test(expects=("computation_temp_swap_round_trip",)) +def test_temp_swap_round_trip(): + """Two swaps return the temperature to EXACTLY "25.0°C" (C->F->C). depth 0.""" + if not ready(): + record("computation_temp_swap_round_trip", False, + "setup_failed: app did not reach foreground", + depth=0, jump_kind="value", + expect=f"Battery Temperature {TEMP_C} after two swaps") + return + start = read_first(temp_value, TEMP_C) + sw = find_node(ui(), content_desc=CD_SWAP) + if sw is None or not tap_node(sw): + record("computation_temp_swap_round_trip", False, + "feature_missing: no 'Swap Unit' control on the temperature card", + depth=0, jump_kind="value", + expect=f"Battery Temperature {TEMP_C} after two swaps") + return + mid = read_first(temp_value, TEMP_F) + sw = find_node(ui(), content_desc=CD_SWAP) + back_ok = sw is not None and tap_node(sw) + final = read_first(temp_value, TEMP_C) + ok = (start == TEMP_C) and (mid == TEMP_F) and back_ok and (final == TEMP_C) + record("computation_temp_swap_round_trip", ok, + "" if ok else + f"behavior_wrong: two swaps should return to {TEMP_C}; saw start={start!r} " + f"mid={mid!r} final={final!r}", + depth=0, jump_kind="value", + expect=f"Battery Temperature {TEMP_C} after two swaps") + restore_temp_c() + + +TESTS = [ + # current multiplier (6, depth 1) + test_current_divide_10p1, + test_current_divide_10p2, + test_current_divide_10p3, + test_current_divide_10p4, + test_current_divide_10p5, # + 1 VLM (content) + test_current_multiply_10p1, + # power (5: 1 depth0 + 4 depth1) + test_power_baseline, + test_power_divide_10p2, + test_power_divide_10p3, # + 1 VLM (content) + test_power_divide_10p4, + test_power_divide_10p3_dual, + test_power_dual_only, + # temperature (2, depth 0) + test_temp_c_to_f, + test_temp_f_to_c, + # round-trips (2) + test_current_divide_then_reset, # depth 1 + test_temp_swap_round_trip, # depth 0 +] + + +if __name__ == "__main__": + run_suite(TESTS, "computation") diff --git a/android/dijia1124-plusplusbattery/tests/test_android_interaction.py b/android/dijia1124-plusplusbattery/tests/test_android_interaction.py new file mode 100644 index 0000000000000000000000000000000000000000..4e7980d40440d4155f4a9c89d5283a77000c72cc --- /dev/null +++ b/android/dijia1124-plusplusbattery/tests/test_android_interaction.py @@ -0,0 +1,1021 @@ +#!/usr/bin/env python3 +"""INTERACTION lane — PlusPlusBattery (Jetpack Compose, single Activity). + +EFFECT-BY-CONSEQUENCE on user DATA/state: multi-step (3+) sequences, multi-record +integrity, and — the flagship — DATA/state PERSISTENCE ACROSS PROCESS DEATH +(force_stop_and_relaunch() then assert the durable observation SURVIVED). This app +has no CRUD in non-root mode, so the durable "data" is the app's user SETTINGS/mode +(current-multiplier, temperature unit, dark-theme flag, show-FAB flag, per-entry +monitor checkboxes), each persisted via DataStore. An in-memory-only recreation +cannot pass the relaunch probes. + +CEDES to other lanes: a single toggle's checked bit in isolation (states); a single +computed value in isolation (computation); the exact rendered label wording (text); +whether a screen is reachable (navigation); view-tree shape (structure). Every test +here is a SEQUENCE producing a durable consequence, verified by reading it back out +of a fresh ui(). + +Every fact below was read off the running ORIGINAL with uiautomator: + + Dashboard : Battery Current "900000 mA" (raw; changes with multiplier), + Battery Temperature "25.0°C" (swaps "77.0°F"), + Battery Power "4500 W" (=current*voltage/1e6; doubles with dual), + Dual Cell "No"/"Yes"; FAB content-desc "Open menu"/"Close menu"; + card action content-descs "Calibrate", "Swap Unit", + "Toggle Dual Battery". + Calibrate dialog (depth 1 from Dashboard, content-desc "Calibrate"): + title "Calibrate via Multiplier"; exactly 2 RadioButtons — the 1st + is Multiply (checked=true initially), the 2nd is Divide + (checked=false); a Spinner whose EditText child shows "10^0"; + tapping it opens a list "10^0".."10^9"; "Close" and "Reset" + (TextViews inside Buttons). Divide + "10^3" + Close -> "900 mA"; + Divide + "10^2" + Close -> "9000 mA". + OBSERVED: tapping "Reset" both RESTORES the value to "900000 mA" + AND dismisses the dialog in one action; reopening then shows the + Multiply radio checked again. So restore = tap Reset (no separate + Close), and the "Multiply re-selected" check is done after a reopen. + Power formatting: at Divide 10^3 the Power reads "4.50 W"; Dual Cell ON doubles + it, and the app renders the doubled round value as "9 W" (trailing + ".00" dropped) — NOT "9.00 W". + Settings : switches are class View, checkable=true+checked, aligned RIGHT + (x~948). Match a switch to its row by the nearest label y-center. + Rows: "Follow system theme" (checked, gates dark-mode), + "Enable dark mode" (unchecked, enabled=false until follow-sys OFF), + "Show floating button on dashboard" (checked). + Monitor Entry Settings (depth 2 from Monitor): tap bottom-nav "Monitor" then row + "Monitor entry settings" -> title "Monitor Entry Settings" + 9 + CheckBoxes (all checked=true initially) + back arrow "Back". + +Persistence gotcha: right after tapping "Close" the dashboard can re-dump empty for +one frame, so Current/temp/power are read through a small settle+retry +(read_first()), never a single dump. + +Restore discipline: every test that CHANGES a persisted setting restores the +default before returning (Reset the multiplier; swap the unit back; dark OFF + +follow-system ON; show-FAB ON; re-check the toggled monitor box), so later +tests/lanes always start from the observed defaults. +""" +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 +import android_testgen_kit as _kit # for the private depth counter only + +RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else os.path.dirname(os.path.abspath(__file__)) + + +# ── Observed constants (all read off the running original) ─────────────────────── +CUR_DEFAULT = "900000 mA" # Battery Current, no multiplier +CUR_DIV3 = "900 mA" # Divide by 10^3 +CUR_DIV2 = "9000 mA" # Divide by 10^2 +TEMP_C = "25.0°C" +TEMP_F = "77.0°F" +POW_DEFAULT = "4500 W" +POW_DIV3 = "4.50 W" # Divide 10^3 recompute +POW_DIV3_DUAL = "9 W" # Divide 10^3 + Dual ON (doubled, ".00" dropped) +DUAL_NO = "No" +DUAL_YES = "Yes" + +FAB_OPEN = "Open menu" # Dashboard FAB (collapsed) content-desc +FAB_CLOSE = "Close menu" # Dashboard FAB (expanded) content-desc +CD_CALIBRATE = "Calibrate" +CD_SWAP = "Swap Unit" +CD_DUAL = "Toggle Dual Battery" + +CAL_TITLE = "Calibrate via Multiplier" +CAL_CLOSE = "Close" +CAL_RESET = "Reset" +SPINNER_LABEL = "10^0" # the collapsed spinner's EditText text + +SET_FOLLOW = "Follow system theme" +SET_DARK = "Enable dark mode" +SET_FAB = "Show floating button on dashboard" + +MON_ENTRY_ROW = "Monitor entry settings" +MON_ENTRY_TITLE = "Monitor Entry Settings" + +# Bottom-nav content-descs (present on a tab except the currently-selected one). +NAV_DASHBOARD = "Dashboard" +NAV_MONITOR = "Monitor" +NAV_SETTINGS = "Settings" + + +# ══════════════════════════════════════════════════════════════════════════════ +# Locators & small readers +# ══════════════════════════════════════════════════════════════════════════════ + +def _dec_depth() -> int: + """Pop one surface from the kit's depth counter WITHOUT pressing hardware BACK, + for when a surface was dismissed by tapping its own Close/Back/Reset affordance.""" + _kit._DEPTH = max(0, _kit._DEPTH - 1) + return _kit._DEPTH + + +def cur_value(nodes=None) -> str: + """The Battery Current label text ("... mA"), or "" if absent this frame.""" + nodes = ui() if nodes is None else nodes + for n in nodes: + t = n.get("text", "") + if t.endswith(" mA"): + return t + return "" + + +def temp_value(nodes=None) -> str: + """The Battery Temperature label ("25.0°C"/"77.0°F"), or "".""" + nodes = ui() if nodes is None else nodes + for n in nodes: + t = n.get("text", "") + if "°" in t: + return t + return "" + + +def power_value(nodes=None) -> str: + """The Battery Power label ("... W"), or "".""" + nodes = ui() if nodes is None else nodes + for n in nodes: + t = n.get("text", "") + if t.endswith(" W"): + return t + return "" + + +def read_first(reader, want: str = "", tries: int = 4) -> str: + """Poll `reader` (cur_value/temp_value/power_value) across fresh dumps until it + returns a non-empty value (or `want` when given). The dashboard can re-dump + empty for one frame right after a dialog closes; this makes the read robust + without ever fabricating a value.""" + val = "" + for _ in range(tries): + val = reader(ui()) + if val and (not want or val == want): + return val + settle("tap") + return val + + +def dual_value(nodes=None) -> str: + """The Dual Cell value string ("No"/"Yes"), or "".""" + nodes = ui() if nodes is None else nodes + if find_node(nodes, text=DUAL_YES): + return DUAL_YES + if find_node(nodes, text=DUAL_NO): + return DUAL_NO + return "" + + +def radio_buttons(nodes=None) -> list[dict]: + nodes = ui() if nodes is None else nodes + return [n for n in nodes if n.get("class", "").endswith("RadioButton")] + + +def check_boxes(nodes=None) -> list[dict]: + nodes = ui() if nodes is None else nodes + return [n for n in nodes if n.get("class", "").endswith("CheckBox")] + + +def switch_for_label(nodes, label: str) -> dict | None: + """The Settings CustomSwitch (class View, checkable=true) whose vertical centre + is nearest the row `label`'s centre. Switches carry no text/desc of their own, + so the adjacent label is the only stable handle (recon §Interaction notes).""" + lab = find_node_ci(nodes, label) + if not lab or "_center" not in lab: + return None + ly = lab["_center"][1] + best, best_d = None, 10 ** 9 + for n in nodes: + if (n.get("checkable") == "true" and "View" in n.get("class", "") + and "_center" in n): + d = abs(n["_center"][1] - ly) + if d < best_d: + best, best_d = n, d + return best if best_d < 90 else None + + +# ══════════════════════════════════════════════════════════════════════════════ +# depth-family helpers — named and_enter_*/and_reach_* so the depth auditor counts +# the DECLARED depth as backed by a real navigation call. Each performs a real +# user-path action and drives the kit's own depth counter. +# ══════════════════════════════════════════════════════════════════════════════ + +def and_enter_calibrate(nodes=None) -> bool: + """Dashboard -> Calibrate dialog. Confirms the dialog title appeared, then + counts one surface.""" + nodes = ui() if nodes is None else nodes + trig = find_node(nodes, content_desc=CD_CALIBRATE) + if trig is None or not tap_node(trig): + return False + if find_node(ui(), text=CAL_TITLE) is None: + return False + and_enter("calibrate_dialog") + return True + + +def and_reach_monitor(nodes=None) -> bool: + """ -> Monitor. Proven target-appeared + source-gone.""" + nodes = ui() if nodes is None else nodes + trig = find_node(nodes, content_desc=NAV_MONITOR) + return trig is not None and and_reach_surface(trig, MON_ENTRY_ROW, FAB_OPEN) + + +def and_reach_entry_settings(nodes=None) -> bool: + """Monitor -> Monitor Entry Settings (nested). Assumes Monitor is showing. The + row label collides case-insensitively with the destination title, so the + vanishing source is a bottom-nav sibling ("History") present on Monitor and + gone on the nested screen.""" + nodes = ui() if nodes is None else nodes + trig = find_node_ci(nodes, MON_ENTRY_ROW) + return trig is not None and and_reach_surface(trig, MON_ENTRY_TITLE, "History") + + +def and_reach_monitor_entry(nodes=None) -> bool: + """Full depth-2 chain from Dashboard: -> Monitor -> Monitor Entry Settings.""" + if not and_reach_monitor(nodes): + return False + return and_reach_entry_settings() + + +def and_back_from_entry() -> bool: + """Tap the nested-screen back arrow ("Back") to return to Monitor; pop one + surface without a hardware BACK (the arrow already dismissed the surface).""" + b = find_node(ui(), content_desc="Back") + if b is None or not tap_node(b): + return False + _dec_depth() + return True + + +# ── Calibrate dialog sub-steps (used inside tests; already-open dialog assumed) ── + +def cal_pick_divide() -> bool: + """Tap the 2nd RadioButton (Divide). Returns True iff it became checked.""" + rb = radio_buttons() + if len(rb) < 2 or not tap_node(rb[1]): + return False + rb = radio_buttons() + return len(rb) >= 2 and rb[1].get("checked") == "true" + + +def cal_set_exponent(exp_text: str) -> bool: + """Open the spinner (its collapsed EditText shows "10^0") and pick `exp_text` + (e.g. "10^3"). Returns True iff the collapsed spinner then shows it.""" + ed = find_node(ui(), text=SPINNER_LABEL) + if ed is None or not tap_node(ed): + return False + item = find_node(ui(), text=exp_text) + if item is None or not tap_node(item): + return False + return find_node(ui(), text=exp_text) is not None + + +def cal_close() -> bool: + """Tap the dialog's Close button (tap_node — Close is a DANGEROUS_TEXT so + safe_tap would refuse; it only dismisses the dialog).""" + c = find_node(ui(), text=CAL_CLOSE) + return c is not None and tap_node(c) + + +def cal_reset() -> bool: + """Tap the dialog's Reset button (tap_node — Reset is a DANGEROUS_TEXT, but the + app's Reset only resets the multiplier PREFERENCE, never user data). OBSERVED: + Reset both restores the value to 900000 mA AND dismisses the dialog, so there + is no separate Close to tap afterwards.""" + r = find_node(ui(), text=CAL_RESET) + return r is not None and tap_node(r) + + +def restore_multiplier() -> None: + """Open Calibrate and tap Reset (which restores + closes), leaving the default + multiplier and Current == 900000 mA. Balances the depth counter.""" + if and_enter_calibrate(): + cal_reset() + _dec_depth() + read_first(cur_value, CUR_DEFAULT) + + +def open_settings() -> bool: + """Dashboard -> Settings tab. Confirms a Settings row appeared.""" + trig = find_node(ui(), content_desc=NAV_SETTINGS) + if trig is None or not tap_node(trig): + return False + return find_node_ci(ui(), SET_FOLLOW) is not None + + +def open_dashboard() -> bool: + """ -> Dashboard tab. Confirms the Dashboard FAB or a card appeared.""" + trig = find_node(ui(), content_desc=NAV_DASHBOARD) + if trig is None or not tap_node(trig): + return False + nodes = ui() + return (find_node(nodes, content_desc=FAB_OPEN) is not None + or cur_value(nodes) != "" or find_node(nodes, text="Dual Cell") is not None) + + +# ══════════════════════════════════════════════════════════════════════════════ +# FLAGSHIP: multiplier persists across process death +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_multiplier_persists_process_death", + "interaction_multiplier_persists_process_death_vlm")) +def test_multiplier_persists_process_death(): + restart_app() + if not wait_for_foreground(): + record("interaction_multiplier_persists_process_death", False, + "setup_failed: app did not reach foreground", + depth=1, jump_kind="transition", + expect="900 mA survives process death") + vlm_assert("interaction_multiplier_persists_process_death", + "In the battery info list, does the Battery Current row show a " + "SMALL number like 900 (three digits) rather than a large number " + "like 900000 (six digits)?", + RESULTS_DIR, depth=0, jump_kind="none", tag="content") + return + before = read_first(cur_value, CUR_DEFAULT) + # multi-step: open dialog -> Divide -> 10^3 -> Close + if not and_enter_calibrate(): + record("interaction_multiplier_persists_process_death", False, + "feature_missing: Calibrate dialog did not open on Dashboard", + depth=1, jump_kind="transition", + expect="900 mA survives process death") + vlm_assert("interaction_multiplier_persists_process_death", + "In the battery info list, does the Battery Current row show a " + "SMALL number like 900 rather than a large number like 900000?", + RESULTS_DIR, depth=0, jump_kind="none", tag="content") + return + steps_ok = cal_pick_divide() and cal_set_exponent("10^3") and cal_close() + _dec_depth() # dialog dismissed by Close + after = read_first(cur_value, CUR_DIV3) + changed = (before == CUR_DEFAULT) and (after == CUR_DIV3) + # THE probe: kill the process, relaunch, assert the value survived. + force_stop_and_relaunch() + wait_for_foreground() + survived = read_first(cur_value, CUR_DIV3) + ok = steps_ok and changed and (survived == CUR_DIV3) + record("interaction_multiplier_persists_process_death", ok, + "" if ok else + f"behavior_wrong: expected Current {CUR_DEFAULT}->{CUR_DIV3} then " + f"{CUR_DIV3} after relaunch; saw before={before!r} after={after!r} " + f"survived={survived!r}", + depth=1, jump_kind="transition", + expect=f"Battery Current {CUR_DIV3} survives process death") + # VLM corroboration of the rendered small value on the relaunched dashboard. + vlm_assert("interaction_multiplier_persists_process_death", + "In the battery info list, does the Battery Current row show a SMALL " + "number like 900 (about three digits) rather than a large number " + "like 900000 (six digits)?", + RESULTS_DIR, depth=0, jump_kind="none", tag="content") + # RESTORE: reopen dialog and Reset back to the default multiplier. + restore_multiplier() + + +# ══════════════════════════════════════════════════════════════════════════════ +# Temperature unit persists across process death +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_temp_unit_persists_process_death",)) +def test_temp_unit_persists_process_death(): + restart_app() + if not wait_for_foreground(): + record("interaction_temp_unit_persists_process_death", False, + "setup_failed: app did not reach foreground", + depth=0, jump_kind="transition", + expect="77.0°F survives process death") + return + before = read_first(temp_value, TEMP_C) + sw = find_node(ui(), content_desc=CD_SWAP) + if sw is None or not tap_node(sw): + record("interaction_temp_unit_persists_process_death", False, + "feature_missing: no 'Swap Unit' control on the temperature card", + depth=0, jump_kind="transition", + expect="77.0°F survives process death") + return + after = read_first(temp_value, TEMP_F) + force_stop_and_relaunch() + wait_for_foreground() + survived = read_first(temp_value, TEMP_F) + ok = (before == TEMP_C) and (after == TEMP_F) and (survived == TEMP_F) + record("interaction_temp_unit_persists_process_death", ok, + "" if ok else + f"behavior_wrong: expected temp {TEMP_C}->{TEMP_F} then {TEMP_F} after " + f"relaunch; saw before={before!r} after={after!r} survived={survived!r}", + depth=0, jump_kind="transition", + expect=f"Battery Temperature {TEMP_F} survives process death") + # RESTORE: swap back to Celsius. + sw = find_node(ui(), content_desc=CD_SWAP) + if sw: + tap_node(sw) + read_first(temp_value, TEMP_C) + + +# ══════════════════════════════════════════════════════════════════════════════ +# Dark mode persists across process death (theme is not in the tree -> VLM color) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_dark_mode_persists_process_death_vlm",)) +def test_dark_mode_persists_process_death(): + restart_app() + if not wait_for_foreground() or not open_settings(): + vlm_assert("interaction_dark_mode_persists_process_death", + "Is this screen rendered with a DARK theme, i.e. a mostly BLACK " + "or very dark background behind the content?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="color") + return + nodes = ui() + fs = switch_for_label(nodes, SET_FOLLOW) + dk = switch_for_label(nodes, SET_DARK) + if fs is not None and dk is not None: + # follow-system OFF unlocks the dark switch; then dark ON. + if fs.get("checked") == "true": + tap_node(fs) + nodes = ui() + dk = switch_for_label(nodes, SET_DARK) + if dk is not None and dk.get("checked") == "false": + tap_node(dk) + # THE probe: kill + relaunch, then judge the rendered theme (Settings surface). + force_stop_and_relaunch() + wait_for_foreground() + open_settings() + and_enter("settings") # depth backing for the VLM assertion on Settings + vlm_assert("interaction_dark_mode_persists_process_death", + "Is this Settings screen rendered with a DARK theme, i.e. a mostly " + "BLACK or very dark background behind the toggle rows?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="color") + _dec_depth() + # RESTORE: dark OFF, then follow-system ON. + nodes = ui() + dk = switch_for_label(nodes, SET_DARK) + if dk is not None and dk.get("checked") == "true": + tap_node(dk) + nodes = ui() + fs = switch_for_label(nodes, SET_FOLLOW) + if fs is not None and fs.get("checked") == "false": + tap_node(fs) + + +# ══════════════════════════════════════════════════════════════════════════════ +# Show-FAB setting persists + cross-surface consequence (rule + 2 VLM layout) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_show_fab_persists_cross_surface", + "interaction_show_fab_off_no_fab_vlm", + "interaction_show_fab_on_fab_back_vlm")) +def test_show_fab_persists_cross_surface(): + restart_app() + if not wait_for_foreground(): + record("interaction_show_fab_persists_cross_surface", False, + "setup_failed: app did not reach foreground", + depth=0, jump_kind="transition", + expect="Dashboard FAB gone after Show-FAB OFF, still gone after relaunch") + vlm_assert("interaction_show_fab_off_no_fab", + "Is the bottom-right corner of the screen EMPTY, with NO round " + "floating action button (no wrench button) there?", + RESULTS_DIR, depth=0, jump_kind="transition", tag="layout") + vlm_assert("interaction_show_fab_on_fab_back", + "Is a round floating action button with a wrench icon visible in " + "the BOTTOM-RIGHT of the screen?", + RESULTS_DIR, depth=0, jump_kind="none", tag="layout") + return + fab_before = find_node(ui(), content_desc=FAB_OPEN) is not None + if not open_settings(): + record("interaction_show_fab_persists_cross_surface", False, + "setup_failed: could not open Settings", + depth=0, jump_kind="transition", + expect="Dashboard FAB gone after Show-FAB OFF, still gone after relaunch") + vlm_assert("interaction_show_fab_off_no_fab", + "Is the bottom-right corner EMPTY with NO round wrench button?", + RESULTS_DIR, depth=0, jump_kind="transition", tag="layout") + vlm_assert("interaction_show_fab_on_fab_back", + "Is a round wrench floating button visible in the BOTTOM-RIGHT?", + RESULTS_DIR, depth=0, jump_kind="none", tag="layout") + return + sw = switch_for_label(ui(), SET_FAB) + toggled_off = False + if sw is not None and sw.get("checked") == "true": + tap_node(sw) + sw2 = switch_for_label(ui(), SET_FAB) + toggled_off = sw2 is not None and sw2.get("checked") == "false" + # cross-surface consequence: FAB gone on Dashboard + open_dashboard() + fab_after_off = find_node(ui(), content_desc=FAB_OPEN) is not None + vlm_assert("interaction_show_fab_off_no_fab", + "Is the bottom-right corner of the screen EMPTY, with NO round " + "floating action button (no wrench button) there?", + RESULTS_DIR, depth=0, jump_kind="transition", tag="layout") + # persistence: kill + relaunch, FAB still gone + force_stop_and_relaunch() + wait_for_foreground() + fab_after_relaunch = find_node(ui(), content_desc=FAB_OPEN) is not None + persisted_gone = (fab_before is True and toggled_off and not fab_after_off + and not fab_after_relaunch) + # RESTORE: Settings -> toggle ON -> Dashboard FAB back + fab_back = False + if open_settings(): + sw = switch_for_label(ui(), SET_FAB) + if sw is not None and sw.get("checked") == "false": + tap_node(sw) + open_dashboard() + fab_back = find_node(ui(), content_desc=FAB_OPEN) is not None + ok = persisted_gone and fab_back + record("interaction_show_fab_persists_cross_surface", ok, + "" if ok else + f"behavior_wrong: Show-FAB OFF should hide the Dashboard FAB and survive " + f"relaunch, ON should restore it; fab_before={fab_before} " + f"off_dash={fab_after_off} relaunch={fab_after_relaunch} back={fab_back}", + depth=0, jump_kind="transition", + expect="Dashboard 'Open menu' FAB gone after OFF+relaunch, back after ON") + vlm_assert("interaction_show_fab_on_fab_back", + "Is a round floating action button with a wrench icon visible in the " + "BOTTOM-RIGHT of the screen?", + RESULTS_DIR, depth=0, jump_kind="none", tag="layout") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Monitor-entry checkbox persists across navigation (multi-record integrity, d2) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_monitor_checkbox_persists_nav", + "interaction_monitor_checkbox_row_unchecked_vlm")) +def test_monitor_checkbox_persists_nav(): + restart_app() + if not wait_for_foreground() or not and_reach_monitor_entry(): + record("interaction_monitor_checkbox_persists_nav", False, + "setup_failed: could not reach Monitor Entry Settings (depth 2)", + depth=2, jump_kind="transition", + expect="box #1 stays off across re-navigation, others stay on") + vlm_assert("interaction_monitor_checkbox_row_unchecked", + "In this list of labelled checkboxes, is at least ONE checkbox " + "UNCHECKED (empty) while the others are CHECKED (filled)?", + RESULTS_DIR, depth=2, jump_kind="transition", tag="content") + return + cbs = check_boxes() + initial = [c.get("checked") for c in cbs] + all_on_initial = len(cbs) >= 2 and all(s == "true" for s in initial) + # toggle box #0 OFF + toggled = False + if cbs: + tap_node(cbs[0]) + cbs = check_boxes() + toggled = cbs and cbs[0].get("checked") == "false" + others_on = cbs and all(c.get("checked") == "true" for c in cbs[1:]) + # VLM: one row visibly unchecked while others checked + vlm_assert("interaction_monitor_checkbox_row_unchecked", + "In this list of labelled checkboxes, is at least ONE checkbox " + "UNCHECKED (empty box) while the others are CHECKED (filled with a " + "check mark)?", + RESULTS_DIR, depth=2, jump_kind="transition", tag="content") + # Back to Monitor, then re-enter -> box #0 STILL off, others STILL on + and_back_from_entry() + reentered = and_reach_entry_settings() + cbs2 = check_boxes() + still_off = reentered and cbs2 and cbs2[0].get("checked") == "false" + rest_still_on = cbs2 and all(c.get("checked") == "true" for c in cbs2[1:]) + ok = (all_on_initial and toggled and others_on and still_off and rest_still_on) + record("interaction_monitor_checkbox_persists_nav", ok, + "" if ok else + f"behavior_wrong: toggled box should persist across re-nav with peers " + f"intact; all_on0={all_on_initial} toggled={toggled} " + f"peers0={others_on} still_off={still_off} peers1={rest_still_on}", + depth=2, jump_kind="transition", + expect="entry box #1 off after Back+re-enter; the other 8 boxes still on") + # RESTORE: re-check box #0 + cbs3 = check_boxes() + if cbs3 and cbs3[0].get("checked") == "false": + tap_node(cbs3[0]) + + +# ══════════════════════════════════════════════════════════════════════════════ +# Monitor-entry checkbox persists across process death (depth 2) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_monitor_checkbox_persists_process_death",)) +def test_monitor_checkbox_persists_process_death(): + restart_app() + if not wait_for_foreground() or not and_reach_monitor_entry(): + record("interaction_monitor_checkbox_persists_process_death", False, + "setup_failed: could not reach Monitor Entry Settings (depth 2)", + depth=2, jump_kind="transition", + expect="box #2 off survives process death, others on") + return + cbs = check_boxes() + idx = 1 # box #2 (0-based index 1) + all_on = len(cbs) > idx and all(c.get("checked") == "true" for c in cbs) + toggled = False + if len(cbs) > idx: + tap_node(cbs[idx]) + cbs = check_boxes() + toggled = len(cbs) > idx and cbs[idx].get("checked") == "false" + # kill + relaunch, re-navigate depth 2, assert box #2 still off + force_stop_and_relaunch() + wait_for_foreground() + reentered = and_reach_monitor_entry() + cbs2 = check_boxes() + still_off = reentered and len(cbs2) > idx and cbs2[idx].get("checked") == "false" + peers_on = cbs2 and all(c.get("checked") == "true" + for i, c in enumerate(cbs2) if i != idx) + ok = all_on and toggled and still_off and peers_on + record("interaction_monitor_checkbox_persists_process_death", ok, + "" if ok else + f"behavior_wrong: box #2 off should survive process death with peers on; " + f"all_on={all_on} toggled={toggled} still_off={still_off} peers={peers_on}", + depth=2, jump_kind="transition", + expect="entry box #2 off after relaunch; the other 8 boxes still on") + # RESTORE: re-check box #2 + cbs3 = check_boxes() + if len(cbs3) > idx and cbs3[idx].get("checked") == "false": + tap_node(cbs3[idx]) + + +# ══════════════════════════════════════════════════════════════════════════════ +# Multi-step calibrate integrity (3+ steps, no persistence): 10^2 = 9000, Reset back +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_calibrate_sequence_integrity",)) +def test_calibrate_sequence_integrity(): + restart_app() + if not wait_for_foreground(): + record("interaction_calibrate_sequence_integrity", False, + "setup_failed: app did not reach foreground", + depth=1, jump_kind="transition", + expect="Current 9000 mA after Divide 10^2, back to 900000 after Reset") + return + before = read_first(cur_value, CUR_DEFAULT) + if not and_enter_calibrate(): + record("interaction_calibrate_sequence_integrity", False, + "feature_missing: Calibrate dialog did not open", + depth=1, jump_kind="transition", + expect="Current 9000 mA after Divide 10^2, back to 900000 after Reset") + return + # step 1 Divide, step 2 pick 10^2, step 3 Close + seq_ok = cal_pick_divide() and cal_set_exponent("10^2") and cal_close() + _dec_depth() + mid = read_first(cur_value, CUR_DIV2) + # step 4 reopen, step 5 Reset (restores value AND closes the dialog) + reopened = and_enter_calibrate() + if reopened: + cal_reset() + _dec_depth() + final = read_first(cur_value, CUR_DEFAULT) + ok = (before == CUR_DEFAULT and seq_ok and mid == CUR_DIV2 + and reopened and final == CUR_DEFAULT) + record("interaction_calibrate_sequence_integrity", ok, + "" if ok else + f"behavior_wrong: expected {CUR_DEFAULT}->(Divide 10^2)->{CUR_DIV2}->" + f"(Reset)->{CUR_DEFAULT}; saw before={before!r} mid={mid!r} final={final!r}", + depth=1, jump_kind="transition", + expect=f"Current {CUR_DIV2} after Divide 10^2, {CUR_DEFAULT} after Reset") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Multi-step: change multiplier THEN dual-cell, then read power (dependency chain) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_multiplier_then_dual_power", + "interaction_dual_power_doubled_vlm")) +def test_multiplier_then_dual_power(): + restart_app() + if not wait_for_foreground(): + record("interaction_multiplier_then_dual_power", False, + "setup_failed: app did not reach foreground", + depth=1, jump_kind="transition", + expect="Power 4.50 W at Divide 10^3, doubles to 9 W when Dual Cell ON") + vlm_assert("interaction_dual_power_doubled", + "Does the Battery Power row show a SMALL number (a few digits, " + "like 9) rather than a large number like 4500?", + RESULTS_DIR, depth=0, jump_kind="transition", tag="content") + return + # step 1-3: Divide 10^3 -> Current 900 mA, Power 4.50 W + if not and_enter_calibrate(): + record("interaction_multiplier_then_dual_power", False, + "feature_missing: Calibrate dialog did not open", + depth=1, jump_kind="transition", + expect="Power 4.50 W at Divide 10^3, doubles to 9 W when Dual Cell ON") + vlm_assert("interaction_dual_power_doubled", + "Does the Battery Power row show a SMALL number (a few digits) " + "rather than a large number like 4500?", + RESULTS_DIR, depth=0, jump_kind="transition", tag="content") + return + calc_ok = cal_pick_divide() and cal_set_exponent("10^3") and cal_close() + _dec_depth() + pow_div3 = read_first(power_value, POW_DIV3) + cur_div3 = cur_value(ui()) + # step 4: Dual Cell ON -> power doubles (4.50 -> rendered "9 W") + dual = find_node(ui(), content_desc=CD_DUAL) + dual_toggled = dual is not None and tap_node(dual) + pow_dual = read_first(power_value, POW_DIV3_DUAL) + dual_now = dual_value(ui()) + doubled = (pow_div3 == POW_DIV3 and pow_dual == POW_DIV3_DUAL + and dual_now == DUAL_YES) + # VLM: rendered power card shows a small value (not the default 4500). This is + # true both at 4.50 and after doubling to 9, and discriminates from 4500. + vlm_assert("interaction_dual_power_doubled", + "Does the Battery Power row show a SMALL number (only a few " + "characters, such as 9 or 9.00) rather than a large number like " + "4500?", + RESULTS_DIR, depth=0, jump_kind="transition", tag="content") + ok = calc_ok and cur_div3 == CUR_DIV3 and dual_toggled and doubled + record("interaction_multiplier_then_dual_power", ok, + "" if ok else + f"behavior_wrong: Divide 10^3 should give Power {POW_DIV3}; Dual ON should " + f"double it to {POW_DIV3_DUAL}; saw cur={cur_div3!r} pow3={pow_div3!r} " + f"powdual={pow_dual!r} dual={dual_now!r}", + depth=1, jump_kind="transition", + expect=f"Power {POW_DIV3} at Divide 10^3, {POW_DIV3_DUAL} with Dual Cell ON") + # RESTORE: dual OFF, then Reset multiplier + dual = find_node(ui(), content_desc=CD_DUAL) + if dual and dual_value(ui()) == DUAL_YES: + tap_node(dual) + restore_multiplier() + + +# ══════════════════════════════════════════════════════════════════════════════ +# Idempotence sequences (small integrity: two toggles return to origin) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_temp_swap_idempotent",)) +def test_temp_swap_idempotent(): + restart_app() + if not wait_for_foreground(): + record("interaction_temp_swap_idempotent", False, + "setup_failed: app did not reach foreground", + depth=0, jump_kind="transition", expect="temp back to 25.0°C after two swaps") + return + start = read_first(temp_value, TEMP_C) + sw = find_node(ui(), content_desc=CD_SWAP) + if sw is None or not tap_node(sw): + record("interaction_temp_swap_idempotent", False, + "feature_missing: no 'Swap Unit' control", + depth=0, jump_kind="transition", expect="temp back to 25.0°C after two swaps") + return + mid = read_first(temp_value, TEMP_F) + sw = find_node(ui(), content_desc=CD_SWAP) + tap_node(sw) + end = read_first(temp_value, TEMP_C) + ok = (start == TEMP_C and mid == TEMP_F and end == TEMP_C) + record("interaction_temp_swap_idempotent", ok, + "" if ok else + f"behavior_wrong: two swaps should return to {TEMP_C}; saw " + f"start={start!r} mid={mid!r} end={end!r}", + depth=0, jump_kind="transition", + expect=f"temp {TEMP_C}->{TEMP_F}->{TEMP_C} across two swaps") + + +@and_test(expects=("interaction_dual_toggle_idempotent",)) +def test_dual_toggle_idempotent(): + restart_app() + if not wait_for_foreground(): + record("interaction_dual_toggle_idempotent", False, + "setup_failed: app did not reach foreground", + depth=0, jump_kind="transition", expect="Dual Cell back to No after two toggles") + return + start = dual_value(ui()) + d = find_node(ui(), content_desc=CD_DUAL) + if d is None or not tap_node(d): + record("interaction_dual_toggle_idempotent", False, + "feature_missing: no 'Toggle Dual Battery' control", + depth=0, jump_kind="transition", expect="Dual Cell back to No after two toggles") + return + mid = dual_value(ui()) + d = find_node(ui(), content_desc=CD_DUAL) + tap_node(d) + end = dual_value(ui()) + ok = (start == DUAL_NO and mid == DUAL_YES and end == DUAL_NO) + record("interaction_dual_toggle_idempotent", ok, + "" if ok else + f"behavior_wrong: two dual toggles should return to {DUAL_NO}; saw " + f"start={start!r} mid={mid!r} end={end!r}", + depth=0, jump_kind="transition", + expect=f"Dual Cell {DUAL_NO}->{DUAL_YES}->{DUAL_NO} across two toggles") + + +# ══════════════════════════════════════════════════════════════════════════════ +# FAB expand -> collapse consequence (2-step interaction returning to origin) + VLM +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_fab_expand_collapse", + "interaction_fab_expanded_stack_vlm")) +def test_fab_expand_collapse(): + restart_app() + if not wait_for_foreground(): + record("interaction_fab_expand_collapse", False, + "setup_failed: app did not reach foreground", + depth=0, jump_kind="transition", + expect="Open menu -> Close menu -> Open menu") + vlm_assert("interaction_fab_expanded_stack", + "Are there several stacked action buttons (a vertical column of " + "labelled pill-shaped buttons) shown above the bottom-right " + "floating button?", + RESULTS_DIR, depth=0, jump_kind="none", tag="layout") + return + open_present = find_node(ui(), content_desc=FAB_OPEN) is not None + fab = find_node(ui(), content_desc=FAB_OPEN) + expanded = False + if fab is not None and tap_node(fab): + nodes = ui() + expanded = (find_node(nodes, content_desc=FAB_CLOSE) is not None + and find_node(nodes, content_desc=FAB_OPEN) is None) + # VLM: the expanded FAB reveals a taller stack of action buttons + vlm_assert("interaction_fab_expanded_stack", + "Are there several stacked action buttons (a vertical column of " + "labelled pill-shaped buttons such as 'Enable root mode' and " + "'Manage custom entries') shown above the bottom-right floating " + "button?", + RESULTS_DIR, depth=0, jump_kind="none", tag="layout") + # collapse: tap Close menu -> Open menu returns (tap_node — do not safe_tap a + # control whose desc contains "Close") + collapsed = False + cm = find_node(ui(), content_desc=FAB_CLOSE) + if cm is not None and tap_node(cm): + nodes = ui() + collapsed = (find_node(nodes, content_desc=FAB_OPEN) is not None + and find_node(nodes, content_desc=FAB_CLOSE) is None) + ok = open_present and expanded and collapsed + record("interaction_fab_expand_collapse", ok, + "" if ok else + f"behavior_wrong: FAB should expand ('Close menu') then collapse back " + f"('Open menu'); open0={open_present} expanded={expanded} " + f"collapsed={collapsed}", + depth=0, jump_kind="transition", + expect="FAB 'Open menu' -> 'Close menu' -> 'Open menu' round-trip") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Extra multi-record integrity: three sequential dashboard mutations, each read +# back, then all restored — proves the surface holds independent per-card state. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_three_card_state_integrity",)) +def test_three_card_state_integrity(): + restart_app() + if not wait_for_foreground(): + record("interaction_three_card_state_integrity", False, + "setup_failed: app did not reach foreground", + depth=1, jump_kind="transition", + expect="temp°F + dual Yes + Current 900 mA all hold together") + return + # record 1: swap temp to °F + sw = find_node(ui(), content_desc=CD_SWAP) + r1 = sw is not None and tap_node(sw) + temp_f = read_first(temp_value, TEMP_F) + # record 2: dual ON + d = find_node(ui(), content_desc=CD_DUAL) + r2 = d is not None and tap_node(d) + dual_yes = dual_value(ui()) + # record 3: Divide 10^3 via dialog + r3 = and_enter_calibrate() + if r3: + r3 = cal_pick_divide() and cal_set_exponent("10^3") and cal_close() + _dec_depth() + cur3 = read_first(cur_value, CUR_DIV3) + # integrity: after the 3rd mutation, records 1 and 2 are STILL intact + nodes = ui() + temp_still = temp_value(nodes) + dual_still = dual_value(nodes) + ok = (r1 and r2 and r3 and temp_f == TEMP_F and dual_yes == DUAL_YES + and cur3 == CUR_DIV3 and temp_still == TEMP_F and dual_still == DUAL_YES) + record("interaction_three_card_state_integrity", ok, + "" if ok else + f"behavior_wrong: three independent card mutations must all hold; " + f"tempF={temp_f!r} dualYes={dual_yes!r} cur3={cur3!r} " + f"tempStill={temp_still!r} dualStill={dual_still!r}", + depth=1, jump_kind="transition", + expect=f"temp {TEMP_F} + Dual {DUAL_YES} + Current {CUR_DIV3} all intact together") + # RESTORE all three + if dual_value(ui()) == DUAL_YES: + d = find_node(ui(), content_desc=CD_DUAL) + if d: + tap_node(d) + if temp_value(ui()) == TEMP_F: + sw = find_node(ui(), content_desc=CD_SWAP) + if sw: + tap_node(sw) + restore_multiplier() + + +# ══════════════════════════════════════════════════════════════════════════════ +# Radio selection sequence integrity: Divide selected persists across a reopen; +# Reset (which closes the dialog) returns the selection to Multiply, confirmed by +# a further reopen. A 3+-step selection sequence verified by re-observation. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_radio_selection_sequence",)) +def test_radio_selection_sequence(): + restart_app() + if not wait_for_foreground() or not and_enter_calibrate(): + record("interaction_radio_selection_sequence", False, + "setup_failed: Calibrate dialog did not open", + depth=1, jump_kind="transition", + expect="Divide stays selected on reopen; Multiply selected after Reset+reopen") + return + rb = radio_buttons() + start_multiply = len(rb) >= 2 and rb[0].get("checked") == "true" \ + and rb[1].get("checked") == "false" + # step 1: select Divide + picked = cal_pick_divide() + # step 2: Close then reopen -> Divide persists (multiplier pref) + cal_close() + _dec_depth() + reopened = and_enter_calibrate() + rb = radio_buttons() + divide_persisted = (reopened and len(rb) >= 2 + and rb[1].get("checked") == "true" + and rb[0].get("checked") == "false") + # step 3: Reset -> restores default AND dismisses the dialog + reset_ok = cal_reset() + _dec_depth() + # step 4: reopen -> Multiply is selected again (Reset restored the default) + reopened2 = and_enter_calibrate() + rb = radio_buttons() + back_to_multiply = (reopened2 and len(rb) >= 2 + and rb[0].get("checked") == "true" + and rb[1].get("checked") == "false") + # close the dialog we just opened for the check + if reopened2: + cal_close() + _dec_depth() + ok = (start_multiply and picked and divide_persisted and reset_ok + and back_to_multiply) + record("interaction_radio_selection_sequence", ok, + "" if ok else + f"behavior_wrong: Divide should persist across reopen and Reset should " + f"restore Multiply; start_mul={start_multiply} picked={picked} " + f"persisted={divide_persisted} reset={reset_ok} back_mul={back_to_multiply}", + depth=1, jump_kind="transition", + expect="Divide radio checked on reopen; Multiply radio checked after Reset+reopen") + # RESTORE: confirm value back to default (Reset already restored it) + read_first(cur_value, CUR_DEFAULT) + + +# ══════════════════════════════════════════════════════════════════════════════ +# Follow-system -> dark dependency sequence + restore (multi-step, no relaunch) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_follow_system_dark_dependency",)) +def test_follow_system_dark_dependency(): + restart_app() + if not wait_for_foreground() or not open_settings(): + record("interaction_follow_system_dark_dependency", False, + "setup_failed: could not open Settings", + depth=1, jump_kind="transition", + expect="dark switch disabled until follow-system OFF, then enabled") + return + and_enter("settings") + nodes = ui() + fs = switch_for_label(nodes, SET_FOLLOW) + dk = switch_for_label(nodes, SET_DARK) + if fs is None or dk is None: + record("interaction_follow_system_dark_dependency", False, + "feature_missing: follow-system / dark switch not found in Settings", + depth=1, jump_kind="transition", + expect="dark switch disabled until follow-system OFF, then enabled") + _dec_depth() + return + # step 1: initial state — follow ON, dark disabled + init_ok = (fs.get("checked") == "true" and dk.get("enabled") == "false") + # step 2: follow OFF -> dark becomes enabled + tap_node(fs) + nodes = ui() + dk = switch_for_label(nodes, SET_DARK) + fs2 = switch_for_label(nodes, SET_FOLLOW) + enabled_now = (dk is not None and dk.get("enabled") == "true" + and fs2 is not None and fs2.get("checked") == "false") + # step 3: restore follow ON -> dark disabled again + if fs2 is not None: + tap_node(fs2) + nodes = ui() + dk = switch_for_label(nodes, SET_DARK) + restored = dk is not None and dk.get("enabled") == "false" + ok = init_ok and enabled_now and restored + record("interaction_follow_system_dark_dependency", ok, + "" if ok else + f"behavior_wrong: dark switch should enable only when follow-system is " + f"OFF; init={init_ok} enabled_after_off={enabled_now} restored={restored}", + depth=1, jump_kind="transition", + expect="dark switch enabled=false while follow ON, enabled=true when OFF") + _dec_depth() + + +TESTS = [ + # flagship persistence (multiplier) — rule + content VLM + test_multiplier_persists_process_death, + # other persistence probes + test_temp_unit_persists_process_death, + test_dark_mode_persists_process_death, # VLM color + test_show_fab_persists_cross_surface, # rule + 2 layout VLM + # multi-record integrity across nav / process death (depth 2) + test_monitor_checkbox_persists_nav, # rule + content VLM + test_monitor_checkbox_persists_process_death, + # multi-step sequences (3+) + test_calibrate_sequence_integrity, + test_multiplier_then_dual_power, # rule + content VLM + test_three_card_state_integrity, + test_radio_selection_sequence, + test_follow_system_dark_dependency, + # small idempotence integrity + test_temp_swap_idempotent, + test_dual_toggle_idempotent, + # FAB expand/collapse — rule + layout VLM + test_fab_expand_collapse, +] + +if __name__ == "__main__": + run_suite(TESTS, "interaction") diff --git a/android/dijia1124-plusplusbattery/tests/test_android_navigation.py b/android/dijia1124-plusplusbattery/tests/test_android_navigation.py new file mode 100644 index 0000000000000000000000000000000000000000..c4600eee06e1f4fb30445593ec636a54fc78b38e --- /dev/null +++ b/android/dijia1124-plusplusbattery/tests/test_android_navigation.py @@ -0,0 +1,710 @@ +#!/usr/bin/env python3 +"""NAVIGATION lane — PlusPlusBattery (Jetpack Compose, single Activity). + +Sole owner of surface REACHABILITY (jump_kind="reach") and BACK-STACK integrity, +and the carrier of the suite's depth>=2 chains. Every jump is proven the honest +way: the TARGET surface's discriminating element APPEARED *and* the SOURCE +surface's element DISAPPEARED (and_reach / and_reach_surface). A screen that was +already in the tree was never "reached". + +CEDES to other lanes: content strings (text), checked/enabled/selected (states), +computed values (computation), CRUD (interaction). This file asserts only that a +trigger LANDS on the intended surface and that BACK unwinds the stack. + +Every discriminator below was read off the running ORIGINAL with uiautomator: + + Dashboard : title text "Plus Plus Battery"; FAB content-desc "Open menu". + Monitor : title text "Battery Monitor"; text "Monitor entry settings", + "Show in notification bar", "Floating window settings". + History : title text "History"; toolbar content-desc "Export" + "Help" + (top-right); text "Charge Cycle Counts: 10". + Settings : title text "Settings"; text "Follow system theme", + "Set refresh interval (ms)". + Monitor Entry Settings (nested<-Monitor): title text "Monitor Entry Settings"; + text "Please select the entries ..."; 9 CheckBoxes; content-desc + "Back"; NO bottom nav. + Floating Window Settings (nested<-Monitor): title text "Floating Window + Settings"; text "Opacity: 0.75", "Size: 1.00"; content-desc "Back". + About (nested<-Settings, scroll first): title text "About"; text + "Version:"; content-desc "Back". + +Back-stack facts (verified on the original): + * Back arrow (content-desc "Back") on Monitor Entry Settings -> Monitor. + * Back arrow on Floating Window Settings -> Monitor. + * Back arrow on About -> Settings (nested back to its parent tab). + * Hardware BACK on a TOP-LEVEL TAB -> Dashboard (start destination). This + asymmetry is its own test. + +Every test opens its OWN entry point with restart_app() (isolation is a hard +rule). The reach is then proven by a subsequent and_reach_surface/and_reach TAP — +the restart is only the clean starting surface, never the thing being "reached". + +SOURCE-DISCRIMINATOR NOTE. and_reach matches target/source as case-insensitive +SUBSTRINGS of node keys. Three destination TITLES are case-insensitively equal to +a row label on their parent surface ("Monitor Entry Settings"=="Monitor entry +settings", "Floating Window Settings"=="Floating window settings", "About" row == +"About" title), so those titles are unusable as the "source that vanished". For a +nested reach the source is therefore a bottom-nav sibling content-desc (present on +the parent tab, absent on the nested screen); for a nested BACK the source is a +nested-only, non-colliding element ("Please select the entries ...", "Opacity: +0.75", "Version:"). +""" +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 +import android_testgen_kit as _kit # for the private depth counter only + +RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else os.path.dirname(os.path.abspath(__file__)) + + +# ── Surface discriminators ────────────────────────────────────────────────────── +DASH_TITLE = "Plus Plus Battery" # Dashboard title +DASH_FAB = "Open menu" # Dashboard FAB content-desc (unique to Dashboard) +MON_TITLE = "Battery Monitor" # Monitor screen title +MON_ITEM = "Monitor entry settings" # Monitor row -> Monitor Entry Settings +MON_FLOAT = "Floating window settings" # Monitor row -> Floating Window Settings +HIST_TITLE = "History" # History title (also the Help-dialog title) +HIST_EXPORT = "Export" # History toolbar content-desc (top-right) +HIST_HELP = "Help" # History toolbar content-desc (top-right) +HIST_ROW = "Charge Cycle Counts: 10" # History list row +SET_FOLLOW = "Follow system theme" # Settings row (unique to Settings) +SET_REFRESH = "Set refresh interval (ms)" # Settings row +ENTRY_TITLE = "Monitor Entry Settings" # nested screen title +ENTRY_INSTR = "Please select the entries" # nested-only, non-colliding source text +FLOAT_TITLE = "Floating Window Settings" # nested screen title +FLOAT_OPACITY = "Opacity: 0.75" # nested-only, non-colliding source/header +ABOUT_TITLE = "About" # nested screen title +ABOUT_VERSION = "Version:" # nested screen version prefix + +# Bottom-nav sibling content-descs (present on every top-level tab, absent on the +# nested screens). Used as the vanishing source for a nested reach. +NAV_MONITOR = "Monitor" +NAV_HISTORY = "History" + +# Dialog discriminators (the modal REPLACES the tree; the source vanishes). +CAL_TITLE = "Calibrate via Multiplier" # Dashboard Calibrate dialog title +EXPORT_DIALOG = "Export History" # History Export dialog title + + +# ── trigger locators ───────────────────────────────────────────────────────────── + +def tab_trigger(nodes, content_desc: str) -> dict | None: + """A bottom-nav tab by its content-desc (present on every surface except the + one currently selected, which renders its label as text).""" + return find_node(nodes, content_desc=content_desc) + + +def back_node(nodes) -> dict | None: + """The nested-screen top-left back arrow (content-desc "Back"). Its icon child + is not itself clickable, but its centre falls inside the clickable IconButton, + so tapping the centre dismisses the surface.""" + return find_node(nodes, content_desc="Back") + + +def row_trigger(nodes, text: str) -> dict | None: + return find_node(nodes, text=text) or find_node_ci(nodes, text) + + +def _dec_depth() -> int: + """Pop one surface from the kit's depth counter WITHOUT pressing BACK — used + after we dismissed a surface by tapping its own back arrow or a Close/Cancel + button (the surface already changed, so we must not also press hardware BACK).""" + _kit._DEPTH = max(0, _kit._DEPTH - 1) + return _kit._DEPTH + + +# ── depth-family helpers (named and_enter_*/and_reach_*/and_back_* so the depth +# auditor accepts the DECLARED depth/reach as BACKED by real navigation, per the +# kit's DEPTH_FWD_RE / DEPTH_BACK_RE). Each performs a real user-path action and +# drives the kit's own depth counter (and_enter / and_reach_surface). Callers pass +# the SOURCE discriminator of the surface they are actually leaving, so the +# source-vanished half of the proof is checked against the real origin. ─────────── + +def and_reach_tab(nodes, content_desc: str, target: str, source: str) -> bool: + """Tap a bottom-nav tab and PROVE the jump: target appeared, source vanished. + Counts one surface via the kit's and_reach_surface.""" + trig = tab_trigger(nodes, content_desc) + return trig is not None and and_reach_surface(trig, target, source) + + +def and_reach_monitor(nodes=None, source: str = DASH_FAB) -> bool: + """ -> Monitor (default source: the Dashboard FAB).""" + nodes = ui() if nodes is None else nodes + return and_reach_tab(nodes, "Monitor", MON_TITLE, source) + + +def and_reach_history(nodes=None, source: str = DASH_FAB) -> bool: + """ -> History. Pass the origin's discriminator as `source`.""" + nodes = ui() if nodes is None else nodes + return and_reach_tab(nodes, "History", HIST_EXPORT, source) + + +def and_reach_settings(nodes=None, source: str = DASH_FAB) -> bool: + """ -> Settings. Pass the origin's discriminator as `source`.""" + nodes = ui() if nodes is None else nodes + return and_reach_tab(nodes, "Settings", SET_FOLLOW, source) + + +def and_reach_dashboard(nodes=None, source: str = SET_FOLLOW) -> bool: + """ -> Dashboard. Pass the origin's discriminator as `source`.""" + nodes = ui() if nodes is None else nodes + return and_reach_tab(nodes, "Dashboard", DASH_FAB, source) + + +def and_reach_entry_settings(nodes=None) -> bool: + """Monitor -> Monitor Entry Settings (nested). Assumes Monitor is showing. + Source is a bottom-nav sibling ("History") which is present on Monitor and + gone on the nested screen — the row label 'Monitor entry settings' cannot be + the source because it is case-insensitively equal to the destination title.""" + nodes = ui() if nodes is None else nodes + trig = row_trigger(nodes, MON_ITEM) + return trig is not None and and_reach_surface(trig, ENTRY_TITLE, NAV_HISTORY) + + +def and_reach_floating_settings(nodes=None) -> bool: + """Monitor -> Floating Window Settings (nested). Assumes Monitor is showing. + Same bottom-nav-sibling source as entry settings, for the same collision + reason ('Floating window settings' row == 'Floating Window Settings' title).""" + nodes = ui() if nodes is None else nodes + trig = row_trigger(nodes, MON_FLOAT) + return trig is not None and and_reach_surface(trig, FLOAT_TITLE, NAV_HISTORY) + + +def and_reach_about(nodes=None) -> bool: + """Settings -> About (nested). Scrolls About into view first, per the app. + Source is a bottom-nav sibling ("Monitor"), present on the (scrolled) Settings + tab and gone on the nested About screen ('About' row == 'About' title).""" + trig = scroll_into_view(ABOUT_TITLE) + if trig is None: + return False + return and_reach_surface(trig, ABOUT_VERSION, NAV_MONITOR) + + +def and_back_via_arrow(nodes=None) -> bool: + """Tap the nested-screen back arrow (content-desc "Back") and pop one surface. + Named and_back_* so the depth auditor counts it as a surface pop, like the + kit's and_back(). Returns True if the arrow was found and tapped. Does NOT + press hardware BACK (the arrow already dismisses the surface).""" + nodes = ui() if nodes is None else nodes + b = back_node(nodes) + if b is None or not tap_node(b): + return False + _dec_depth() + return True + + +# ══════════════════════════════════════════════════════════════════════════════ +# Top-level tab reachability (each proven target-appeared + source-gone) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_dashboard_to_monitor",)) +def test_reach_dashboard_to_monitor(): + restart_app() + if not wait_for_foreground(): + record("nav_reach_dashboard_to_monitor", False, + "setup_failed: app did not reach foreground", jump_kind="reach", + expect="Monitor title appears, Dashboard FAB gone") + return + nodes = ui() + if find_node(nodes, content_desc=DASH_FAB) is None: + record("nav_reach_dashboard_to_monitor", False, + "setup_failed: not on Dashboard at start (no 'Open menu' FAB)", + jump_kind="reach", + expect="Monitor title appears, Dashboard FAB gone") + return + ok = and_reach_monitor(nodes, source=DASH_FAB) + record("nav_reach_dashboard_to_monitor", ok, + "" if ok else "behavior_wrong: tapping Monitor did not surface the " + "Monitor screen (title 'Battery Monitor' absent or FAB still present)", + jump_kind="reach", + expect="'Battery Monitor' title appears; Dashboard 'Open menu' FAB gone") + + +@and_test(expects=("nav_reach_monitor_to_history",)) +def test_reach_monitor_to_history(): + restart_app() + m = and_reach_monitor(source=DASH_FAB) # Dashboard -> Monitor first + ok = m and and_reach_history(source=MON_TITLE) # Monitor -> History + record("nav_reach_monitor_to_history", ok, + "" if ok else "behavior_wrong: Monitor->History jump not proven " + "(History 'Export' absent or Monitor title still present)", + jump_kind="reach", + expect="History toolbar 'Export' appears; Monitor 'Battery Monitor' gone") + + +@and_test(expects=("nav_reach_history_to_settings",)) +def test_reach_history_to_settings(): + restart_app() + h = and_reach_history(source=DASH_FAB) # Dashboard -> History + ok = h and and_reach_settings(source=HIST_EXPORT) # History -> Settings + record("nav_reach_history_to_settings", ok, + "" if ok else "behavior_wrong: History->Settings jump not proven " + "('Follow system theme' absent or History 'Export' still present)", + jump_kind="reach", + expect="'Follow system theme' appears; History 'Export' toolbar gone") + + +@and_test(expects=("nav_reach_settings_to_dashboard",)) +def test_reach_settings_to_dashboard(): + restart_app() + s = and_reach_settings(source=DASH_FAB) # Dashboard -> Settings + ok = s and and_reach_dashboard(source=SET_FOLLOW) # Settings -> Dashboard + record("nav_reach_settings_to_dashboard", ok, + "" if ok else "behavior_wrong: Settings->Dashboard jump not proven " + "(FAB 'Open menu' absent or 'Follow system theme' still present)", + jump_kind="reach", + expect="Dashboard 'Open menu' FAB appears; 'Follow system theme' gone") + + +@and_test(expects=("nav_reach_dashboard_to_settings",)) +def test_reach_dashboard_to_settings(): + restart_app() + nodes = ui() + trig = tab_trigger(nodes, "Settings") + ok = trig is not None and and_reach_surface(trig, SET_FOLLOW, DASH_FAB) + record("nav_reach_dashboard_to_settings", ok, + "" if ok else "behavior_wrong: Dashboard->Settings jump not proven " + "('Follow system theme' absent or FAB 'Open menu' still present)", + jump_kind="reach", + expect="'Follow system theme' appears; Dashboard 'Open menu' FAB gone") + + +@and_test(expects=("nav_roundtrip_dashboard_settings_dashboard",)) +def test_roundtrip_dashboard_settings_dashboard(): + """Dashboard -> Settings -> Dashboard, each hop proven; ends on Dashboard.""" + restart_app() + hop1 = and_reach_settings(source=DASH_FAB) # Dashboard -> Settings + hop2 = hop1 and and_reach_dashboard(source=SET_FOLLOW) # Settings -> Dashboard + record("nav_roundtrip_dashboard_settings_dashboard", hop2, + "" if hop2 else "behavior_wrong: round-trip Dashboard<->Settings not " + "proven on both hops", + jump_kind="reach", + expect="hop1 Settings 'Follow system theme' appears; hop2 back on " + "Dashboard with 'Open menu' FAB, 'Follow system theme' gone") + + +@and_test(expects=("nav_roundtrip_history_dashboard_history",)) +def test_roundtrip_history_dashboard_history(): + """Dashboard -> History -> Dashboard -> History; every hop a proven reach.""" + restart_app() + hop1 = and_reach_history(source=DASH_FAB) # Dashboard -> History + hop2 = hop1 and and_reach_dashboard(source=HIST_EXPORT) # History -> Dashboard + hop3 = hop2 and and_reach_history(source=DASH_FAB) # Dashboard -> History + record("nav_roundtrip_history_dashboard_history", hop3, + "" if hop3 else "behavior_wrong: History<->Dashboard round-trip not " + "proven on all three hops", + jump_kind="reach", + expect="History 'Export' toolbar reappears after the round-trip; " + "Dashboard 'Open menu' FAB gone on the final hop") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Depth-2 nested chains + BACK unwinding +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_monitor_entry_settings", + "nav_reach_monitor_entry_settings_vlm")) +def test_reach_monitor_entry_settings(): + """Dashboard -> Monitor (surface 1) -> Monitor Entry Settings (surface 2).""" + restart_app() + hop1 = and_reach_monitor(source=DASH_FAB) # surface 1 + hop2 = hop1 and and_reach_entry_settings() # surface 2 + record("nav_reach_monitor_entry_settings", hop2, + "" if hop2 else "behavior_wrong: could not reach Monitor Entry Settings " + "from Monitor ('Monitor Entry Settings' title absent or bottom nav still " + "present)", + depth=2, jump_kind="reach", + expect="'Monitor Entry Settings' title appears; the Monitor tab's " + "bottom-nav 'History' item is gone (nested screen)") + # VLM: the destination truly RENDERED a vertical list of checkbox rows. + vlm_assert("nav_reach_monitor_entry_settings", + "Does this screen show a vertical list of rows, each with a small " + "square checkbox on the LEFT and a text label to its right?", + RESULTS_DIR, tag="layout") + + +@and_test(expects=("nav_reach_entry_settings_toolbar_vlm",)) +def test_reach_entry_settings_toolbar_vlm(): + """VLM position check: the nested screen's back arrow is at the top-left.""" + restart_app() + hop1 = and_reach_monitor(source=DASH_FAB) + hop2 = hop1 and and_reach_entry_settings() + if not hop2: + record("nav_reach_entry_settings_toolbar", False, + "setup_failed: never reached Monitor Entry Settings for the VLM shot", + depth=2, jump_kind="reach", expect="on Monitor Entry Settings") + vlm_assert("nav_reach_entry_settings_toolbar", + "Is there a left-pointing back arrow rendered at the TOP-LEFT of the " + "screen, to the left of a 'Monitor Entry Settings' title?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("nav_backstack_entry_settings_to_monitor",)) +def test_backstack_entry_settings_to_monitor(): + """Depth-2 in, then the nested back arrow pops to Monitor (not Dashboard).""" + restart_app() + hop1 = and_reach_monitor(source=DASH_FAB) + hop2 = hop1 and and_reach_entry_settings() # now on surface 2 + back_ok = False + if hop2: + before = and_showing() + arrow_ok = and_back_via_arrow() # tap the "Back" arrow, pop 1 + after = and_showing() + # Monitor's title returns AND the nested-only instruction text is gone. + # (ENTRY_TITLE cannot be the source: it collides with the Monitor row.) + back_ok = arrow_ok and and_reach(before, after, target=MON_TITLE, + source=ENTRY_INSTR) + record("nav_backstack_entry_settings_to_monitor", back_ok, + "" if back_ok else "behavior_wrong: back arrow did not return to Monitor " + "('Battery Monitor' title absent or the entry-settings screen still shown)", + depth=2, jump_kind="reach", + expect="after one BACK: 'Battery Monitor' restored, the 'Please select " + "the entries ...' instruction gone") + + +@and_test(expects=("nav_reach_floating_window_settings",)) +def test_reach_floating_window_settings(): + """Dashboard -> Monitor (surface 1) -> Floating Window Settings (surface 2).""" + restart_app() + hop1 = and_reach_monitor(source=DASH_FAB) + hop2 = hop1 and and_reach_floating_settings() + record("nav_reach_floating_window_settings", hop2, + "" if hop2 else "behavior_wrong: could not reach Floating Window " + "Settings from Monitor ('Floating Window Settings' title absent or " + "bottom nav still present)", + depth=2, jump_kind="reach", + expect="'Floating Window Settings' title appears; the Monitor tab's " + "bottom-nav 'History' item is gone (nested screen)") + + +@and_test(expects=("nav_reach_floating_toolbar_vlm",)) +def test_reach_floating_toolbar_vlm(): + """VLM position check: Floating Window Settings' back arrow is at the top-left.""" + restart_app() + hop1 = and_reach_monitor(source=DASH_FAB) + hop2 = hop1 and and_reach_floating_settings() + if not hop2: + record("nav_reach_floating_toolbar", False, + "setup_failed: never reached Floating Window Settings for the VLM shot", + depth=2, jump_kind="reach", expect="on Floating Window Settings") + vlm_assert("nav_reach_floating_toolbar", + "Is there a left-pointing back arrow rendered at the TOP-LEFT of the " + "screen, to the left of a 'Floating Window Settings' title?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("nav_backstack_floating_settings_to_monitor",)) +def test_backstack_floating_settings_to_monitor(): + restart_app() + hop1 = and_reach_monitor(source=DASH_FAB) + hop2 = hop1 and and_reach_floating_settings() + back_ok = False + if hop2: + before = and_showing() + arrow_ok = and_back_via_arrow() + after = and_showing() + # FLOAT_TITLE collides with the Monitor row, so use the nested-only header. + back_ok = arrow_ok and and_reach(before, after, target=MON_TITLE, + source=FLOAT_OPACITY) + record("nav_backstack_floating_settings_to_monitor", back_ok, + "" if back_ok else "behavior_wrong: back arrow did not return to Monitor " + "from Floating Window Settings", + depth=2, jump_kind="reach", + expect="after one BACK: 'Battery Monitor' restored, the 'Opacity: 0.75' " + "header gone") + + +@and_test(expects=("nav_reach_about",)) +def test_reach_about(): + """Settings -> About (scroll then tap). Nested reach.""" + restart_app() + s = and_reach_settings(source=DASH_FAB) # Dashboard -> Settings (surface 1) + ok = s and and_reach_about() # scroll + tap About (surface 2) + record("nav_reach_about", ok, + "" if ok else "behavior_wrong: could not reach About from Settings " + "('Version:' absent or Settings bottom nav still present)", + depth=2, jump_kind="reach", + expect="'Version:' line appears; the Settings tab's bottom-nav 'Monitor' " + "item is gone (nested screen)") + + +@and_test(expects=("nav_reach_about_toolbar_vlm",)) +def test_reach_about_toolbar_vlm(): + """VLM position check: About's back arrow is at the top-left.""" + restart_app() + s = and_reach_settings(source=DASH_FAB) + ok = s and and_reach_about() + if not ok: + record("nav_reach_about_toolbar", False, + "setup_failed: never reached About for the VLM shot", + depth=2, jump_kind="reach", expect="on About") + vlm_assert("nav_reach_about_toolbar", + "Is there a left-pointing back arrow rendered at the TOP-LEFT of the " + "screen, to the left of an 'About' title?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("nav_backstack_about_to_settings",)) +def test_backstack_about_to_settings(): + """About's back arrow returns to its PARENT tab (Settings), not to Dashboard.""" + restart_app() + s = and_reach_settings(source=DASH_FAB) + ok = s and and_reach_about() + back_ok = False + if ok: + before = and_showing() + arrow_ok = and_back_via_arrow() # tap About's "Back" arrow + after = and_showing() + # The Settings tab is restored (its bottom-nav 'Monitor' sibling returns) + # and the About 'Version:' line is gone. + back_ok = arrow_ok and and_reach(before, after, target=NAV_MONITOR, + source=ABOUT_VERSION) + record("nav_backstack_about_to_settings", back_ok, + "" if back_ok else "behavior_wrong: About back arrow did not return to " + "the Settings tab", + depth=2, jump_kind="reach", + expect="after About BACK: Settings tab restored (bottom-nav 'Monitor' " + "returns), 'Version:' gone") + + +@and_test(expects=("nav_backstack_deep_unwind_to_dashboard",)) +def test_backstack_deep_unwind_to_dashboard(): + """Full unwind: Dashboard -> Monitor -> Entry Settings, then back arrow to + Monitor, then hardware BACK from the Monitor TAB lands on Dashboard.""" + restart_app() + hop1 = and_reach_monitor(source=DASH_FAB) # surface 1 (Monitor) + hop2 = hop1 and and_reach_entry_settings() # surface 2 (Entry Settings) + at_monitor = False + at_dashboard = False + if hop2: + before = and_showing() + arrow_ok = and_back_via_arrow() # pop nested -> Monitor + mid = and_showing() + # ENTRY_TITLE collides with the Monitor row; use the nested-only text. + at_monitor = arrow_ok and and_reach(before, mid, target=MON_TITLE, + source=ENTRY_INSTR) + if at_monitor: + and_back() # hardware BACK from Monitor TAB + after = and_showing() + at_dashboard = and_reach(mid, after, target=DASH_FAB, source=MON_TITLE) + ok = at_monitor and at_dashboard + record("nav_backstack_deep_unwind_to_dashboard", ok, + "" if ok else "behavior_wrong: two BACKs from Entry Settings did not " + "unwind Monitor then land on Dashboard", + depth=2, jump_kind="reach", + expect="1st BACK: Monitor restored; 2nd BACK: Dashboard 'Open menu' FAB, " + "Monitor title gone") + + +@and_test(expects=("nav_backstack_tab_back_to_dashboard",)) +def test_backstack_tab_back_to_dashboard(): + """The top-level asymmetry: hardware BACK on a NON-start tab (Settings) goes to + the START destination (Dashboard), not to the previously visited tab.""" + restart_app() + s = and_reach_settings(source=DASH_FAB) # surface 1 (Settings tab) + at_dash = False + if s: + before = and_showing() + and_back() # hardware BACK from the tab + after = and_showing() + at_dash = and_reach(before, after, target=DASH_FAB, source=SET_FOLLOW) + record("nav_backstack_tab_back_to_dashboard", at_dash, + "" if at_dash else "behavior_wrong: hardware BACK on the Settings tab " + "did not return to the Dashboard start destination", + depth=1, jump_kind="reach", + expect="BACK from Settings tab lands on Dashboard ('Open menu' FAB " + "appears, 'Follow system theme' gone)") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Dialog reach (modal REPLACES the tree; the source element genuinely vanishes) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_reach_calibrate_dialog",)) +def test_reach_calibrate_dialog(): + """Dashboard Calibrate opens a modal: title appears, the FAB vanishes. Close + dismisses it and the FAB returns.""" + restart_app() + nodes = ui() + trig = find_node(nodes, content_desc="Calibrate") + opened = trig is not None and and_reach_surface(trig, CAL_TITLE, DASH_FAB) + closed = False + if opened: + n2 = ui() + close = row_trigger(n2, "Close") # app's Close (safe dismiss control) + if close is not None: + before = and_showing(n2) + tap_node(close) + _dec_depth() # modal dismissed -> pop counter + after = and_showing() + closed = and_reach(before, after, target=DASH_FAB, source=CAL_TITLE) + ok = opened and closed + record("nav_reach_calibrate_dialog", ok, + "" if ok else "behavior_wrong: Calibrate dialog did not open onto a " + "modal ('Calibrate via Multiplier') or Close did not restore Dashboard", + depth=1, jump_kind="reach", + expect="open: 'Calibrate via Multiplier' appears, FAB 'Open menu' gone; " + "Close: FAB restored, dialog title gone") + + +@and_test(expects=("nav_reach_history_help_dialog",)) +def test_reach_history_help_dialog(): + """History Help opens a modal that replaces the toolbar; Close restores it.""" + restart_app() + h = and_reach_history(source=DASH_FAB) + opened = False + closed = False + if h: + n1 = ui() + trig = find_node(n1, content_desc=HIST_HELP) + if trig is not None: + before = and_showing(n1) + tap_node(trig) + and_enter("history_help_dialog") # depth pop-in for the modal + after = and_showing() + # The dialog adds "Close" and removes the "Export" toolbar icon. + opened = and_reach(before, after, target="Close", source=HIST_EXPORT) + if opened: + n2 = ui() + close = row_trigger(n2, "Close") + if close is not None: + b2 = and_showing(n2) + tap_node(close) + _dec_depth() # modal dismissed -> pop counter + a2 = and_showing() + closed = and_reach(b2, a2, target=HIST_EXPORT, source="Close") + ok = opened and closed + record("nav_reach_history_help_dialog", ok, + "" if ok else "behavior_wrong: History Help dialog did not open (Close " + "absent / Export toolbar still present) or Close did not restore History", + depth=1, jump_kind="reach", + expect="open: 'Close' appears, History 'Export' toolbar gone; " + "Close: 'Export' toolbar restored, 'Close' gone") + + +@and_test(expects=("nav_reach_history_export_dialog",)) +def test_reach_history_export_dialog(): + """History Export opens the 'Export History' modal; Cancel dismisses it.""" + restart_app() + h = and_reach_history(source=DASH_FAB) + opened = False + closed = False + if h: + n1 = ui() + trig = find_node(n1, content_desc=HIST_EXPORT) + if trig is not None: + before = and_showing(n1) + tap_node(trig) + and_enter("history_export_dialog") + after = and_showing() + # Title 'Export History' appears; the 'Help' toolbar icon vanishes. + opened = and_reach(before, after, target=EXPORT_DIALOG, source=HIST_HELP) + if opened: + n2 = ui() + cancel = row_trigger(n2, "Cancel") # app's Cancel (safe dismiss) + if cancel is not None: + b2 = and_showing(n2) + tap_node(cancel) + _dec_depth() # modal dismissed -> pop counter + a2 = and_showing() + closed = and_reach(b2, a2, target=HIST_HELP, source=EXPORT_DIALOG) + ok = opened and closed + record("nav_reach_history_export_dialog", ok, + "" if ok else "behavior_wrong: History Export dialog did not open " + "('Export History' absent / Help toolbar still present) or Cancel did " + "not restore History", + depth=1, jump_kind="reach", + expect="open: 'Export History' appears, History 'Help' toolbar gone; " + "Cancel: 'Help' toolbar restored, 'Export History' gone") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Remaining VLM budget: selected-tab highlight + History toolbar + Back-to-Dashboard +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("nav_history_tab_selected_vlm",)) +def test_history_tab_selected_vlm(): + """After switching to History, its bottom-nav item reads as selected.""" + restart_app() + ok = and_reach_history(source=DASH_FAB) + if not ok: + record("nav_history_tab_selected", False, + "setup_failed: never reached History for the VLM shot", + depth=1, jump_kind="reach", expect="on History") + vlm_assert("nav_history_tab_selected", + "In the bottom navigation bar, is the 'History' item visually " + "highlighted (its icon sits on a filled rounded pill) while the " + "other three items are not?", + RESULTS_DIR, tag="color") + + +@and_test(expects=("nav_history_toolbar_actions_vlm",)) +def test_history_toolbar_actions_vlm(): + """History renders two circular action icons at the TOP-RIGHT of its bar.""" + restart_app() + ok = and_reach_history(source=DASH_FAB) + if not ok: + record("nav_history_toolbar_actions", False, + "setup_failed: never reached History for the VLM shot", + depth=1, jump_kind="reach", expect="on History") + vlm_assert("nav_history_toolbar_actions", + "Are there exactly two circular icon buttons at the TOP-RIGHT of the " + "screen, level with a 'History' title on the left?", + RESULTS_DIR, tag="layout") + + +@and_test(expects=("nav_back_to_dashboard_endstate_vlm",)) +def test_back_to_dashboard_endstate_vlm(): + """After a BACK from the Settings tab, the Dashboard end-state is on screen: + the wrench FAB sits at the lower-right.""" + restart_app() + s = and_reach_settings(source=DASH_FAB) + landed = False + if s: + before = and_showing() + and_back() + after = and_showing() + landed = and_reach(before, after, target=DASH_FAB, source=SET_FOLLOW) + if not landed: + record("nav_back_to_dashboard_endstate", False, + "setup_failed: BACK did not land on Dashboard for the VLM shot", + depth=1, jump_kind="reach", expect="on Dashboard after BACK") + vlm_assert("nav_back_to_dashboard_endstate", + "Is a round floating action button showing a wrench icon rendered " + "near the BOTTOM-RIGHT of the screen?", + RESULTS_DIR, tag="position") + + +TESTS = [ + # top-level tab reachability + test_reach_dashboard_to_monitor, + test_reach_monitor_to_history, + test_reach_history_to_settings, + test_reach_settings_to_dashboard, + test_reach_dashboard_to_settings, + test_roundtrip_dashboard_settings_dashboard, + test_roundtrip_history_dashboard_history, + # depth-2 nested chains + back unwinding + test_reach_monitor_entry_settings, + test_reach_entry_settings_toolbar_vlm, + test_backstack_entry_settings_to_monitor, + test_reach_floating_window_settings, + test_reach_floating_toolbar_vlm, + test_backstack_floating_settings_to_monitor, + test_reach_about, + test_reach_about_toolbar_vlm, + test_backstack_about_to_settings, + test_backstack_deep_unwind_to_dashboard, + test_backstack_tab_back_to_dashboard, + # dialog reach + dismiss + test_reach_calibrate_dialog, + test_reach_history_help_dialog, + test_reach_history_export_dialog, + # remaining VLM budget + test_history_tab_selected_vlm, + test_history_toolbar_actions_vlm, + test_back_to_dashboard_endstate_vlm, +] + +if __name__ == "__main__": + run_suite(TESTS, "navigation") diff --git a/android/dijia1124-plusplusbattery/tests/test_android_states.py b/android/dijia1124-plusplusbattery/tests/test_android_states.py new file mode 100644 index 0000000000000000000000000000000000000000..2d51be9f2a030c0714caf3be19fceaa24d3e1ad1 --- /dev/null +++ b/android/dijia1124-plusplusbattery/tests/test_android_states.py @@ -0,0 +1,811 @@ +#!/usr/bin/env python3 +"""STATES lane — PlusPlusBattery (Jetpack Compose battery info viewer). + +This lane owns exactly ONE observation type: a widget's STATE observed through a +before/after interaction — `checked` / `enabled` / `selected` / `focused` +transitions PAIRED WITH the app-authored consequence, conditional enable/disable, +and SETTINGS/mode persistence across process death. It is the SOLE owner of the +`checked` attribute. A pixel-perfect dead shell (no state wiring) FAILS every case +here: every test taps/toggles/kills and then asserts a real transition, never mere +existence, never a framework-default attribute. + +All expected states below were read off the RUNNING original app before writing: + + * Calibrate dialog: 2 RadioButtons with EMPTY text (labels "Multiply"/"Divide" + are TextViews to the RIGHT and are NOT the tap target). The choice PERSISTS + across launches, so the test first RE-SELECTS Multiply to fix a known baseline + (Multiply.checked=true, Divide.checked=false), THEN taps the 2nd radio and + asserts the exclusive flip Divide->true AND Multiply->false, then restores + Multiply so re-runs / the computation lane see the default. + * Settings CustomSwitch = a `View` with checkable=true + a `checked` attr, EMPTY + text/desc — located by the y-row of its adjacent label TextView. Observed: + "Follow system theme" checked=true enabled=true + "Enable dark mode" checked=false enabled=FALSE (gated) + "Show floating button on dashboard" checked=true enabled=true + "Automatic daily charge cycle log" checked=false enabled=true + "Show OPlus exclusive entries" checked=true enabled=true + Toggling "Follow system theme" OFF flips "Enable dark mode" enabled false->true + (conditional enable/disable). With follow-system OFF, toggling "Enable dark + mode" ON darkens the whole theme (color — unreadable from XML -> the VLM cases). + * Monitor Entry Settings (depth 2 from Monitor): 9 CheckBoxes, all checked=true; + tapping one flips it to false, tapping again restores true. (The 'Monitor entry + settings' row label stays visible on the nested screen, so the surface change is + proven by the 'Monitor Entry Settings' TITLE appearing, not by the source + vanishing.) + * Floating Window Settings (depth 2 from Monitor): "Text stroke"/"Text shadow" + are checkable `View`s (checked=false -> true); "Enable touch" is checked=true + -> false. These rows sit near the bottom, so each is scrolled into view first. + * Show-FAB is a SETTINGS persistence + cross-surface consequence: toggling "Show + floating button on dashboard" OFF removes the Dashboard FAB (content-desc + "Open menu"); ON restores it. + * A Settings switch survives process death: toggle "Automatic daily charge cycle + log" ON, force_stop_and_relaunch(), the switch is STILL on. + +Each test opens its own entry via restart_app() and RESTORES every mutated switch / +radio to the observed default so later tests / other lanes see a clean app. +Root-gated controls ("Enable root mode", "Manage custom entries", "Experimental: +logcat"), sliders, and SAF import/export are deliberately untouched. +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 +import android_testgen_kit as _kit # for the private depth counter only + +RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else os.path.dirname(os.path.abspath(__file__)) + + +# ── content-descs / labels / titles observed on the running original ───────────── +CD_DASHBOARD = "Dashboard" +CD_MONITOR = "Monitor" +CD_SETTINGS = "Settings" +CD_CALIBRATE = "Calibrate" +CD_FAB = "Open menu" + +CAL_TITLE = "Calibrate via Multiplier" +CAL_CLOSE = "Close" + +LBL_MONITOR_ENTRY = "Monitor entry settings" +LBL_FLOATING = "Floating window settings" +TITLE_MONITOR_ENTRY = "Monitor Entry Settings" +TITLE_FLOATING = "Floating Window Settings" + +LBL_FOLLOW = "Follow system theme" +LBL_DARK = "Enable dark mode" +LBL_SHOWFAB = "Show floating button on dashboard" +LBL_DAILYLOG = "Automatic daily charge cycle log" +LBL_OPLUS = "Show OPlus exclusive entries" + +LBL_TEXT_STROKE = "Text stroke" +LBL_TEXT_SHADOW = "Text shadow" +LBL_ENABLE_TOUCH = "Enable touch" + + +# ══════════════════════════════════════════════════════════════════════════════ +# Small readers / locators +# ══════════════════════════════════════════════════════════════════════════════ + +def _dec_depth() -> int: + """Pop one surface from the kit's depth counter WITHOUT a hardware BACK — for a + dialog dismissed by its own Close affordance.""" + _kit._DEPTH = max(0, _kit._DEPTH - 1) + return _kit._DEPTH + + +def ready() -> bool: + """restart_app + wait; True once the app is foreground.""" + restart_app() + return wait_for_foreground() + + +def switch_near(nodes, label: str, max_dy: int = 90) -> dict | None: + """The CustomSwitch (checkable View) on the SAME y-row as `label`'s TextView. + CustomSwitches carry empty text/desc, so proximity to the label is the only + honest way to name them; the tight max_dy keeps adjacent rows from matching.""" + lab = find_node_ci(nodes, label) + if lab is None or "_center" not in lab: + return None + ly = lab["_center"][1] + best, best_dy = None, max_dy + 1 + for n in nodes: + if n.get("checkable") == "true" and "_center" in n: + dy = abs(n["_center"][1] - ly) + if dy < best_dy: + best, best_dy = n, dy + return best if best_dy <= max_dy else None + + +def radio_buttons(nodes=None) -> list: + nodes = ui() if nodes is None else nodes + return [n for n in nodes if n.get("class", "").endswith("RadioButton")] + + +def checkboxes(nodes=None) -> list: + nodes = ui() if nodes is None else nodes + return [n for n in nodes if n.get("class", "").endswith("CheckBox")] + + +# ══════════════════════════════════════════════════════════════════════════════ +# depth-family helpers — named and_enter_*/and_reach_* so the depth auditor counts +# the declared depth as backed by a real navigation call. Each CONFIRMS the target +# surface's own element appeared (a real surface change) before counting a surface. +# (and_reach_surface is not used because these list-backed screens keep the tapped +# row's label visible, so the "source vanished" half of a strict reach never holds; +# the assertion these back is a state TRANSITION, not the reach itself.) +# ══════════════════════════════════════════════════════════════════════════════ + +def and_enter_settings() -> bool: + """Dashboard -> Settings tab (depth 1). Confirms a Settings-only switch label + appeared, then counts one surface.""" + trig = find_node(ui(), content_desc=CD_SETTINGS) + if trig is None or not tap_node(trig): + return False + if find_node_ci(ui(), LBL_FOLLOW) is None: + return False + and_enter("settings") + return True + + +def and_enter_monitor() -> bool: + """Dashboard -> Monitor tab (depth 1). Confirms the 'Monitor entry settings' + row appeared, then counts one surface.""" + trig = find_node(ui(), content_desc=CD_MONITOR) + if trig is None or not tap_node(trig): + return False + if find_node_ci(ui(), LBL_MONITOR_ENTRY) is None: + return False + and_enter("monitor") + return True + + +def and_enter_calibrate() -> bool: + """Dashboard -> Calibrate dialog (depth 1). Confirms the dialog title appeared, + then counts one surface.""" + trig = find_node(ui(), content_desc=CD_CALIBRATE) + if trig is None or not tap_node(trig): + return False + if find_node(ui(), text=CAL_TITLE) is None: + return False + and_enter("calibrate_dialog") + return True + + +def and_reach_monitor_entry() -> bool: + """Monitor -> Monitor Entry Settings (depth 2). Taps the 'Monitor entry + settings' row and confirms the 'Monitor Entry Settings' TITLE appeared (a new + surface), then counts one surface.""" + n = find_node_ci(ui(), LBL_MONITOR_ENTRY) + if n is None or not tap_node(n): + return False + if find_node_ci(ui(), TITLE_MONITOR_ENTRY) is None: + return False + and_enter("monitor_entry_settings") + return True + + +def and_reach_floating() -> bool: + """Monitor -> Floating Window Settings (depth 2). Taps the 'Floating window + settings' row and confirms the 'Floating Window Settings' TITLE appeared (a new + surface), then counts one surface.""" + n = find_node_ci(ui(), LBL_FLOATING) + if n is None or not tap_node(n): + return False + if find_node_ci(ui(), TITLE_FLOATING) is None: + return False + and_enter("floating_window_settings") + return True + + +def reach_floating_switch(label: str) -> dict | None: + """Scroll the floating-window row `label` into view (its switch sits low on the + page and is otherwise below the fold), then return the switch on its y-row.""" + scroll_into_view(label) + scroll_down(0.3) + return switch_near(ui(), label) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 1) Multiply/Divide radio — SOLE CHECKED owner. From a Multiply baseline, tapping +# the 2nd RadioButton (Divide) flips Divide.checked false->true AND +# Multiply.checked true->false (radio-group exclusivity is the app-authored +# consequence). depth 1 (dialog). +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_radio_divide", "states_radio_divide_vlm")) +def test_radio_divide_selects_and_deselects(): + if not ready(): + record("states_radio_divide", False, + "setup_failed: app did not reach foreground", + depth=1, jump_kind="transition", + expect="Divide checked false->true, Multiply true->false") + return + if find_node(ui(), content_desc=CD_CALIBRATE) is None: + record("states_radio_divide", False, + "feature_missing: no 'Calibrate' control on the Battery Current card", + depth=1, jump_kind="transition", + expect="Divide checked false->true, Multiply true->false") + return + if not and_enter_calibrate(): + record("states_radio_divide", False, + "setup_failed: Calibrate dialog did not open", + depth=1, jump_kind="transition", + expect="Divide checked false->true, Multiply true->false") + return + rb = radio_buttons() + if len(rb) < 2: + record("states_radio_divide", False, + f"feature_missing: expected 2 RadioButtons, saw {len(rb)}", + depth=1, jump_kind="transition", + expect="Divide checked false->true, Multiply true->false") + _dec_depth() + return + # The Multiply/Divide choice PERSISTS across launches, so the dialog need not + # open on Multiply. Establish a known baseline: tap the 1st radio (Multiply) and + # confirm Multiply=true/Divide=false — THAT is the before-state we assert from. + tap_node(rb[0]) + rb_base = radio_buttons() + mul_before = rb_base[0].get("checked") if len(rb_base) >= 1 else None + div_before = rb_base[1].get("checked") if len(rb_base) >= 2 else None + tap_node(rb_base[1] if len(rb_base) >= 2 else rb[1]) # tap Divide (2nd radio) + rb2 = radio_buttons() + mul_after = rb2[0].get("checked") if len(rb2) >= 1 else None + div_after = rb2[1].get("checked") if len(rb2) >= 2 else None + ok = (mul_before == "true" and div_before == "false" + and div_after == "true" and mul_after == "false") + record("states_radio_divide", ok, + "" if ok else + f"behavior_wrong: from Multiply-selected, tapping Divide should set " + f"Divide checked and clear Multiply; saw before(m={mul_before}," + f"d={div_before}) after(m={mul_after},d={div_after})", + depth=1, jump_kind="transition", + expect="Divide checked=true, Multiply checked=false after tapping Divide") + # VLM (shape): the selected radio (Divide, the RIGHT one) shows the FILLED dot. + vlm_assert("states_radio_divide", + "In this dialog there are two radio buttons in a row labelled " + "'Multiply' (left) and 'Divide' (right). Is the RIGHT radio button " + "(next to 'Divide') the one that is filled (a solid dot inside its " + "ring), while the left one is an empty ring?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="shape") + # RESTORE: re-select Multiply so the persisted default is clean for re-runs and + # other lanes, then Close the dialog (Close does not change the multiplier). + rb_r = radio_buttons() + if len(rb_r) >= 1 and rb_r[0].get("checked") == "false": + tap_node(rb_r[0]) + c = find_node(ui(), text=CAL_CLOSE) + if c: + tap_node(c) + _dec_depth() + + +# ══════════════════════════════════════════════════════════════════════════════ +# 2) Follow-system -> Enable-dark-mode ENABLE dependency (conditional enable). With +# "Follow system theme" ON, "Enable dark mode" is enabled=false; toggling +# follow-system OFF flips it enabled false->true. depth 1 (Settings). Restore ON. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_dark_enable_dependency", "states_dark_enable_dependency_vlm")) +def test_follow_system_gates_dark_mode(): + if not ready(): + record("states_dark_enable_dependency", False, + "setup_failed: app did not reach foreground", + depth=1, jump_kind="transition", + expect="Enable-dark-mode enabled false->true when Follow-system OFF") + return + if not and_enter_settings(): + record("states_dark_enable_dependency", False, + "setup_failed: Settings tab did not open", + depth=1, jump_kind="transition", + expect="Enable-dark-mode enabled false->true when Follow-system OFF") + return + nodes = ui() + fs = switch_near(nodes, LBL_FOLLOW) + dm = switch_near(nodes, LBL_DARK) + if fs is None or dm is None: + record("states_dark_enable_dependency", False, + "feature_missing: 'Follow system theme' or 'Enable dark mode' switch not found", + depth=1, jump_kind="transition", + expect="Enable-dark-mode enabled false->true when Follow-system OFF") + return + follow_before = fs.get("checked") + dark_enabled_before = dm.get("enabled") + tap_node(fs) # follow-system OFF + fresh = ui() + fs2 = switch_near(fresh, LBL_FOLLOW) + dm2 = switch_near(fresh, LBL_DARK) + follow_after = fs2.get("checked") if fs2 else None + dark_enabled_after = dm2.get("enabled") if dm2 else None + ok = (follow_before == "true" and dark_enabled_before == "false" + and follow_after == "false" and dark_enabled_after == "true") + record("states_dark_enable_dependency", ok, + "" if ok else + f"behavior_wrong: follow-system OFF should enable 'Enable dark mode'; " + f"saw follow {follow_before}->{follow_after}, dark.enabled " + f"{dark_enabled_before}->{dark_enabled_after}", + depth=1, jump_kind="transition", + expect="Enable-dark-mode enabled=true and Follow-system checked=false") + # Restore follow-system ON so the dark switch is disabled again for the VLM shot. + fs3 = switch_near(ui(), LBL_FOLLOW) + if fs3 and fs3.get("checked") == "false": + tap_node(fs3) + # VLM (color): with follow-system ON, the 'Enable dark mode' switch is dimmed. + vlm_assert("states_dark_enable_dependency", + "This is a settings screen with a 'Follow system theme' toggle " + "(which is ON) directly above an 'Enable dark mode' row. Does the " + "'Enable dark mode' switch look greyed-out / dimmed / disabled " + "(faded compared with the toggles above it)?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="color") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 3) Dark mode ON -> theme darkens. With follow-system OFF, toggle "Enable dark +# mode" ON: checked false->true AND the whole theme goes dark (color, unreadable +# from XML -> the flagship VLM + a paired light baseline). depth 1. Restore. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_dark_mode_toggle", + "states_dark_mode_light_baseline_vlm", + "states_dark_mode_dark_vlm")) +def test_dark_mode_darkens_theme(): + if not ready(): + for nm, tag in (("states_dark_mode_light_baseline", "color"), + ("states_dark_mode_dark", "color")): + record(nm + "_vlm", False, "setup_failed: app did not reach foreground", + depth=1, jump_kind="transition", tag=tag) + record("states_dark_mode_toggle", False, + "setup_failed: app did not reach foreground", + depth=1, jump_kind="transition", + expect="Enable-dark-mode checked false->true; theme dark") + return + if not and_enter_settings(): + for nm, tag in (("states_dark_mode_light_baseline", "color"), + ("states_dark_mode_dark", "color")): + record(nm + "_vlm", False, "setup_failed: Settings tab did not open", + depth=1, jump_kind="transition", tag=tag) + record("states_dark_mode_toggle", False, + "setup_failed: Settings tab did not open", + depth=1, jump_kind="transition", + expect="Enable-dark-mode checked false->true; theme dark") + return + # PAIRED baseline VLM: before enabling dark mode the theme is light. + vlm_assert("states_dark_mode_light_baseline", + "Is this screen's background light/white (a light theme) with dark " + "text?", RESULTS_DIR, depth=1, jump_kind="transition", tag="color") + fs = switch_near(ui(), LBL_FOLLOW) + if fs is None: + record("states_dark_mode_dark_vlm", False, + "setup_failed: 'Follow system theme' switch not found", + depth=1, jump_kind="transition", tag="color") + record("states_dark_mode_toggle", False, + "feature_missing: 'Follow system theme' switch not found", + depth=1, jump_kind="transition", + expect="Enable-dark-mode checked false->true; theme dark") + return + if fs.get("checked") == "true": + tap_node(fs) # follow-system OFF -> dark enabled + dm = switch_near(ui(), LBL_DARK) + if dm is None or dm.get("enabled") != "true": + record("states_dark_mode_dark_vlm", False, + "setup_failed: 'Enable dark mode' switch not enabled after follow OFF", + depth=1, jump_kind="transition", tag="color") + record("states_dark_mode_toggle", False, + "setup_failed: 'Enable dark mode' did not become enabled", + depth=1, jump_kind="transition", + expect="Enable-dark-mode checked false->true; theme dark") + fsr = switch_near(ui(), LBL_FOLLOW) + if fsr and fsr.get("checked") == "false": + tap_node(fsr) + return + dark_before = dm.get("checked") + tap_node(dm) # enable dark mode + fresh = ui() + dm2 = switch_near(fresh, LBL_DARK) + dark_after = dm2.get("checked") if dm2 else None + ok = dark_before == "false" and dark_after == "true" + record("states_dark_mode_toggle", ok, + "" if ok else + f"behavior_wrong: 'Enable dark mode' checked should flip false->true; " + f"saw {dark_before}->{dark_after}", + depth=1, jump_kind="transition", + expect="Enable-dark-mode checked=true; theme visibly dark") + # FLAGSHIP VLM (color): the whole app is now dark. + vlm_assert("states_dark_mode_dark", + "Is this app's background dark / near-black (a dark theme is active) " + "with light-coloured text?", + RESULTS_DIR, depth=1, jump_kind="transition", tag="color") + # RESTORE: dark OFF, then follow-system back ON. + dmr = switch_near(ui(), LBL_DARK) + if dmr and dmr.get("checked") == "true": + tap_node(dmr) + fsr = switch_near(ui(), LBL_FOLLOW) + if fsr and fsr.get("checked") == "false": + tap_node(fsr) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 4) Monitor entry checkbox — 9 CheckBoxes all checked=true; tapping one flips it +# checked true->false, tapping again restores true. depth 2 (Monitor -> Entry). +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_monitor_checkbox", "states_monitor_checkbox_vlm")) +def test_monitor_entry_checkbox_toggles(): + if not ready(): + record("states_monitor_checkbox_vlm", False, + "setup_failed: app did not reach foreground", + depth=2, jump_kind="transition", tag="shape") + record("states_monitor_checkbox", False, + "setup_failed: app did not reach foreground", + depth=2, jump_kind="transition", + expect="a Monitor-entry CheckBox checked true->false->true") + return + if not and_enter_monitor(): + record("states_monitor_checkbox_vlm", False, + "setup_failed: Monitor tab did not open", + depth=2, jump_kind="transition", tag="shape") + record("states_monitor_checkbox", False, + "setup_failed: Monitor tab did not open", + depth=2, jump_kind="transition", + expect="a Monitor-entry CheckBox checked true->false->true") + return + if not and_reach_monitor_entry(): + record("states_monitor_checkbox_vlm", False, + "setup_failed: could not reach Monitor Entry Settings", + depth=2, jump_kind="transition", tag="shape") + record("states_monitor_checkbox", False, + "setup_failed: could not reach Monitor Entry Settings", + depth=2, jump_kind="transition", + expect="a Monitor-entry CheckBox checked true->false->true") + return + cbs = checkboxes() + if len(cbs) < 9: + record("states_monitor_checkbox_vlm", False, + f"setup_failed: expected 9 CheckBoxes, saw {len(cbs)}", + depth=2, jump_kind="transition", tag="shape") + record("states_monitor_checkbox", False, + f"feature_missing: expected 9 CheckBoxes, saw {len(cbs)}", + depth=2, jump_kind="transition", + expect="a Monitor-entry CheckBox checked true->false->true") + return + target = cbs[0] + before = target.get("checked") + tap_node(target) + after = (find_closest_match(ui(), target) or {}).get("checked") + # VLM (shape): the toggled row's checkbox now reads unchecked/empty. + vlm_assert("states_monitor_checkbox", + "This screen lists battery entries each with a checkbox on the left. " + "Is the checkbox next to 'Battery Level' (the first row) an EMPTY " + "square with NO tick/checkmark inside it?", + RESULTS_DIR, depth=2, jump_kind="transition", tag="shape") + # tap again -> restore true (also the second half of the transition proof) + again = find_closest_match(ui(), target) or target + tap_node(again) + restored = (find_closest_match(ui(), target) or {}).get("checked") + ok = before == "true" and after == "false" and restored == "true" + record("states_monitor_checkbox", ok, + "" if ok else + f"behavior_wrong: a CheckBox should toggle true->false->true; " + f"saw before={before} after={after} restored={restored}", + depth=2, jump_kind="transition", + expect="CheckBox checked true->false then back to true") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 5-7) Floating Window switches (depth 2). Text stroke / Text shadow are checkable +# Views (checked false->true); Enable touch is checked true->false. Each row is +# scrolled into view first. Restore each. +# ══════════════════════════════════════════════════════════════════════════════ + +def _floating_switch_case(name: str, label: str, expect_from: str, extra_vlm=None): + expect_to = "true" if expect_from == "false" else "false" + exp = f"'{label}' checked {expect_from}->{expect_to}" + if not ready(): + if extra_vlm: + extra_vlm(reached=False) + record(name, False, "setup_failed: app did not reach foreground", + depth=2, jump_kind="transition", expect=exp) + return + if not and_enter_monitor(): + if extra_vlm: + extra_vlm(reached=False) + record(name, False, "setup_failed: Monitor tab did not open", + depth=2, jump_kind="transition", expect=exp) + return + if not and_reach_floating(): + if extra_vlm: + extra_vlm(reached=False) + record(name, False, "setup_failed: could not reach Floating Window Settings", + depth=2, jump_kind="transition", expect=exp) + return + if extra_vlm: + extra_vlm(reached=True) # screenshot the rendered screen + sw = reach_floating_switch(label) + if sw is None: + record(name, False, f"feature_missing: '{label}' switch not found", + depth=2, jump_kind="transition", expect=exp) + return + # Floating-window prefs PERSIST across launches, so this switch may not start at + # the documented default. Normalize it to `expect_from` first (this is setup, + # not the assertion), then perform and assert the real toggle from that baseline. + if sw.get("checked") != expect_from: + tap_node(sw) + sw = reach_floating_switch(label) or sw + before = sw.get("checked") + tap_node(sw) + after = (switch_near(ui(), label) or {}).get("checked") + ok = before == expect_from and after == expect_to + record(name, ok, + "" if ok else + f"behavior_wrong: '{label}' should toggle {expect_from}->{expect_to}; " + f"saw before={before} after={after}", + depth=2, jump_kind="transition", expect=exp) + # restore + sw_r = switch_near(ui(), label) + if sw_r and sw_r.get("checked") != expect_from: + tap_node(sw_r) + + +@and_test(expects=("states_floating_text_stroke",)) +def test_floating_text_stroke_toggles(): + _floating_switch_case("states_floating_text_stroke", LBL_TEXT_STROKE, "false") + + +@and_test(expects=("states_floating_text_shadow", "states_floating_text_shadow_vlm")) +def test_floating_text_shadow_toggles(): + def _vlm(reached): + if not reached: + record("states_floating_text_shadow_vlm", False, + "setup_failed: Floating Window Settings not reached", + depth=2, jump_kind="transition", tag="layout") + return + # VLM (layout): the Floating Window Settings screen renders its controls — + # a labelled toggle row (e.g. 'Text stroke'/'Text shadow'/'Enable touch') is + # visibly present, i.e. the screen is not blank. + vlm_assert("states_floating_text_shadow", + "Does this screen show a settings toggle/switch on the right-hand " + "side of a labelled row (for example a row labelled 'Text shadow' " + "or 'Enable touch') — i.e. it renders real controls, not a blank " + "screen?", RESULTS_DIR, expect="YES", depth=2, + jump_kind="transition", tag="layout") + _floating_switch_case("states_floating_text_shadow", LBL_TEXT_SHADOW, "false", + extra_vlm=_vlm) + + +@and_test(expects=("states_floating_enable_touch",)) +def test_floating_enable_touch_toggles(): + _floating_switch_case("states_floating_enable_touch", LBL_ENABLE_TOUCH, "true") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 8-10) Settings switches toggle (depth 1). Automatic daily log (off->on), +# OPlus fields (on->off), Show-FAB (on->off). Each asserts its checked flip and +# restores. The daily-log case carries the "ON = coloured track" VLM. +# ══════════════════════════════════════════════════════════════════════════════ + +def _settings_switch_case(name: str, label: str, expect_from: str, extra_vlm=None): + expect_to = "true" if expect_from == "false" else "false" + exp = f"'{label}' checked {expect_from}->{expect_to}" + if not ready(): + if extra_vlm: + extra_vlm(flipped=False) + record(name, False, "setup_failed: app did not reach foreground", + depth=1, jump_kind="transition", expect=exp) + return + if not and_enter_settings(): + if extra_vlm: + extra_vlm(flipped=False) + record(name, False, "setup_failed: Settings tab did not open", + depth=1, jump_kind="transition", expect=exp) + return + sw = switch_near(ui(), label) + if sw is None: + if extra_vlm: + extra_vlm(flipped=False) + record(name, False, f"feature_missing: '{label}' switch not found", + depth=1, jump_kind="transition", expect=exp) + return + # Settings switches PERSIST across launches, so normalize this switch to + # `expect_from` first (setup, not the assertion), then toggle and assert. + if sw.get("checked") != expect_from: + tap_node(sw) + sw = switch_near(ui(), label) or sw + before = sw.get("checked") + tap_node(sw) + after = (switch_near(ui(), label) or {}).get("checked") + ok = before == expect_from and after == expect_to + record(name, ok, + "" if ok else + f"behavior_wrong: '{label}' should toggle {expect_from}->{expect_to}; " + f"saw before={before} after={after}", + depth=1, jump_kind="transition", expect=exp) + if extra_vlm: + extra_vlm(flipped=ok) # screenshot with the switch flipped + # restore + sw_r = switch_near(ui(), label) + if sw_r and sw_r.get("checked") != expect_from: + tap_node(sw_r) + + +@and_test(expects=("states_daily_log_toggle", "states_daily_log_toggle_vlm")) +def test_daily_log_switch_toggles(): + def _vlm(flipped): + if not flipped: + record("states_daily_log_toggle_vlm", False, + "setup_failed: daily-log switch was not flipped ON", + depth=1, jump_kind="transition", tag="color") + return + # VLM (color): a switch just turned ON shows a coloured/filled track with the + # thumb to the right — ask about the 'Automatic daily charge cycle log' row. + vlm_assert("states_daily_log_toggle", + "On this settings screen, is the switch on the " + "'Automatic daily charge cycle log' row turned ON — its track " + "filled with an accent colour and its thumb pushed to the RIGHT?", + RESULTS_DIR, expect="YES", depth=1, jump_kind="transition", + tag="color") + _settings_switch_case("states_daily_log_toggle", LBL_DAILYLOG, "false", extra_vlm=_vlm) + + +@and_test(expects=("states_oplus_toggle",)) +def test_oplus_switch_toggles(): + _settings_switch_case("states_oplus_toggle", LBL_OPLUS, "true") + + +@and_test(expects=("states_showfab_toggle",)) +def test_showfab_switch_toggles(): + _settings_switch_case("states_showfab_toggle", LBL_SHOWFAB, "true") + + +# ══════════════════════════════════════════════════════════════════════════════ +# 11) Show-FAB persistence + CROSS-SURFACE consequence (depth 1). Toggle "Show +# floating button on dashboard" OFF -> the Dashboard FAB (content-desc +# "Open menu") DISAPPEARS; toggle ON -> reappears. Restore ON. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_showfab_consequence", "states_showfab_consequence_vlm")) +def test_showfab_hides_dashboard_fab(): + exp = "Dashboard FAB 'Open menu' present->absent when Show-FAB OFF, back on restore" + if not ready(): + record("states_showfab_consequence_vlm", False, + "setup_failed: app did not reach foreground", + depth=1, jump_kind="transition", tag="layout") + record("states_showfab_consequence", False, + "setup_failed: app did not reach foreground", + depth=1, jump_kind="transition", expect=exp) + return + fab_before = find_node(ui(), content_desc=CD_FAB) is not None + if not and_enter_settings(): + record("states_showfab_consequence_vlm", False, + "setup_failed: Settings tab did not open", + depth=1, jump_kind="transition", tag="layout") + record("states_showfab_consequence", False, + "setup_failed: Settings tab did not open", + depth=1, jump_kind="transition", expect=exp) + return + sw = switch_near(ui(), LBL_SHOWFAB) + if sw is None: + record("states_showfab_consequence_vlm", False, + f"setup_failed: '{LBL_SHOWFAB}' switch not found", + depth=1, jump_kind="transition", tag="layout") + record("states_showfab_consequence", False, + f"feature_missing: '{LBL_SHOWFAB}' switch not found", + depth=1, jump_kind="transition", expect=exp) + return + # Show-FAB persists, so normalize it ON first (setup), re-derive the Dashboard + # baseline, THEN toggle OFF and assert the FAB disappears. + if sw.get("checked") != "true": + tap_node(sw) + dash0 = find_node(ui(), content_desc=CD_DASHBOARD) + if dash0: + tap_node(dash0) + fab_before = find_node(ui(), content_desc=CD_FAB) is not None + if not and_enter_settings(): + record("states_showfab_consequence_vlm", False, + "setup_failed: Settings tab did not reopen after normalize", + depth=1, jump_kind="transition", tag="layout") + record("states_showfab_consequence", False, + "setup_failed: Settings tab did not reopen after normalize", + depth=1, jump_kind="transition", expect=exp) + return + sw = switch_near(ui(), LBL_SHOWFAB) or sw + tap_node(sw) # Show-FAB OFF + # back to Dashboard and check the FAB is gone + dash = find_node(ui(), content_desc=CD_DASHBOARD) + if dash: + tap_node(dash) + fab_off = find_node(ui(), content_desc=CD_FAB) is not None + # VLM (layout): the FAB is absent from the dashboard now. + vlm_assert("states_showfab_consequence", + "Is there a round floating action button in the bottom-right corner " + "of this dashboard screen?", + RESULTS_DIR, expect="NO", depth=1, jump_kind="transition", tag="layout") + # toggle back ON and confirm it reappears + if and_enter_settings(): + sw_on = switch_near(ui(), LBL_SHOWFAB) + if sw_on and sw_on.get("checked") == "false": + tap_node(sw_on) + dash2 = find_node(ui(), content_desc=CD_DASHBOARD) + if dash2: + tap_node(dash2) + fab_on = find_node(ui(), content_desc=CD_FAB) is not None + ok = fab_before and (not fab_off) and fab_on + record("states_showfab_consequence", ok, + "" if ok else + f"behavior_wrong: Show-FAB OFF should hide the Dashboard FAB and ON " + f"restore it; saw present_before={fab_before} present_off={fab_off} " + f"present_on={fab_on}", + depth=1, jump_kind="transition", expect=exp) + + +# ══════════════════════════════════════════════════════════════════════════════ +# 12) SETTINGS persistence across process death (depth 1). Toggle "Automatic daily +# charge cycle log" ON, force_stop_and_relaunch(), and assert the switch is +# STILL ON in the fresh process. Restore OFF. An in-memory-only recreation fails. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("states_setting_persists_process_death",)) +def test_setting_survives_process_death(): + exp = "'Automatic daily charge cycle log' checked=true survives force-stop+relaunch" + if not ready(): + record("states_setting_persists_process_death", False, + "setup_failed: app did not reach foreground", + depth=1, jump_kind="transition", expect=exp) + return + if not and_enter_settings(): + record("states_setting_persists_process_death", False, + "setup_failed: Settings tab did not open", + depth=1, jump_kind="transition", expect=exp) + return + sw = switch_near(ui(), LBL_DAILYLOG) + if sw is None: + record("states_setting_persists_process_death", False, + f"feature_missing: '{LBL_DAILYLOG}' switch not found", + depth=1, jump_kind="transition", expect=exp) + return + # Normalize the switch OFF first (its persisted state may differ), so the + # persistence assertion always starts from a known OFF baseline. + if sw.get("checked") != "false": + tap_node(sw) + sw = switch_near(ui(), LBL_DAILYLOG) or sw + before = sw.get("checked") + if before != "false": + record("states_setting_persists_process_death", False, + f"setup_failed: could not set '{LBL_DAILYLOG}' OFF at start, saw {before}", + depth=1, jump_kind="transition", expect=exp) + return + tap_node(sw) # ON + toggled = (switch_near(ui(), LBL_DAILYLOG) or {}).get("checked") + # process death + force_stop_and_relaunch() + wait_for_foreground() + and_reset_depth() + reopened = and_enter_settings() + persisted = (switch_near(ui(), LBL_DAILYLOG) or {}).get("checked") if reopened else None + ok = toggled == "true" and reopened and persisted == "true" + record("states_setting_persists_process_death", ok, + "" if ok else + f"behavior_wrong: the toggled-ON setting should survive process death; " + f"saw toggled={toggled} reopened={reopened} persisted={persisted}", + depth=1, jump_kind="transition", expect=exp) + # restore OFF + sw_r = switch_near(ui(), LBL_DAILYLOG) + if sw_r and sw_r.get("checked") == "true": + tap_node(sw_r) + + +TESTS = [ + test_radio_divide_selects_and_deselects, # depth 1 + VLM (shape) + test_follow_system_gates_dark_mode, # depth 1 + VLM (color) + test_dark_mode_darkens_theme, # depth 1 + 2 VLM (color x2) + test_monitor_entry_checkbox_toggles, # depth 2 + VLM (shape) + test_floating_text_stroke_toggles, # depth 2 + test_floating_text_shadow_toggles, # depth 2 + VLM (layout) + test_floating_enable_touch_toggles, # depth 2 + test_daily_log_switch_toggles, # depth 1 + VLM (color) + test_oplus_switch_toggles, # depth 1 + test_showfab_switch_toggles, # depth 1 + test_showfab_hides_dashboard_fab, # depth 1 + VLM (layout) + test_setting_survives_process_death, # depth 1 +] + + +if __name__ == "__main__": + run_suite(TESTS, "states") diff --git a/android/dijia1124-plusplusbattery/tests/test_android_structure.py b/android/dijia1124-plusplusbattery/tests/test_android_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..4635532fc58ed6d47448d9b008ef6519820fc8cd --- /dev/null +++ b/android/dijia1124-plusplusbattery/tests/test_android_structure.py @@ -0,0 +1,599 @@ +#!/usr/bin/env python3 +"""STRUCTURE lane — PlusPlusBattery (Jetpack Compose, single Activity). + +Owns exactly two things: + (1) the GATE: the app launches to the Dashboard with its top-level surfaces + present (main container, title, 4-item bottom-nav host). jump_kind="none". + (2) tree-SHAPE deltas: an interaction that changes the view tree's SHAPE — a + dialog adds a modal window layer (node count / a widget CLASS appears), + the FAB expand/collapse re-shapes the overlay, a tab renders a distinct + subtree (a class of checkable View that the Dashboard card list lacks), + a deep surface exposes a column of CheckBox / a row of SeekBar widgets. + Each is recorded as jump_kind="transition" and REVERSED to prove it restores. + +CEDES to other lanes: content strings (text), checked/enabled/selected (states), +reachability of a named screen (navigation), computed values (computation), +CRUD on records (interaction). This file asserts SHAPE only. + +All observed values below were read off the running original with uiautomator. +""" +import os, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 + +RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else os.path.dirname(os.path.abspath(__file__)) + +# Bottom-nav sibling tabs (content-desc on every surface except the selected one, +# which renders as a plain text label instead). +NAV_SIBLINGS = ("Monitor", "History", "Settings") + + +# ── depth-family helpers (named and_enter_* so the depth auditor accepts the +# declared depth>=1 as BACKED navigation, per the kit's DEPTH_FWD_RE). Each taps a +# real user-path trigger, confirms the surface actually changed, then increments +# the kit depth counter via the kit's and_enter(). ───────────────────────────── + +def and_enter_dialog(nodes, *, text="", content_desc="", info_near="") -> tuple[bool, set]: + """Open a dialog from a trigger and confirm the surface re-shaped. Returns + (opened, before_showing). Counts one surface. `info_near` disambiguates a + duplicate 'Show Info' button by the y-row of the given label.""" + trig = None + if info_near: + trig = _info_near(nodes, info_near) + elif text: + trig = find_node(nodes, text=text) or find_node_ci(nodes, text) + elif content_desc: + trig = find_node(nodes, content_desc=content_desc) + if trig is None: + return False, set() + before = and_showing(nodes) + if not tap_node(trig): + return False, before + after = and_showing() + if not surface_changed(before, after): + return False, before + and_enter("dialog") + return True, before + + +def and_enter_tab(nodes, content_desc: str) -> tuple[bool, set]: + """Tap a bottom-nav tab and confirm its subtree replaced the current one. + Counts one surface. Returns (ok, before_showing).""" + trig = find_node(nodes, content_desc=content_desc) + if trig is None: + return False, set() + before = and_showing(nodes) + if not tap_node(trig): + return False, before + after = and_showing() + if not surface_changed(before, after): + return False, before + and_enter(content_desc) + return True, before + + +def and_enter_deep(nodes, *, text: str) -> tuple[bool, set]: + """From a tab, open a nested settings surface (Monitor entry settings / + Floating window settings / About). Counts one MORE surface (depth 2).""" + trig = find_node(nodes, text=text) or find_node_ci(nodes, text) + if trig is None: + return False, set() + before = and_showing(nodes) + if not tap_node(trig): + return False, before + after = and_showing() + if not surface_changed(before, after): + return False, before + and_enter(text) + return True, before + + +def _info_near(nodes, label: str) -> dict | None: + """The 'Show Info' button closest in y to `label` (the content-desc repeats + across cards, so proximity is the only honest disambiguator).""" + ln = find_node(nodes, text=label) or find_node_ci(nodes, label) + if not ln or "_center" not in ln: + return None + infos = find_nodes(nodes, content_desc="Show Info") + infos = [n for n in infos if "_center" in n] + if not infos: + return None + return min(infos, key=lambda n: abs(n["_center"][1] - ln["_center"][1])) + + +def _count_checkable(nodes) -> int: + return len([n for n in nodes if n.get("checkable") == "true"]) + + +# ══════════════════════════════════════════════════════════════════════════════ +# (1) THE GATE — top-level surfaces exist. jump_kind="none", depth=0. +# Kept to 3 of 18 tests (17%), under the 30% existence ceiling. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_gate_launch", "structure_gate_launch_vlm")) +def test_gate_launch(): + restart_app() + fg = wait_for_foreground() + nodes = ui() + # Main container present: a Compose host FrameLayout/View tree with the + # dashboard's card TextViews rendered inside it. + container = bool(find_by_class(nodes, "FrameLayout")) and bool(find_by_class(nodes, "View")) + cards = len(find_by_class(nodes, "TextView")) + ok = bool(fg) and container and cards >= 15 + record("structure_gate_launch", ok, + "" if ok else f"setup_failed: app did not reach a populated foreground " + f"(fg={fg}, container={container}, textviews={cards})", + depth=0, jump_kind="none") + vlm_assert("structure_gate_launch", + "Does this screen show a vertical list of battery-info cards with a " + "bottom navigation bar containing exactly 4 icons evenly spaced across " + "the bottom edge?", + RESULTS_DIR, tag="shape") + + +@and_test(expects=("structure_gate_navhost",)) +def test_gate_navhost(): + restart_app() + wait_for_foreground() + nodes = ui() + # 4-item nav host: 3 sibling tabs by content-desc + the selected "Dashboard" + # label as text (the selected item renders its label instead of a desc). + siblings = [cd for cd in NAV_SIBLINGS if find_node(nodes, content_desc=cd)] + selected = bool(find_node(nodes, text="Dashboard")) + ok = len(siblings) == 3 and selected + record("structure_gate_navhost", ok, + "" if ok else f"feature_missing: bottom-nav host incomplete " + f"(siblings={siblings}, dashboard_label={selected})", + depth=0, jump_kind="none") + + +@and_test(expects=("structure_gate_title_and_cards",)) +def test_gate_title_and_cards(): + restart_app() + wait_for_foreground() + nodes = ui() + # App title present as the top TextView, and the dashboard exposes a stack of + # value Buttons (info/swap/calibrate/expand affordances) — its shape signature. + title = bool(find_node(nodes, text="Plus Plus Battery")) + buttons = len(find_by_class(nodes, "Button")) + ok = title and buttons == 8 + record("structure_gate_title_and_cards", ok, + "" if ok else f"feature_missing: dashboard shape wrong " + f"(title={title}, buttons={buttons}, expected 8)", + depth=0, jump_kind="none") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (2) DIALOG SHAPE DELTAS — a dialog adds a modal window layer. depth=1. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_calibrate_dialog_shape", "structure_calibrate_dialog_shape_vlm")) +def test_calibrate_dialog_shape(): + restart_app() + wait_for_foreground() + nodes = ui() + before_rb = len(find_by_class(nodes, "RadioButton")) # 0 on dashboard + opened, before = and_enter_dialog(nodes, content_desc="Calibrate") + dlg = ui() + after_rb = len(find_by_class(dlg, "RadioButton")) # 2 in the dialog + grew = opened and after_rb == before_rb + 2 and surface_changed(before, and_showing(dlg)) + # Ask the VLM WHILE the dialog is still on screen — a rendered modal-overlay + # property the tree cannot express. (Fired here, not after Close, so the + # screenshot actually contains the dialog.) + settle("tap") + vlm_assert("structure_calibrate_dialog_shape", + "Is there a rounded dialog box floating on top of the screen, with the " + "app content behind it faded or greyed out?", + RESULTS_DIR, tag="position") + # reverse: Close removes the RadioButton subtree + restored = False + if opened: + close = find_node(dlg, text="Close") + if close and tap_node(close): # DANGEROUS word -> tap_node, not safe_tap + restored = len(find_by_class(ui(), "RadioButton")) == before_rb + ok = grew and restored + record("structure_calibrate_dialog_shape", ok, + "" if ok else f"behavior_wrong: calibrate dialog RadioButton delta wrong " + f"(before={before_rb}, after={after_rb}, restored={restored})", + depth=1, jump_kind="transition", + expect="RadioButton class 0->2 when Calibrate opens, back to 0 on Close") + + +@and_test(expects=("structure_cyclecount_info_shape",)) +def test_cyclecount_info_shape(): + restart_app() + wait_for_foreground() + nodes = ui() + before_n = len(nodes) + opened, before = and_enter_dialog(nodes, info_near="Charge Cycle Count") + dlg = ui() + # The modal replaces the dashboard window: node count collapses sharply and a + # single "Close" Button appears in place of the card stack. + shrank = opened and len(dlg) < before_n - 30 + has_close = bool(find_node(dlg, text="Close")) + changed = opened and surface_changed(before, and_showing(dlg)) + restored = False + if opened: + close = find_node(dlg, text="Close") + if close and tap_node(close): + restored = len(ui()) >= before_n - 2 + ok = shrank and has_close and changed and restored + record("structure_cyclecount_info_shape", ok, + "" if ok else f"behavior_wrong: cycle-count info dialog shape delta wrong " + f"(before_n={before_n}, dlg_n={len(dlg)}, close={has_close}, " + f"restored={restored})", + depth=1, jump_kind="transition", + expect="dashboard subtree (~88 nodes) replaced by a small modal (~13) with a Close button, restored on Close") + + +@and_test(expects=("structure_voltage_info_shape",)) +def test_voltage_info_shape(): + restart_app() + wait_for_foreground() + nodes = ui() + before_n = len(nodes) + opened, before = and_enter_dialog(nodes, info_near="Battery Voltage") + dlg = ui() + shrank = opened and len(dlg) < before_n - 30 + has_close = bool(find_node(dlg, text="Close")) + changed = opened and surface_changed(before, and_showing(dlg)) + restored = False + if opened: + close = find_node(dlg, text="Close") + if close and tap_node(close): + restored = len(ui()) >= before_n - 2 + ok = shrank and has_close and changed and restored + record("structure_voltage_info_shape", ok, + "" if ok else f"behavior_wrong: voltage info dialog shape delta wrong " + f"(before_n={before_n}, dlg_n={len(dlg)}, close={has_close}, " + f"restored={restored})", + depth=1, jump_kind="transition", + expect="dashboard subtree replaced by a small modal with a Close button, restored on Close") + + +@and_test(expects=("structure_estfcc_info_shape",)) +def test_estfcc_info_shape(): + restart_app() + wait_for_foreground() + nodes = ui() + before_n = len(nodes) + opened, before = and_enter_dialog(nodes, info_near="Full Charge Capacity") + dlg = ui() + shrank = opened and len(dlg) < before_n - 30 + has_close = bool(find_node(dlg, text="Close")) + changed = opened and surface_changed(before, and_showing(dlg)) + restored = False + if opened: + close = find_node(dlg, text="Close") + if close and tap_node(close): + restored = len(ui()) >= before_n - 2 + ok = shrank and has_close and changed and restored + record("structure_estfcc_info_shape", ok, + "" if ok else f"behavior_wrong: FCC info dialog shape delta wrong " + f"(before_n={before_n}, dlg_n={len(dlg)}, close={has_close}, " + f"restored={restored})", + depth=1, jump_kind="transition", + expect="dashboard subtree replaced by a small modal with a Close button, restored on Close") + + +@and_test(expects=("structure_history_help_shape",)) +def test_history_help_shape(): + restart_app() + wait_for_foreground() + ok_tab, _ = and_enter_tab(ui(), "History") + h = ui() + before_n = len(h) + before = and_showing(h) + help_btn = find_node(h, content_desc="Help") + opened = bool(help_btn) and tap_node(help_btn) + dlg = ui() + shrank = opened and len(dlg) < before_n - 15 + has_close = bool(find_node(dlg, text="Close")) + changed = opened and surface_changed(before, and_showing(dlg)) + restored = False + if opened: + close = find_node(dlg, text="Close") + if close and tap_node(close): + restored = len(ui()) >= before_n - 2 + ok = ok_tab and shrank and has_close and changed and restored + record("structure_history_help_shape", ok, + "" if ok else f"behavior_wrong: history Help dialog shape delta wrong " + f"(tab={ok_tab}, before_n={before_n}, dlg_n={len(dlg)}, " + f"close={has_close}, restored={restored})", + depth=1, jump_kind="transition", + expect="History list subtree (~43) replaced by a Help modal (~13) with Close, restored on Close") + + +@and_test(expects=("structure_history_export_shape",)) +def test_history_export_shape(): + restart_app() + wait_for_foreground() + ok_tab, _ = and_enter_tab(ui(), "History") + h = ui() + before_n = len(h) + before = and_showing(h) + exp = find_node(h, content_desc="Export") + opened = bool(exp) and tap_node(exp) + dlg = ui() + # Confirm modal adds an Export/Cancel action pair as a new layer. + changed = opened and surface_changed(before, and_showing(dlg)) + has_actions = bool(find_node(dlg, text="Cancel")) and bool(find_node(dlg, text="Export")) + restored = False + if opened: + cancel = find_node(dlg, text="Cancel") # safe dismissal, no write + if cancel and tap_node(cancel): + restored = len(ui()) >= before_n - 2 + ok = ok_tab and changed and has_actions and restored + record("structure_history_export_shape", ok, + "" if ok else f"behavior_wrong: history Export dialog shape delta wrong " + f"(tab={ok_tab}, changed={changed}, actions={has_actions}, " + f"restored={restored})", + depth=1, jump_kind="transition", + expect="Export confirm modal (Export/Cancel buttons) layered over the History list, restored on Cancel") + + +@and_test(expects=("structure_refresh_dialog_shape",)) +def test_refresh_dialog_shape(): + restart_app() + wait_for_foreground() + ok_tab, _ = and_enter_tab(ui(), "Settings") + # The refresh row is below the fold — scroll it into view first. + ri = scroll_into_view("Set refresh interval (ms)") + s = ui() + before_n = len(s) + before = and_showing(s) + opened = False + if ri: + ri = find_node(s, text="Set refresh interval (ms)") or find_node_ci(s, "Set refresh interval (ms)") + opened = bool(ri) and tap_node(ri) + if opened: + and_enter("refresh_dialog") + dlg = ui() + shrank = opened and len(dlg) < before_n - 30 + has_close = bool(find_node(dlg, text="Close")) + changed = opened and surface_changed(before, and_showing(dlg)) + restored = False + if opened: + close = find_node(dlg, text="Close") + if close and tap_node(close): + restored = len(ui()) >= before_n - 2 + ok = ok_tab and shrank and has_close and changed and restored + record("structure_refresh_dialog_shape", ok, + "" if ok else f"behavior_wrong: refresh dialog shape delta wrong " + f"(tab={ok_tab}, before_n={before_n}, dlg_n={len(dlg)}, " + f"close={has_close}, restored={restored})", + depth=1, jump_kind="transition", + expect="Settings subtree (~83) replaced by the refresh modal (~20) with a Close button, restored on Close") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (3) FAB EXPAND SHAPE DELTA — in-place overlay re-shapes the tree. depth=0. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_fab_expand_shape", "structure_fab_expand_shape_vlm")) +def test_fab_expand_shape(): + restart_app() + wait_for_foreground() + nodes = ui() + fab = find_node(nodes, content_desc="Open menu") + before = and_showing(nodes) + opened = bool(fab) and tap_node(fab) + exp = ui() + # The speed-dial overlays the dashboard: the collapsed "Open menu" affordance + # is gone and a "Close menu" affordance plus menu-item subtree appear. + flipped = opened and (not find_node(exp, content_desc="Open menu")) and \ + bool(find_node(exp, content_desc="Close menu")) + reshaped = opened and surface_changed(before, and_showing(exp)) + # Ask the VLM WHILE the speed-dial is expanded (screenshot must contain the stack). + settle("tap") + vlm_assert("structure_fab_expand_shape", + "Above the bottom-right circular button, is there a vertical stack of " + "labeled action buttons that expanded upward from that button?", + RESULTS_DIR, tag="shape") + # reverse + restored = False + if opened: + cm = find_node(exp, content_desc="Close menu") + if cm and tap_node(cm): + back = ui() + restored = bool(find_node(back, content_desc="Open menu")) and \ + not find_node(back, content_desc="Close menu") + ok = flipped and reshaped and restored + record("structure_fab_expand_shape", ok, + "" if ok else f"behavior_wrong: FAB expand shape delta wrong " + f"(flipped={flipped}, reshaped={reshaped}, restored={restored})", + depth=0, jump_kind="transition", + expect="FAB affordance 'Open menu'->'Close menu' with a menu-item subtree overlay, restored on collapse") + + +@and_test(expects=("structure_fab_position_vlm",)) +def test_fab_position(): + # A pure rendered-position claim the tree cannot express: the collapsed FAB + # sits at the bottom-right, above the nav bar. VLM-only record. + restart_app() + wait_for_foreground() + ui() # settle a fresh dashboard before the screenshot + vlm_assert("structure_fab_position", + "Is there a single round floating action button positioned in the " + "bottom-right corner of the screen, just above the bottom navigation bar?", + RESULTS_DIR, tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (4) TAB CONTENT SHAPE — each tab renders a DISTINCT top-level subtree. depth=1. +# Signature = a widget CLASS present here and absent on the Dashboard card list. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_monitor_tab_shape",)) +def test_monitor_tab_shape(): + restart_app() + wait_for_foreground() + dash = ui() + dash_chk = _count_checkable(dash) # 0 on dashboard + ok_tab, before = and_enter_tab(dash, "Monitor") + mon = ui() + mon_chk = _count_checkable(mon) # 2 toggle Views on Monitor + # Distinct subtree: Monitor adds a class of checkable View the dashboard lacks, + # and the surface materially changed. + ok = ok_tab and dash_chk == 0 and mon_chk == 2 and surface_changed(before, and_showing(mon)) + record("structure_monitor_tab_shape", ok, + "" if ok else f"behavior_wrong: Monitor subtree shape wrong " + f"(tab={ok_tab}, dash_checkable={dash_chk}, monitor_checkable={mon_chk})", + depth=1, jump_kind="transition", + expect="checkable-View count 0 (Dashboard) -> 2 (Monitor); distinct subtree") + + +@and_test(expects=("structure_settings_tab_shape", "structure_settings_tab_shape_vlm")) +def test_settings_tab_shape(): + restart_app() + wait_for_foreground() + dash = ui() + dash_chk = _count_checkable(dash) # 0 + ok_tab, before = and_enter_tab(dash, "Settings") + st = ui() + set_chk = _count_checkable(st) # 6 toggle Views on Settings + ok = ok_tab and dash_chk == 0 and set_chk == 6 and surface_changed(before, and_showing(st)) + record("structure_settings_tab_shape", ok, + "" if ok else f"behavior_wrong: Settings subtree shape wrong " + f"(tab={ok_tab}, dash_checkable={dash_chk}, settings_checkable={set_chk})", + depth=1, jump_kind="transition", + expect="checkable-View count 0 (Dashboard) -> 6 (Settings); distinct subtree") + vlm_assert("structure_settings_tab_shape", + "Is the settings content organized into multiple grouped section cards, " + "each containing rows with a toggle switch on the right side?", + RESULTS_DIR, tag="layout") + + +@and_test(expects=("structure_history_tab_shape", "structure_history_tab_shape_vlm")) +def test_history_tab_shape(): + restart_app() + wait_for_foreground() + dash = ui() + ok_tab, before = and_enter_tab(dash, "History") + h = ui() + # History's signature: a top toolbar exposing Export + Help icon Buttons that + # the Dashboard does not have, plus its own list subtree (no checkable Views). + toolbar = bool(find_node(h, content_desc="Export")) and bool(find_node(h, content_desc="Help")) + no_toggles = _count_checkable(h) == 0 + dash_toolbar = bool(find_node(dash, content_desc="Export")) # absent on dashboard + ok = ok_tab and toolbar and no_toggles and not dash_toolbar and \ + surface_changed(before, and_showing(h)) + record("structure_history_tab_shape", ok, + "" if ok else f"behavior_wrong: History subtree shape wrong " + f"(tab={ok_tab}, toolbar={toolbar}, no_toggles={no_toggles}, " + f"dash_had_toolbar={dash_toolbar})", + depth=1, jump_kind="transition", + expect="History adds an Export+Help toolbar subtree absent on the Dashboard") + vlm_assert("structure_history_tab_shape", + "Are there two circular icon buttons in the top-right corner, with a " + "list of history record entries below them?", + RESULTS_DIR, tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# (5) DEEP SURFACE SHAPE — depth=2 (Dashboard -> tab -> nested settings). +# Backed by TWO and_enter_* calls so the depth auditor accepts depth=2. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_monitor_entry_checkboxes", "structure_monitor_entry_checkboxes_vlm")) +def test_monitor_entry_checkboxes(): + restart_app() + wait_for_foreground() + ok_tab, _ = and_enter_tab(ui(), "Monitor") + mon = ui() + ok_deep, before = and_enter_deep(mon, text="Monitor entry settings") + mes = ui() + # Deep surface signature: a column of CheckBox widgets (none exist anywhere on + # the Dashboard/Monitor card surfaces). + cbs = len(find_by_class(mes, "CheckBox")) + ok = ok_tab and ok_deep and cbs == 9 and surface_changed(before, and_showing(mes)) + record("structure_monitor_entry_checkboxes", ok, + "" if ok else f"behavior_wrong: Monitor Entry Settings CheckBox count wrong " + f"(tab={ok_tab}, deep={ok_deep}, checkboxes={cbs}, expected 9)", + depth=2, jump_kind="transition", + expect="CheckBox class count = 9 on Monitor Entry Settings (0 on the tabs above it)") + vlm_assert("structure_monitor_entry_checkboxes", + "Is this a vertical list of rows where each row has a filled checkbox " + "at its far left followed by a text label?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("structure_floating_window_seekbars", "structure_floating_window_seekbars_vlm")) +def test_floating_window_seekbars(): + restart_app() + wait_for_foreground() + ok_tab, _ = and_enter_tab(ui(), "Monitor") + mon = ui() + ok_deep, before = and_enter_deep(mon, text="Floating window settings") + fws = ui() + # Deep surface signature: a set of SeekBar (Compose Slider) widgets that no + # other surface in this app renders. + sbs = len(find_by_class(fws, "SeekBar")) + ok = ok_tab and ok_deep and sbs == 3 and surface_changed(before, and_showing(fws)) + record("structure_floating_window_seekbars", ok, + "" if ok else f"behavior_wrong: Floating Window Settings SeekBar count wrong " + f"(tab={ok_tab}, deep={ok_deep}, seekbars={sbs}, expected 3)", + depth=2, jump_kind="transition", + expect="SeekBar class count = 3 on Floating Window Settings") + vlm_assert("structure_floating_window_seekbars", + "Does this screen show horizontal slider controls and a horizontal row " + "of rounded color-option chips grouped inside cards?", + RESULTS_DIR, tag="shape") + + +@and_test(expects=("structure_about_shape", "structure_about_shape_vlm")) +def test_about_shape(): + restart_app() + wait_for_foreground() + ok_tab, _ = and_enter_tab(ui(), "Settings") + # About is below the fold on Settings; scroll then open it. + ab = scroll_into_view("About") + st = ui() + ok_deep = False + before = set() + if ab: + ok_deep, before = and_enter_deep(st, text="About") + ab_nodes = ui() + # About's signature: a Back affordance + a scrollable long text block, and it + # carries NONE of Settings' toggle Views. + back = bool(find_node(ab_nodes, content_desc="Back")) + has_scroll = bool(find_by_class(ab_nodes, "ScrollView")) + no_toggles = _count_checkable(ab_nodes) == 0 + ok = ok_tab and ok_deep and back and has_scroll and no_toggles and \ + surface_changed(before, and_showing(ab_nodes)) + record("structure_about_shape", ok, + "" if ok else f"behavior_wrong: About subtree shape wrong " + f"(tab={ok_tab}, deep={ok_deep}, back={back}, " + f"scroll={has_scroll}, toggles0={no_toggles})", + depth=2, jump_kind="transition", + expect="About = Back + a scrollable text block, none of Settings' toggle Views") + vlm_assert("structure_about_shape", + "Is this screen dominated by a single large block of paragraph text " + "(version, repo, author and battery-field descriptions) rather than " + "rows of controls?", + RESULTS_DIR, tag="layout") + + +TESTS = [ + test_gate_launch, + test_gate_navhost, + test_gate_title_and_cards, + test_calibrate_dialog_shape, + test_cyclecount_info_shape, + test_voltage_info_shape, + test_estfcc_info_shape, + test_history_help_shape, + test_history_export_shape, + test_refresh_dialog_shape, + test_fab_expand_shape, + test_fab_position, + test_monitor_tab_shape, + test_settings_tab_shape, + test_history_tab_shape, + test_monitor_entry_checkboxes, + test_floating_window_seekbars, + test_about_shape, +] + +if __name__ == "__main__": + run_suite(TESTS, "structure") diff --git a/android/dijia1124-plusplusbattery/tests/test_android_text.py b/android/dijia1124-plusplusbattery/tests/test_android_text.py new file mode 100644 index 0000000000000000000000000000000000000000..59e58b394b680cd3a43b13310b89e01b6e1370d0 --- /dev/null +++ b/android/dijia1124-plusplusbattery/tests/test_android_text.py @@ -0,0 +1,719 @@ +#!/usr/bin/env python3 +"""TEXT lane — PlusPlusBattery (Jetpack Compose battery info viewer). + +This lane owns the CONTENT STRINGS an interaction PRODUCES, and it is the sole +owner of exact-string equality. Every test is a TRIGGER (tap a swap/toggle, open +a dialog, reach a nested screen) -> read the EXACT string the running app then +renders out of a FRESH ui() dump. A dead shell that never renders the string must +FAIL, so the discriminating half of each test asserts the string is ABSENT before +the trigger (where meaningful) and PRESENT after. + +What this lane does NOT touch: the computed numeric VALUES of the calibration / +power engine (computation), any checked/enabled/selected bit (states), CRUD / +persistence (interaction), tree shape (structure), or surface reachability as the +point (navigation — a dialog/tab is opened here only as a PRECONDITION to read a +string it renders). + +Every expected string below was confirmed by dumping the running ORIGINAL app: + + Dashboard (depth 0, produced IN PLACE by a toggle): + - "Swap Unit" temp label 25.0°C -> 77.0°F (restore to °C) + - "Toggle Dual Battery" Dual Cell No -> Yes (restore to No) + + Dashboard info/calibrate DIALOG TITLES (depth 1, open -> read title -> Close): + - "Calibrate" dialog title = "Calibrate via Multiplier" + - Charge-Cycle-Count info dialog title = "Charge Cycle Count" + - Battery-Voltage info dialog title = "Battery Voltage" + - Full-Charge-Capacity info dialog title = "FCC Estimation" (card label differs) + + History tab DIALOG TITLES (depth 1 — the dialog is the crossed surface): + - Help toolbar button -> dialog title "History" + - Export toolbar button -> dialog title "Export History" + (only OPEN it; never tap its "Export" confirm — that writes a CSV / opens SAF) + + Settings refresh DIALOG content (depth 1): + - "Set refresh interval (ms)" -> dialog shows "Current value: 1000" + + Nested-screen STATIC content: + - Monitor -> "Floating window settings" (depth 2): "Opacity: 0.75", + "Size: 1.00", "Font weight: 400" (static text; sliders ignore uiautomator) + - Settings -> "About" (depth 1): a "Version:" label renders (the version NUMBER + may vary between builds, so only the stable "Version:" label is asserted) + +Info-buttons share the duplicate content-desc "Show Info"; the SPECIFIC dialog is +opened by tapping the "Show Info" nearest in y to its row label, then CONFIRMED by +the dialog title. Dialogs are dismissed with tap_node on "Close" (Close is a +DANGEROUS_TEXT, so safe_tap would refuse) or hardware BACK for the nested screens. +Every depth>=1 record is backed by a helper NAMED and_enter_*/and_reach_* so the +depth auditor counts it. VLM budget for this lane is EXACTLY 2 (both tag="content", +the right tag for a rendered-text confirmation): the swapped "77.0°F" temperature +label, and the static "Opacity: 0.75" header on the Floating window screen. +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,F401 +import android_testgen_kit as _kit # for the private depth counter only + +RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else os.path.dirname(os.path.abspath(__file__)) + + +# ── Observed constants (each read off the running original) ────────────────────── +CD_SWAP = "Swap Unit" +CD_DUAL = "Toggle Dual Battery" +CD_CALIBRATE = "Calibrate" +CD_SHOW_INFO = "Show Info" + +TEMP_C = "25.0°C" +TEMP_F = "77.0°F" +DUAL_NO = "No" +DUAL_YES = "Yes" + +CLOSE = "Close" + +# Dialog titles (exact) +CAL_TITLE = "Calibrate via Multiplier" +CYCLE_TITLE = "Charge Cycle Count" +VOLTAGE_TITLE = "Battery Voltage" +FCC_TITLE = "FCC Estimation" +HISTORY_HELP_TITLE = "History" +EXPORT_TITLE = "Export History" +REFRESH_VALUE = "Current value: 1000" + +# Row labels used to disambiguate the duplicate "Show Info" buttons by y-proximity +LABEL_CYCLE = "Charge Cycle Count" +LABEL_VOLTAGE = "Battery Voltage" +LABEL_FCC = "Full Charge Capacity" + +# Nested-screen static strings +FW_OPACITY = "Opacity: 0.75" +FW_SIZE = "Size: 1.00" +FW_FONT = "Font weight: 400" +VERSION_LABEL = "Version:" + + +# ══════════════════════════════════════════════════════════════════════════════ +# Small readers / helpers +# ══════════════════════════════════════════════════════════════════════════════ + +def _dec_depth() -> int: + """Pop one surface from the kit's depth counter WITHOUT a hardware BACK — for a + dialog dismissed by its own Close affordance.""" + _kit._DEPTH = max(0, _kit._DEPTH - 1) + return _kit._DEPTH + + +def ready() -> bool: + """restart_app + wait; True once the Dashboard is up.""" + restart_app() + return wait_for_foreground() + + +def all_text(nodes=None) -> str: + nodes = ui() if nodes is None else nodes + return " | ".join(n.get("text", "") for n in nodes if n.get("text")) + + +def temp_value(nodes=None) -> str: + """The Battery Temperature label ("25.0°C"/"77.0°F"), or "".""" + nodes = ui() if nodes is None else nodes + for n in nodes: + if "°" in n.get("text", ""): + return n["text"] + return "" + + +def dual_value(nodes=None) -> str: + """The Dual Cell value string ("No"/"Yes"), or "".""" + nodes = ui() if nodes is None else nodes + if find_node(nodes, text=DUAL_YES): + return DUAL_YES + if find_node(nodes, text=DUAL_NO): + return DUAL_NO + return "" + + +def read_until(reader, want: str, tries: int = 6) -> str: + """Poll `reader` across fresh dumps until it equals `want` (or gives up). The + dashboard can re-dump stale for one frame right after a toggle/dialog; this + makes the read robust without ever fabricating a value.""" + val = "" + for _ in range(tries): + val = reader(ui()) + if val == want: + return val + settle("tap") + return val + + +def dialog_title(nodes=None) -> str: + """Best-effort dialog title = the FIRST non-empty TextView text in the dump. + Only used for logging; assertions match the exact expected title directly.""" + nodes = ui() if nodes is None else nodes + for n in nodes: + t = n.get("text", "").strip() + if t: + return t + return "" + + +def close_dialog() -> None: + """Dismiss an open dialog via its Close button (tap_node — Close is a + DANGEROUS_TEXT so safe_tap would refuse; it only dismisses the dialog).""" + c = find_node(ui(), text=CLOSE) or find_node_ci(ui(), CLOSE) + if c: + tap_node(c) + + +def restore_temp_c() -> None: + if temp_value(ui()) == TEMP_F: + sw = find_node(ui(), content_desc=CD_SWAP) + if sw: + tap_node(sw) + read_until(temp_value, TEMP_C) + + +def restore_dual_off() -> None: + if dual_value(ui()) == DUAL_YES: + d = find_node(ui(), content_desc=CD_DUAL) + if d: + tap_node(d) + read_until(dual_value, DUAL_NO) + + +# ══════════════════════════════════════════════════════════════════════════════ +# depth-family helpers — named and_enter_*/and_reach_* so the depth auditor counts +# every declared depth>=1 as backed by a real navigation call. Each opens a surface +# and confirms an element of that surface appeared before counting it. +# ══════════════════════════════════════════════════════════════════════════════ + +def and_enter_calibrate_dialog(nodes=None) -> bool: + """Dashboard -> Calibrate dialog. Confirmed by its title, then counts one + surface via the kit's depth counter.""" + nodes = ui() if nodes is None else nodes + trig = find_node(nodes, content_desc=CD_CALIBRATE) + if trig is None or not tap_node(trig): + return False + if find_node(ui(), text=CAL_TITLE) is None: + return False + and_enter("calibrate_dialog") + return True + + +def and_enter_info_dialog(row_label: str, expect_title: str) -> bool: + """Open the info dialog whose "Show Info" button is nearest in y to `row_label`, + then confirm `expect_title` rendered. Counts one surface.""" + nodes = ui() + lab = find_node(nodes, text=row_label) + if lab is None or "_bounds" not in lab: + return False + ly = lab["_bounds"][1] + infos = [n for n in nodes + if n.get("content-desc") == CD_SHOW_INFO and "_bounds" in n] + if not infos: + return False + infos.sort(key=lambda n: abs(n["_bounds"][1] - ly)) + if not tap_node(infos[0]): + return False + if find_node(ui(), text=expect_title) is None: + return False + and_enter("info_dialog") + return True + + +def and_reach_history_tab() -> bool: + """Dashboard -> History tab. Proven by a History-tab element appearing and the + Dashboard card gone; counts one surface (jump backing for depth).""" + h = find_node(ui(), content_desc="History") + if h is None: + return False + return and_reach_surface(h, target="Export", source="Battery Level") + + +def and_enter_history_dialog(toolbar_cd: str, expect_title: str) -> bool: + """History tab -> a toolbar dialog (Help/Export). Confirmed by title; counts + one surface. Assumes the History tab is already showing.""" + btn = find_node(ui(), content_desc=toolbar_cd) + if btn is None or not tap_node(btn): + return False + if find_node(ui(), text=expect_title) is None: + return False + and_enter(f"history_{toolbar_cd}_dialog") + return True + + +def and_reach_settings_tab() -> bool: + s = find_node(ui(), content_desc="Settings") + if s is None: + return False + return and_reach_surface(s, target="Follow system theme", source="Battery Level") + + +def and_enter_refresh_dialog() -> bool: + """Settings -> refresh-interval dialog. Confirmed by its "Current value:" line; + counts one surface. Assumes the Settings tab is already showing.""" + ri = find_node(ui(), text="Set refresh interval (ms)") + if ri is None or not tap_node(ri): + return False + if find_node(ui(), text=REFRESH_VALUE) is None: + return False + and_enter("refresh_dialog") + return True + + +def and_enter_floating_settings() -> bool: + """Monitor -> Floating window settings (a second surface). Confirmed by the + screen title, then counts one surface. Assumes the Monitor tab is showing.""" + fw = find_node(ui(), text="Floating window settings") + if fw is None or not tap_node(fw): + return False + if find_node(ui(), text="Floating Window Settings") is None: + return False + and_enter("floating_settings") + return True + + +def and_reach_monitor_tab() -> bool: + m = find_node(ui(), content_desc="Monitor") + if m is None: + return False + return and_reach_surface(m, target="Floating window settings", + source="Battery Level") + + +def and_reach_about_screen() -> bool: + """Settings -> About (a nested screen). Scroll it into view, tap, confirm a + "Version:" string appeared and the Settings list is gone; counts one surface. + Assumes the Settings tab is already showing.""" + ab = scroll_into_view("About") + if ab is None: + return False + before = and_showing() + if not tap_node(ab): + return False + after = and_showing() + # target: any node carrying the Version label; source: a Settings-only row + appeared = any("version:" in k.lower() for k in (after - before)) or \ + any(VERSION_LABEL.lower() in n.get("text", "").lower() for n in ui()) + if not appeared: + return False + and_enter("about_screen") + return True + + +# ══════════════════════════════════════════════════════════════════════════════ +# DASHBOARD toggles — the produced label IN PLACE (depth 0). Positive/negative: +# the produced string is ABSENT before the toggle and PRESENT after. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_temp_label_after_swap", "text_temp_label_after_swap_vlm")) +def test_temp_label_after_swap(): + if not ready(): + record("text_temp_label_after_swap", False, + "setup_failed: app did not reach foreground", + depth=0, jump_kind="value", expect=f"temperature label reads {TEMP_F}") + return + before = read_until(temp_value, TEMP_C) + sw = find_node(ui(), content_desc=CD_SWAP) + if sw is None or not tap_node(sw): + record("text_temp_label_after_swap", False, + "feature_missing: no 'Swap Unit' control on the temperature card", + depth=0, jump_kind="value", expect=f"temperature label reads {TEMP_F}") + return + after = read_until(temp_value, TEMP_F) + # ABSENT before (°F not shown), PRESENT after + ok = (before == TEMP_C) and (TEMP_F not in (before or "")) and (after == TEMP_F) + record("text_temp_label_after_swap", ok, + "" if ok else + f"behavior_wrong: Swap Unit should make the temperature label read " + f"{TEMP_F!r}; saw before={before!r} after={after!r}", + depth=0, jump_kind="value", expect=f"temperature label reads {TEMP_F}") + # VLM (content): the swapped label is on screen right now, before the restore. + vlm_assert("text_temp_label_after_swap", + "Look at the 'Battery Temperature' row. Does its value read exactly " + "'77.0°F' (a Fahrenheit temperature), rather than a Celsius value like " + "'25.0°C'?", + RESULTS_DIR, depth=0, jump_kind="none", tag="content") + restore_temp_c() + + +@and_test(expects=("text_dual_value_after_toggle",)) +def test_dual_value_after_toggle(): + if not ready(): + record("text_dual_value_after_toggle", False, + "setup_failed: app did not reach foreground", + depth=0, jump_kind="value", expect=f"Dual Cell value reads {DUAL_YES}") + return + before = read_until(dual_value, DUAL_NO) + d = find_node(ui(), content_desc=CD_DUAL) + if d is None or not tap_node(d): + record("text_dual_value_after_toggle", False, + "feature_missing: no 'Toggle Dual Battery' control", + depth=0, jump_kind="value", expect=f"Dual Cell value reads {DUAL_YES}") + return + after = read_until(dual_value, DUAL_YES) + ok = (before == DUAL_NO) and (after == DUAL_YES) + record("text_dual_value_after_toggle", ok, + "" if ok else + f"behavior_wrong: Toggle Dual Battery should make the Dual Cell value " + f"read {DUAL_YES!r}; saw before={before!r} after={after!r}", + depth=0, jump_kind="value", expect=f"Dual Cell value reads {DUAL_YES}") + restore_dual_off() + + +# ══════════════════════════════════════════════════════════════════════════════ +# DASHBOARD dialog TITLES (depth 1) — open the dialog, assert its EXACT title +# string, then Close. The title is ABSENT before the trigger and PRESENT after. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_calibrate_dialog_title",)) +def test_calibrate_dialog_title(): + if not ready(): + record("text_calibrate_dialog_title", False, + "setup_failed: app did not reach foreground", + depth=1, jump_kind="value", expect=f"dialog title {CAL_TITLE!r}") + return + absent = find_node(ui(), text=CAL_TITLE) is None + if find_node(ui(), content_desc=CD_CALIBRATE) is None: + record("text_calibrate_dialog_title", False, + "feature_missing: no 'Calibrate' control on the Battery Current card", + depth=1, jump_kind="value", expect=f"dialog title {CAL_TITLE!r}") + return + opened = and_enter_calibrate_dialog() + title = dialog_title() if opened else "" + present = find_node(ui(), text=CAL_TITLE) is not None + ok = absent and opened and present + record("text_calibrate_dialog_title", ok, + "" if ok else + f"behavior_wrong: the Calibrate dialog title should be {CAL_TITLE!r}; " + f"opened={opened} saw={title!r}", + depth=1, jump_kind="value", expect=f"dialog title {CAL_TITLE!r}") + close_dialog() + if opened: + _dec_depth() + + +def _info_title_case(name: str, row_label: str, expect_title: str): + """Shared body for an info-dialog-title assertion (depth 1). The dialog is + proven present by (title text + a Close button), which is robust even when the + dialog title happens to equal the card row label.""" + if not ready(): + record(name, False, "setup_failed: app did not reach foreground", + depth=1, jump_kind="value", expect=f"dialog title {expect_title!r}") + return + dialog_before = find_node(ui(), text=CLOSE) is not None + if find_node(ui(), text=row_label) is None: + record(name, False, + f"feature_missing: no '{row_label}' row on the Dashboard", + depth=1, jump_kind="value", expect=f"dialog title {expect_title!r}") + return + opened = and_enter_info_dialog(row_label, expect_title) + title = dialog_title() if opened else "" + present = (find_node(ui(), text=expect_title) is not None + and find_node(ui(), text=CLOSE) is not None) + ok = (not dialog_before) and opened and present + record(name, ok, + "" if ok else + f"behavior_wrong: the '{row_label}' info dialog title should be " + f"{expect_title!r}; opened={opened} saw={title!r}", + depth=1, jump_kind="value", expect=f"dialog title {expect_title!r}") + close_dialog() + if opened: + _dec_depth() + + +@and_test(expects=("text_cycle_count_dialog_title",)) +def test_cycle_count_dialog_title(): + _info_title_case("text_cycle_count_dialog_title", LABEL_CYCLE, CYCLE_TITLE) + + +@and_test(expects=("text_voltage_dialog_title",)) +def test_voltage_dialog_title(): + _info_title_case("text_voltage_dialog_title", LABEL_VOLTAGE, VOLTAGE_TITLE) + + +@and_test(expects=("text_fcc_dialog_title",)) +def test_fcc_dialog_title(): + """The Full-Charge-Capacity card's info dialog title is 'FCC Estimation' — it + DIFFERS from the card label, so this is a genuine produced-string check.""" + if not ready(): + record("text_fcc_dialog_title", False, + "setup_failed: app did not reach foreground", + depth=1, jump_kind="value", expect=f"dialog title {FCC_TITLE!r}") + return + absent = find_node(ui(), text=FCC_TITLE) is None + if find_node(ui(), text=LABEL_FCC) is None: + record("text_fcc_dialog_title", False, + "feature_missing: no 'Full Charge Capacity' row on the Dashboard", + depth=1, jump_kind="value", expect=f"dialog title {FCC_TITLE!r}") + return + opened = and_enter_info_dialog(LABEL_FCC, FCC_TITLE) + title = dialog_title() if opened else "" + present = find_node(ui(), text=FCC_TITLE) is not None + ok = absent and opened and present + record("text_fcc_dialog_title", ok, + "" if ok else + f"behavior_wrong: the Full Charge Capacity info dialog title should be " + f"{FCC_TITLE!r} (differs from the card label); opened={opened} saw={title!r}", + depth=1, jump_kind="value", expect=f"dialog title {FCC_TITLE!r}") + close_dialog() + if opened: + _dec_depth() + + +# ══════════════════════════════════════════════════════════════════════════════ +# HISTORY tab dialog TITLES (depth 1 — the dialog is the crossed surface reached +# from the History tab). Only OPEN each dialog; never tap Export's confirm. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_history_help_dialog_title",)) +def test_history_help_dialog_title(): + if not ready(): + record("text_history_help_dialog_title", False, + "setup_failed: app did not reach foreground", + depth=1, jump_kind="value", + expect=f"Help dialog title {HISTORY_HELP_TITLE!r}") + return + if not and_reach_history_tab(): + record("text_history_help_dialog_title", False, + "setup_failed: could not reach the History tab", + depth=1, jump_kind="value", + expect=f"Help dialog title {HISTORY_HELP_TITLE!r}") + return + if find_node(ui(), content_desc="Help") is None: + record("text_history_help_dialog_title", False, + "feature_missing: no 'Help' toolbar button on the History tab", + depth=1, jump_kind="value", + expect=f"Help dialog title {HISTORY_HELP_TITLE!r}") + _kit._DEPTH = 0 + return + dialog_before = find_node(ui(), text=CLOSE) is not None + opened = and_enter_history_dialog("Help", HISTORY_HELP_TITLE) + # confirm the Help dialog specifically (title + Close button present) + present = (find_node(ui(), text=HISTORY_HELP_TITLE) is not None + and find_node(ui(), text=CLOSE) is not None) + ok = (not dialog_before) and opened and present + record("text_history_help_dialog_title", ok, + "" if ok else + f"behavior_wrong: the History Help dialog title should be " + f"{HISTORY_HELP_TITLE!r}; opened={opened}", + depth=1, jump_kind="value", + expect=f"Help dialog title {HISTORY_HELP_TITLE!r}") + close_dialog() + _kit._DEPTH = 0 + + +@and_test(expects=("text_history_export_dialog_title",)) +def test_history_export_dialog_title(): + if not ready(): + record("text_history_export_dialog_title", False, + "setup_failed: app did not reach foreground", + depth=1, jump_kind="value", expect=f"dialog title {EXPORT_TITLE!r}") + return + if not and_reach_history_tab(): + record("text_history_export_dialog_title", False, + "setup_failed: could not reach the History tab", + depth=1, jump_kind="value", expect=f"dialog title {EXPORT_TITLE!r}") + return + absent = find_node(ui(), text=EXPORT_TITLE) is None + if find_node(ui(), content_desc="Export") is None: + record("text_history_export_dialog_title", False, + "feature_missing: no 'Export' toolbar button on the History tab", + depth=1, jump_kind="value", expect=f"dialog title {EXPORT_TITLE!r}") + _kit._DEPTH = 0 + return + opened = and_enter_history_dialog("Export", EXPORT_TITLE) + title = dialog_title() if opened else "" + present = find_node(ui(), text=EXPORT_TITLE) is not None + ok = absent and opened and present + record("text_history_export_dialog_title", ok, + "" if ok else + f"behavior_wrong: the History Export dialog title should be " + f"{EXPORT_TITLE!r}; opened={opened} saw={title!r}", + depth=1, jump_kind="value", expect=f"dialog title {EXPORT_TITLE!r}") + # Dismiss WITHOUT tapping "Export" (which writes a CSV / opens SAF). Cancel is + # safe; else hardware BACK. + cancel = find_node(ui(), text="Cancel") + if cancel: + tap_node(cancel) + else: + back() + _kit._DEPTH = 0 + + +# ══════════════════════════════════════════════════════════════════════════════ +# SETTINGS refresh dialog content (depth 1) — exact produced string. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_refresh_dialog_current_value",)) +def test_refresh_dialog_current_value(): + if not ready(): + record("text_refresh_dialog_current_value", False, + "setup_failed: app did not reach foreground", + depth=1, jump_kind="value", expect=f"dialog shows {REFRESH_VALUE!r}") + return + if not and_reach_settings_tab(): + record("text_refresh_dialog_current_value", False, + "setup_failed: could not reach the Settings tab", + depth=1, jump_kind="value", expect=f"dialog shows {REFRESH_VALUE!r}") + return + absent = find_node(ui(), text=REFRESH_VALUE) is None + if find_node(ui(), text="Set refresh interval (ms)") is None: + record("text_refresh_dialog_current_value", False, + "feature_missing: no 'Set refresh interval (ms)' control in Settings", + depth=1, jump_kind="value", expect=f"dialog shows {REFRESH_VALUE!r}") + _kit._DEPTH = 0 + return + opened = and_enter_refresh_dialog() + present = find_node(ui(), text=REFRESH_VALUE) is not None + ok = absent and opened and present + record("text_refresh_dialog_current_value", ok, + "" if ok else + f"behavior_wrong: the refresh-interval dialog should show {REFRESH_VALUE!r}; " + f"opened={opened}", + depth=1, jump_kind="value", expect=f"dialog shows {REFRESH_VALUE!r}") + close_dialog() + if opened: + _dec_depth() + _kit._DEPTH = 0 + + +# ══════════════════════════════════════════════════════════════════════════════ +# MONITOR -> Floating window settings (depth 2) — three STATIC header strings. +# Each is asserted absent on the Monitor tab and present on the settings screen. +# ══════════════════════════════════════════════════════════════════════════════ + +def _floating_header_case(name: str, expect_str: str): + if not ready(): + record(name, False, "setup_failed: app did not reach foreground", + depth=2, jump_kind="value", expect=f"header {expect_str!r}") + return + if not and_reach_monitor_tab(): + record(name, False, "setup_failed: could not reach the Monitor tab", + depth=2, jump_kind="value", expect=f"header {expect_str!r}") + return + absent = find_node(ui(), text=expect_str) is None + if find_node(ui(), text="Floating window settings") is None: + record(name, False, + "feature_missing: no 'Floating window settings' entry on Monitor", + depth=2, jump_kind="value", expect=f"header {expect_str!r}") + _kit._DEPTH = 0 + return + entered = and_enter_floating_settings() + present = find_node(ui(), text=expect_str) is not None + ok = absent and entered and present + record(name, ok, + "" if ok else + f"behavior_wrong: the Floating window settings screen should render the " + f"header {expect_str!r}; entered={entered}", + depth=2, jump_kind="value", expect=f"header {expect_str!r}") + _kit._DEPTH = 0 + + +@and_test(expects=("text_floating_opacity_header", "text_floating_opacity_header_vlm")) +def test_floating_opacity_header(): + if not ready(): + record("text_floating_opacity_header", False, + "setup_failed: app did not reach foreground", + depth=2, jump_kind="value", expect=f"header {FW_OPACITY!r}") + return + if not and_reach_monitor_tab(): + record("text_floating_opacity_header", False, + "setup_failed: could not reach the Monitor tab", + depth=2, jump_kind="value", expect=f"header {FW_OPACITY!r}") + return + absent = find_node(ui(), text=FW_OPACITY) is None + if find_node(ui(), text="Floating window settings") is None: + record("text_floating_opacity_header", False, + "feature_missing: no 'Floating window settings' entry on Monitor", + depth=2, jump_kind="value", expect=f"header {FW_OPACITY!r}") + _kit._DEPTH = 0 + return + entered = and_enter_floating_settings() + present = find_node(ui(), text=FW_OPACITY) is not None + ok = absent and entered and present + record("text_floating_opacity_header", ok, + "" if ok else + f"behavior_wrong: the Floating window settings screen should render the " + f"header {FW_OPACITY!r}; entered={entered}", + depth=2, jump_kind="value", expect=f"header {FW_OPACITY!r}") + # VLM (content): the Opacity header is on screen now. + vlm_assert("text_floating_opacity_header", + "Does this screen show a settings label that reads exactly " + "'Opacity: 0.75'?", + RESULTS_DIR, depth=2, jump_kind="none", tag="content") + _kit._DEPTH = 0 + + +@and_test(expects=("text_floating_size_header",)) +def test_floating_size_header(): + _floating_header_case("text_floating_size_header", FW_SIZE) + + +@and_test(expects=("text_floating_font_weight_header",)) +def test_floating_font_weight_header(): + _floating_header_case("text_floating_font_weight_header", FW_FONT) + + +# ══════════════════════════════════════════════════════════════════════════════ +# SETTINGS -> About (depth 1) — the produced "Version:" label. The version NUMBER +# may differ between builds, so only the stable label is asserted (never the value +# read from a source tree). +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_about_version_label",)) +def test_about_version_label(): + if not ready(): + record("text_about_version_label", False, + "setup_failed: app did not reach foreground", + depth=1, jump_kind="value", expect=f"About shows a {VERSION_LABEL!r} label") + return + if not and_reach_settings_tab(): + record("text_about_version_label", False, + "setup_failed: could not reach the Settings tab", + depth=1, jump_kind="value", expect=f"About shows a {VERSION_LABEL!r} label") + return + absent = VERSION_LABEL.lower() not in all_text(ui()).lower() + if scroll_into_view("About") is None: + record("text_about_version_label", False, + "feature_missing: no 'About' entry in Settings", + depth=1, jump_kind="value", expect=f"About shows a {VERSION_LABEL!r} label") + _kit._DEPTH = 0 + return + reached = and_reach_about_screen() + present = VERSION_LABEL.lower() in all_text(ui()).lower() + ok = absent and reached and present + record("text_about_version_label", ok, + "" if ok else + f"behavior_wrong: the About screen should render a {VERSION_LABEL!r} label; " + f"reached={reached}", + depth=1, jump_kind="value", expect=f"About shows a {VERSION_LABEL!r} label") + _kit._DEPTH = 0 + + +TESTS = [ + # Dashboard produced labels (depth 0) + test_temp_label_after_swap, # + 1 VLM (content) + test_dual_value_after_toggle, + # Dashboard dialog titles (depth 1) + test_calibrate_dialog_title, + test_cycle_count_dialog_title, + test_voltage_dialog_title, + test_fcc_dialog_title, + # History tab dialog titles (depth 1) + test_history_help_dialog_title, + test_history_export_dialog_title, + # Settings refresh dialog (depth 1) + test_refresh_dialog_current_value, + # Monitor -> Floating window settings static headers (depth 2) + test_floating_opacity_header, # + 1 VLM (content) + test_floating_size_header, + test_floating_font_weight_header, + # Settings -> About (depth 1) + test_about_version_label, +] + + +if __name__ == "__main__": + run_suite(TESTS, "text") diff --git a/android/dijia1124-plusplusbattery/tests/test_manifest.json b/android/dijia1124-plusplusbattery/tests/test_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..0d754a0e253237311438c41e5d5dc78ade3e354c --- /dev/null +++ b/android/dijia1124-plusplusbattery/tests/test_manifest.json @@ -0,0 +1,744 @@ +{ + "manifest_version": 1, + "kit_api_version": 1, + "task_id": "plusplusbattery", + "baseline_model": "claude-opus-4-8", + "baseline_package": "", + "total": 101, + "manifest_sha": "71a36e558f12", + "tests": [ + { + "name": "computation::computation_current_divide_10p1", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_current_divide_10p2", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_current_divide_10p3", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_current_divide_10p4", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_current_divide_10p5", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_current_divide_10p5_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_current_divide_then_reset", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_current_multiply_10p1", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_power_baseline", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_power_divide_10p2", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_power_divide_10p3", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_power_divide_10p3_dual", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_power_divide_10p3_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_power_divide_10p4", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_power_dual_only", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_temp_c_to_f", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_temp_f_to_c", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_temp_swap_round_trip", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_calibrate_sequence_integrity", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_dual_toggle_idempotent", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_fab_expand_collapse", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_follow_system_dark_dependency", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_monitor_checkbox_persists_nav", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_monitor_checkbox_persists_process_death", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_multiplier_persists_process_death", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_multiplier_then_dual_power", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_radio_selection_sequence", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_show_fab_persists_cross_surface", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_temp_swap_idempotent", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_temp_unit_persists_process_death", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_three_card_state_integrity", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_about_to_settings", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_deep_unwind_to_dashboard", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_entry_settings_to_monitor", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_floating_settings_to_monitor", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_backstack_tab_back_to_dashboard", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_about", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_calibrate_dialog", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_dashboard_to_monitor", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_dashboard_to_settings", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_floating_window_settings", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_history_export_dialog", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_history_help_dialog", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_history_to_settings", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_monitor_entry_settings", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_monitor_to_history", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_reach_settings_to_dashboard", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_roundtrip_dashboard_settings_dashboard", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::nav_roundtrip_history_dashboard_history", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "states::states_daily_log_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_daily_log_toggle_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_enable_dependency", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_enable_dependency_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_mode_dark_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_mode_light_baseline_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_mode_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_floating_enable_touch", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_floating_text_shadow", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_floating_text_shadow_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_floating_text_stroke", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_monitor_checkbox", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_monitor_checkbox_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_oplus_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_radio_divide", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_radio_divide_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_setting_persists_process_death", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_showfab_consequence", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_showfab_consequence_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_showfab_toggle", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "structure::structure_about_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_calibrate_dialog_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_cyclecount_info_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_estfcc_info_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_fab_expand_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_floating_window_seekbars", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_launch", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_navhost", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_title_and_cards", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_history_export_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_history_help_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_history_tab_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_monitor_entry_checkboxes", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_monitor_tab_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_refresh_dialog_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_tab_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_voltage_info_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "text::text_about_version_label", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_calibrate_dialog_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_cycle_count_dialog_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_dual_value_after_toggle", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_fcc_dialog_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_floating_font_weight_header", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_floating_opacity_header", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_floating_opacity_header_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_floating_size_header", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_history_export_dialog_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_history_help_dialog_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_refresh_dialog_current_value", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_temp_label_after_swap", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_temp_label_after_swap_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_voltage_dialog_title", + "module": "text", + "baseline_status": "passed" + } + ], + "ignored": [ + { + "name": "interaction::interaction_dark_mode_persists_process_death_vlm", + "module": "interaction", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "interaction::interaction_dual_power_doubled_vlm", + "module": "interaction", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "interaction::interaction_fab_expanded_stack_vlm", + "module": "interaction", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "interaction::interaction_monitor_checkbox_row_unchecked_vlm", + "module": "interaction", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "interaction::interaction_multiplier_persists_process_death_vlm", + "module": "interaction", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "interaction::interaction_show_fab_off_no_fab_vlm", + "module": "interaction", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "interaction::interaction_show_fab_on_fab_back_vlm", + "module": "interaction", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "navigation::nav_back_to_dashboard_endstate_vlm", + "module": "navigation", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "navigation::nav_history_tab_selected_vlm", + "module": "navigation", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "navigation::nav_history_toolbar_actions_vlm", + "module": "navigation", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "navigation::nav_reach_about_toolbar_vlm", + "module": "navigation", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "navigation::nav_reach_entry_settings_toolbar_vlm", + "module": "navigation", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "navigation::nav_reach_floating_toolbar_vlm", + "module": "navigation", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "navigation::nav_reach_monitor_entry_settings_vlm", + "module": "navigation", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "structure::structure_about_shape_vlm", + "module": "structure", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "structure::structure_calibrate_dialog_shape_vlm", + "module": "structure", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "structure::structure_fab_expand_shape_vlm", + "module": "structure", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "structure::structure_fab_position_vlm", + "module": "structure", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "structure::structure_floating_window_seekbars_vlm", + "module": "structure", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "structure::structure_gate_launch_vlm", + "module": "structure", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "structure::structure_history_tab_shape_vlm", + "module": "structure", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "structure::structure_monitor_entry_checkboxes_vlm", + "module": "structure", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + }, + { + "name": "structure::structure_settings_tab_shape_vlm", + "module": "structure", + "reason": "vlm_unverified", + "baseline_status": "passed", + "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case" + } + ], + "vlm_assertions": [ + { + "name": "computation::computation_current_divide_10p5_vlm", + "module": "computation", + "tag": "content" + }, + { + "name": "computation::computation_power_divide_10p3_vlm", + "module": "computation", + "tag": "content" + }, + { + "name": "states::states_radio_divide_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_dark_enable_dependency_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_dark_mode_light_baseline_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_dark_mode_dark_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_monitor_checkbox_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_floating_text_shadow_vlm", + "module": "states", + "tag": "layout" + }, + { + "name": "states::states_daily_log_toggle_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_showfab_consequence_vlm", + "module": "states", + "tag": "layout" + }, + { + "name": "text::text_temp_label_after_swap_vlm", + "module": "text", + "tag": "content" + }, + { + "name": "text::text_floating_opacity_header_vlm", + "module": "text", + "tag": "content" + } + ], + "vlm_total": 12, + "n_vlm_unverified": 23, + "vlm_log_found": true +} \ No newline at end of file diff --git a/android/dijia1124-plusplusbattery/vlm_assertions.json b/android/dijia1124-plusplusbattery/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..4d9bf95198fe66ad33884065a4b8c6b0350cc76d --- /dev/null +++ b/android/dijia1124-plusplusbattery/vlm_assertions.json @@ -0,0 +1,733 @@ +{ + "schema_version": 2, + "instance_id": "android/dijia1124-plusplusbattery", + "grading": { + "mode": "inline", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 35, + "with_verdict": 35, + "calibrated": 0, + "usable": null, + "scored_records": 35, + "unbacked_records": 23, + "unbacked_sample": [ + "interaction_multiplier_persists_process_death_vlm", + "interaction_dark_mode_persists_process_death_vlm", + "interaction_show_fab_off_no_fab_vlm", + "interaction_show_fab_on_fab_back_vlm", + "interaction_monitor_checkbox_row_unchecked_vlm", + "interaction_dual_power_doubled_vlm", + "interaction_fab_expanded_stack_vlm", + "nav_reach_monitor_entry_settings_vlm" + ] + }, + "assertions": [ + { + "id": "states_radio_divide_vlm", + "screenshot": "states_radio_divide_vlm.png", + "assertion": "In this dialog there are two radio buttons in a row labelled 'Multiply' (left) and 'Divide' (right). Is the RIGHT radio button (next to 'Divide') the one that is filled (a solid dot inside its ring), while the left one is an empty ring?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_radio_divide", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_dark_enable_dependency_vlm", + "screenshot": "states_dark_enable_dependency_vlm.png", + "assertion": "This is a settings screen with a 'Follow system theme' toggle (which is ON) directly above an 'Enable dark mode' row. Does the 'Enable dark mode' switch look greyed-out / dimmed / disabled (faded compared with the toggles above it)?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_dark_enable_dependency", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_dark_mode_light_baseline_vlm", + "screenshot": "states_dark_mode_light_baseline_vlm.png", + "assertion": "Is this screen's background light/white (a light theme) with dark text?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_dark_mode_light_baseline", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_dark_mode_dark_vlm", + "screenshot": "states_dark_mode_dark_vlm.png", + "assertion": "Is this app's background dark / near-black (a dark theme is active) with light-coloured text?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_dark_mode_dark", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_monitor_checkbox_vlm", + "screenshot": "states_monitor_checkbox_vlm.png", + "assertion": "This screen lists battery entries each with a checkbox on the left. Is the checkbox next to 'Battery Level' (the first row) an EMPTY square with NO tick/checkmark inside it?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_monitor_checkbox", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_floating_text_shadow_vlm", + "screenshot": "states_floating_text_shadow_vlm.png", + "assertion": "Does this screen show a settings toggle/switch on the right-hand side of a labelled row (for example a row labelled 'Text shadow' or 'Enable touch') — i.e. it renders real controls, not a blank screen?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "states_floating_text_shadow", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_daily_log_toggle_vlm", + "screenshot": "states_daily_log_toggle_vlm.png", + "assertion": "On this settings screen, is the switch on the 'Automatic daily charge cycle log' row turned ON — its track filled with an accent colour and its thumb pushed to the RIGHT?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_daily_log_toggle", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_showfab_consequence_vlm", + "screenshot": "states_showfab_consequence_vlm.png", + "assertion": "Is there a round floating action button in the bottom-right corner of this dashboard screen?", + "form": "question", + "expected": false, + "aspect": "layout", + "modality": null, + "links_to": "states_showfab_consequence", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_temp_label_after_swap_vlm", + "screenshot": "text_temp_label_after_swap_vlm.png", + "assertion": "Look at the 'Battery Temperature' row. Does its value read exactly '77.0°F' (a Fahrenheit temperature), rather than a Celsius value like '25.0°C'?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "text_temp_label_after_swap", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_floating_opacity_header_vlm", + "screenshot": "text_floating_opacity_header_vlm.png", + "assertion": "Does this screen show a settings label that reads exactly 'Opacity: 0.75'?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "text_floating_opacity_header", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_current_divide_10p5_vlm", + "screenshot": "computation_current_divide_10p5_vlm.png", + "assertion": "Look at the 'Battery Current' row. Is its value a SMALL number of just one or two characters (for example '9'), rather than a long six-digit number like '900000'?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "computation_current_divide_10p5", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_power_divide_10p3_vlm", + "screenshot": "computation_power_divide_10p3_vlm.png", + "assertion": "Look at the 'Battery Power' row. Is its value a SMALL decimal number like '4.50', rather than a large number like '4500'?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "computation_power_divide_10p3", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_multiplier_persists_process_death_vlm", + "screenshot": "interaction_multiplier_persists_process_death_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "interaction_multiplier_persists_process_death", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_dark_mode_persists_process_death_vlm", + "screenshot": "interaction_dark_mode_persists_process_death_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "interaction_dark_mode_persists_process_death", + "rigor": { + "jump_kind": "transition", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_show_fab_off_no_fab_vlm", + "screenshot": "interaction_show_fab_off_no_fab_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "interaction_show_fab_off_no_fab", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_show_fab_on_fab_back_vlm", + "screenshot": "interaction_show_fab_on_fab_back_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "interaction_show_fab_on_fab_back", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_monitor_checkbox_row_unchecked_vlm", + "screenshot": "interaction_monitor_checkbox_row_unchecked_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "interaction_monitor_checkbox_row_unchecked", + "rigor": { + "jump_kind": "transition", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_dual_power_doubled_vlm", + "screenshot": "interaction_dual_power_doubled_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "interaction_dual_power_doubled", + "rigor": { + "jump_kind": "transition", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_fab_expanded_stack_vlm", + "screenshot": "interaction_fab_expanded_stack_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "interaction_fab_expanded_stack", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_monitor_entry_settings_vlm", + "screenshot": "nav_reach_monitor_entry_settings_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "nav_reach_monitor_entry_settings", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_entry_settings_toolbar_vlm", + "screenshot": "nav_reach_entry_settings_toolbar_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "nav_reach_entry_settings_toolbar", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_floating_toolbar_vlm", + "screenshot": "nav_reach_floating_toolbar_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "nav_reach_floating_toolbar", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_reach_about_toolbar_vlm", + "screenshot": "nav_reach_about_toolbar_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "nav_reach_about_toolbar", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_history_tab_selected_vlm", + "screenshot": "nav_history_tab_selected_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "nav_history_tab_selected", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_history_toolbar_actions_vlm", + "screenshot": "nav_history_toolbar_actions_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "nav_history_toolbar_actions", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "nav_back_to_dashboard_endstate_vlm", + "screenshot": "nav_back_to_dashboard_endstate_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "nav_back_to_dashboard_endstate", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_gate_launch_vlm", + "screenshot": "structure_gate_launch_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_gate_launch", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_calibrate_dialog_shape_vlm", + "screenshot": "structure_calibrate_dialog_shape_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_calibrate_dialog_shape", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_fab_expand_shape_vlm", + "screenshot": "structure_fab_expand_shape_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_fab_expand_shape", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_fab_position_vlm", + "screenshot": "structure_fab_position_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_fab_position", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_settings_tab_shape_vlm", + "screenshot": "structure_settings_tab_shape_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_settings_tab_shape", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_history_tab_shape_vlm", + "screenshot": "structure_history_tab_shape_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_history_tab_shape", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_monitor_entry_checkboxes_vlm", + "screenshot": "structure_monitor_entry_checkboxes_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_monitor_entry_checkboxes", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_floating_window_seekbars_vlm", + "screenshot": "structure_floating_window_seekbars_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_floating_window_seekbars", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_about_shape_vlm", + "screenshot": "structure_about_shape_vlm.png", + "assertion": "", + "form": "statement", + "expected": true, + "aspect": null, + "modality": null, + "links_to": "structure_about_shape", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + } + ], + "merged_from_files": 1, + "source_shapes": { + "list": 1 + } +} \ No newline at end of file diff --git a/android/dimowner-audiorecorder/LICENCE b/android/dimowner-audiorecorder/LICENCE new file mode 100644 index 0000000000000000000000000000000000000000..b5f5c7fae801fade225b169bdd335dd354e3b277 --- /dev/null +++ b/android/dimowner-audiorecorder/LICENCE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2021 Dmytro Ponomarenko + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/android/dimowner-audiorecorder/instance.json b/android/dimowner-audiorecorder/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..d4cee4f0259128c812c7706d57c39360fb92df10 --- /dev/null +++ b/android/dimowner-audiorecorder/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "android/dimowner-audiorecorder", + "platform": "android", + "repo": "https://github.com/Dimowner/AudioRecorder", + "commit": "81dddfbb8a31868a5eae0fd1e9c5acb8744b8507", + "patches": [], + "package": "com.dimowner.audiorecorder.debug", + "license": null +} diff --git a/android/dimowner-audiorecorder/reference/launch.sh b/android/dimowner-audiorecorder/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8 --- /dev/null +++ b/android/dimowner-audiorecorder/reference/launch.sh @@ -0,0 +1,9 @@ +#!/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 1 diff --git a/android/dimowner-audiorecorder/tests/android_computation_eval.json b/android/dimowner-audiorecorder/tests/android_computation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..0dd41ce4a564fb2a97765aad832e9fa44e3b681f --- /dev/null +++ b/android/dimowner-audiorecorder/tests/android_computation_eval.json @@ -0,0 +1,151 @@ +{ + "module": "computation", + "total": 13, + "passed": 13, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 11, + "passed": 11, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 2, + "passed": 2, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.1818, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 13, + "depth_ge1": 6, + "depth_ge2": 2, + "value": 13, + "vlm_fine": 2 + }, + "results": [ + { + "test": "computation_record_timer_advances", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "big timer 00:00 -> increasing seconds (7s -> larger)" + }, + { + "test": "computation_record_size_grows", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "size grows (490.0 kB -> larger) on a '128 kbps, 44 kHz' line" + }, + { + "test": "computation_record_timer_starts_at_zero", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "idle big timer reads 00:00 (0 seconds)" + }, + { + "test": "computation_char_counter_updates", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "char counter 0/500 -> 5/500 after typing 'hello'" + }, + { + "test": "computation_char_counter_two_lengths", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "char counter reads 3/500 after typing 'abc'" + }, + { + "test": "computation_total_records_count_valid", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "'Total records count: N' parses to an int >= 11 visible rows" + }, + { + "test": "computation_total_duration_parseable", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "'Total recorded duration:' value '6m' is a number + time unit" + }, + { + "test": "computation_name_format_epoch_all_digits", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "one example name is an all-digits epoch stem + '.m4a'" + }, + { + "test": "computation_name_format_fixed_and_dated", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "'Record-1.m4a' present and >=1 date-and-time formatted '*.m4a' example" + }, + { + "test": "computation_playback_position_advances", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "playback position 00:00 -> increasing seconds (readings [2, 5, 8, 0, 0, 0])" + }, + { + "test": "computation_playback_stop_resets", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "big timer counted up during playback then reset to 00:00 on Stop" + }, + { + "test": "computation_recording_timeaxis_vlm", + "passed": true, + "message": "VLM: Q='While recording, is a horizontal time axis with numeric time labels (such as 00:00, 00:02, 00:04) drawn across the MIDDLE of the screen, left to right, above the large 00:0X timer?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: While recording, is a horizontal time axis with numeric time labels (such as 00:00, 00:02, 00:04) drawn across the MIDDLE of the screen, left to right, above the large 00:0X timer?", + "tag": "position" + }, + { + "test": "computation_recording_progress_line_vlm", + "passed": true, + "message": "VLM: Q='In the waveform area in the middle of the screen, is there a single bright coloured (yellow/orange) VERTICAL line marking the current recording position, standing out from the fainter grid marks?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: In the waveform area in the middle of the screen, is there a single bright coloured (yellow/orange) VERTICAL line marking the current recording position, standing out from the fainter grid marks?", + "tag": "color" + } + ] +} \ No newline at end of file diff --git a/android/dimowner-audiorecorder/tests/android_interaction_eval.json b/android/dimowner-audiorecorder/tests/android_interaction_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..857835137d2232f7e592160a6285d69e8d31c030 --- /dev/null +++ b/android/dimowner-audiorecorder/tests/android_interaction_eval.json @@ -0,0 +1,197 @@ +{ + "module": "interaction", + "total": 18, + "passed": 18, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 15, + "passed": 15, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 3, + "passed": 3, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.2, + "audit": { + "kit_api_version": 1, + "existence": 2, + "liveness": 0, + "interactive": 16, + "depth_ge1": 16, + "depth_ge2": 6, + "value": 15, + "vlm_fine": 3 + }, + "results": [ + { + "test": "interaction_create_persists", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Records row containing 'KitP54961100' present after force-stop+relaunch" + }, + { + "test": "interaction_create_increments_count", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Total records count 126->127" + }, + { + "test": "interaction_multi_record_integrity", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "rows contain 'KitB55149824' above 'KitA55108826' (both intact, newest first)" + }, + { + "test": "interaction_rename_home", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Home record name contains 'KitR55204986'" + }, + { + "test": "interaction_rename_persists", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Records row containing 'KitR55245345' present after force-stop+relaunch" + }, + { + "test": "interaction_rename_cross_surface", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "record name 'KitX55295109' present on Home AND in the Records list" + }, + { + "test": "interaction_context_menu_items", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Share/Information/Rename/Edit description/Open with…/Save as…/Delete all present" + }, + { + "test": "interaction_context_information", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Information screen shown with 'Name:' and 'File location:' labels" + }, + { + "test": "interaction_context_rename", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Records row name now contains 'KitC55400357' after context-menu Rename" + }, + { + "test": "interaction_context_edit_description", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Information screen shows the typed description 'Kitdesc55448168'" + }, + { + "test": "interaction_description_persists", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Information shows description 'Kitdp55508720' after force-stop+relaunch" + }, + { + "test": "interaction_bookmark_filter", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "row 'Record-129KiKitR55204986tB55149824KitC55400357KitX55295109KitR55245345' present after enabling the bookmark-only filter" + }, + { + "test": "interaction_bookmark_persists", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "row 'Record-129KiKitR55204986tB55149824KitC55400357KitX55295109KitR55245345' still bookmarked (shown under filter) after relaunch" + }, + { + "test": "interaction_sequence_record_info_back", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "returned to Home and row 'Record-129KiKitR55204986tB55149824KitC55400357KitX55295109KitR55245345' still listed after Info round-trip" + }, + { + "test": "interaction_row_starts_playback", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "tapping row 'Record-129' raises a Stop control (inline playback) on the Records screen" + }, + { + "test": "interaction_bookmark_icon_vlm", + "passed": true, + "message": "VLM: Q='On the first record row, is the bookmark icon (to the right of the record name, left of the 3-dot menu) drawn as a SOLID/FILLED bookmark shape rather than a hollow outline?' A=YES expect=YES", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: On the first record row, is the bookmark icon (to the right of the record name, left of the 3-dot menu) drawn as a SOLID/FILLED bookmark shape rather than a hollow outline?", + "tag": "shape" + }, + { + "test": "interaction_recording_cursor_vlm", + "passed": true, + "message": "VLM: Q='In the waveform area in the upper-middle of the screen, is there a bright YELLOW vertical line drawn (the recording position cursor), distinct from the darker background and the pale time-axis gridlines?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the waveform area in the upper-middle of the screen, is there a bright YELLOW vertical line drawn (the recording position cursor), distinct from the darker background and the pale time-axis gridlines?", + "tag": "color" + }, + { + "test": "interaction_playback_started_vlm", + "passed": true, + "message": "VLM: Q='Is the central round play/pause button now showing a PAUSE icon (two vertical bars) rather than a triangular play arrow, indicating playback is in progress?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is the central round play/pause button now showing a PAUSE icon (two vertical bars) rather than a triangular play arrow, indicating playback is in progress?", + "tag": "shape" + } + ] +} \ No newline at end of file diff --git a/android/dimowner-audiorecorder/tests/android_navigation_eval.json b/android/dimowner-audiorecorder/tests/android_navigation_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..4b72aa072cad2f78b2ecea9708a2e3713d8a84b8 --- /dev/null +++ b/android/dimowner-audiorecorder/tests/android_navigation_eval.json @@ -0,0 +1,218 @@ +{ + "module": "navigation", + "total": 20, + "passed": 20, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 14, + "passed": 14, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 6, + "passed": 6, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.4286, + "audit": { + "kit_api_version": 1, + "existence": 6, + "liveness": 0, + "interactive": 14, + "depth_ge1": 14, + "depth_ge2": 5, + "value": 0, + "vlm_fine": 4 + }, + "results": [ + { + "test": "navigation_reach_records", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Records subtitle 'By date (newest)' appeared; Home 'Import' gone" + }, + { + "test": "navigation_reach_records_vlm", + "passed": true, + "message": "VLM: Q='Does the top of this screen show two small horizontal-line sort/filter icons and a bookmark (ribbon) icon in a row at the top-right?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does the top of this screen show two small horizontal-line sort/filter icons and a bookmark (ribbon) icon in a row at the top-right?", + "tag": "position" + }, + { + "test": "navigation_reach_settings", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Settings row 'Dark theme' appeared; Home 'Import' gone" + }, + { + "test": "navigation_reach_settings_vlm", + "passed": true, + "message": "VLM: Q='Is this a settings screen showing a vertical list of labelled rows with pill-shaped ON/OFF toggle switches on the right side of some rows?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is this a settings screen showing a vertical list of labelled rows with pill-shaped ON/OFF toggle switches on the right side of some rows?", + "tag": "layout" + }, + { + "test": "navigation_reach_info_home", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Info label 'Record author' appeared; overflow 'Share' gone" + }, + { + "test": "navigation_chain_records_info", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Info 'Record author' appeared after leaving Records via the row menu" + }, + { + "test": "navigation_chain_records_info_vlm", + "passed": true, + "message": "VLM: Q='Does this detail screen show label/value pairs such as 'Format:' and 'Bitrate:' stacked vertically beneath a header?' A=YES expect=YES", + "depth": 3, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does this detail screen show label/value pairs such as 'Format:' and 'Bitrate:' stacked vertically beneath a header?", + "tag": "content" + }, + { + "test": "navigation_chain_settings_trash", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Trash empty-state 'permanently deleted' appeared; Settings 'Dark theme' gone" + }, + { + "test": "navigation_chain_settings_trash_vlm", + "passed": true, + "message": "VLM: Q='Does this screen show a large trash-can icon centered in the middle with a short message below it and no list of items?' A=YES expect=YES", + "depth": 2, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does this screen show a large trash-can icon centered in the middle with a short message below it and no list of items?", + "tag": "position" + }, + { + "test": "navigation_back_records_home", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Home 'Import' restored; Records 'By date' gone after one BACK" + }, + { + "test": "navigation_back_records_home_vlm", + "passed": true, + "message": "VLM: Q='Does this screen show a large round 'Record' button near the bottom center with a gear (settings) icon at the bottom-left?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Does this screen show a large round 'Record' button near the bottom center with a gear (settings) icon at the bottom-left?", + "tag": "position" + }, + { + "test": "navigation_back_settings_home", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Home 'Import' restored; Settings 'Dark theme' gone after one BACK" + }, + { + "test": "navigation_back_info_home", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Home 'Import' restored; Info 'Record author' gone after one BACK" + }, + { + "test": "navigation_backstack_unwind_2hop", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Trash->Settings then Settings->Home restored, one surface per BACK" + }, + { + "test": "navigation_backstack_records_info_unwind", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "Info->Records then Records->Home restored, one surface per BACK" + }, + { + "test": "navigation_info_reachable_two_paths", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "'Record author' Info surface reached from the Home overflow and from a Records row" + }, + { + "test": "navigation_settings_records_sibling", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "Records reached, BACK to Home, then Settings reached from the same Home" + }, + { + "test": "navigation_overflow_opens", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "'Information' menu item appeared over Home after tapping overflow" + }, + { + "test": "navigation_import_external_picker_vlm", + "passed": true, + "message": "VLM: Q='Is this a system file browser (light/white background) with a search magnifier icon at the top-right and a hamburger menu at the top-left, clearly different chrome from a dark audio-recorder app?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is this a system file browser (light/white background) with a search magnifier icon at the top-right and a hamburger menu at the top-left, clearly different chrome from a dark audio-recorder app?", + "tag": "color" + }, + { + "test": "navigation_import_external_picker", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "documentsui 'Show roots' appeared and the app left the foreground" + } + ] +} \ No newline at end of file diff --git a/android/dimowner-audiorecorder/tests/android_states_eval.json b/android/dimowner-audiorecorder/tests/android_states_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..ec6fb0c78b3625727a4b4c8a8adc67bbfe8d4317 --- /dev/null +++ b/android/dimowner-audiorecorder/tests/android_states_eval.json @@ -0,0 +1,237 @@ +{ + "module": "states", + "total": 22, + "passed": 22, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 15, + "passed": 15, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 7, + "passed": 7, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.4667, + "audit": { + "kit_api_version": 1, + "existence": 7, + "liveness": 0, + "interactive": 15, + "depth_ge1": 12, + "depth_ge2": 0, + "value": 5, + "vlm_fine": 7 + }, + "results": [ + { + "test": "states_dark_theme_on_vlm", + "passed": true, + "message": "VLM: Q='Is the whole screen background a very dark, near-black colour (dark theme), with light-coloured text on top of it?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is the whole screen background a very dark, near-black colour (dark theme), with light-coloured text on top of it?", + "tag": "color" + }, + { + "test": "states_dark_theme_off_vlm", + "passed": true, + "message": "VLM: Q='Is the whole screen background now a light, near-white colour (light theme), rather than dark?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is the whole screen background now a light, near-white colour (light theme), rather than dark?", + "tag": "color" + }, + { + "test": "states_dark_theme", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Dark theme switch on->off; background changed dark->light" + }, + { + "test": "states_dynamic_theme", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Dynamic theme colors switch off->on" + }, + { + "test": "states_dynamic_theme_on_vlm", + "passed": true, + "message": "VLM: Q='Look at the 'Dynamic theme colors' row. Is its toggle switch in the ON state — a filled blue/coloured track with the round thumb positioned on the RIGHT side?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Look at the 'Dynamic theme colors' row. Is its toggle switch in the ON state — a filled blue/coloured track with the round thumb positioned on the RIGHT side?", + "tag": "color" + }, + { + "test": "states_keep_screen_off_vlm", + "passed": true, + "message": "VLM: Q='Look at the 'Keep screen ON while recording' row. Is its toggle switch in the OFF state — a grey/unfilled track with the round thumb positioned on the LEFT side?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Look at the 'Keep screen ON while recording' row. Is its toggle switch in the OFF state — a grey/unfilled track with the round thumb positioned on the LEFT side?", + "tag": "color" + }, + { + "test": "states_keep_screen_on", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Keep screen ON switch off->on" + }, + { + "test": "states_keep_screen_persists", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Keep screen ON flipped to ON stays ON after force-stop+relaunch" + }, + { + "test": "states_show_rename_dialog", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "toggle OFF -> Stop shows NO 'Update name and description' dialog; toggle ON -> the dialog appears" + }, + { + "test": "states_sort_mode", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "toolbar sort subtitle 'By date (newest)' -> 'By name (A-Z)'" + }, + { + "test": "states_format_chip_wav_vlm", + "passed": true, + "message": "VLM: Q='In the 'Recording format:' chip row, does the 'Wav' chip have a small round CHECKMARK (tick) icon to the LEFT of the word 'Wav', marking it as the selected chip, while the '3gp' chip has no such checkmark?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the 'Recording format:' chip row, does the 'Wav' chip have a small round CHECKMARK (tick) icon to the LEFT of the word 'Wav', marking it as the selected chip, while the '3gp' chip has no such checkmark?", + "tag": "shape" + }, + { + "test": "states_format_chip", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Recording-settings summary leading token 'M4a...' -> 'Wav...'" + }, + { + "test": "states_bitrate_chip_96_vlm", + "passed": true, + "message": "VLM: Q='In the 'Bitrate:' chip row, does the '96 kbps' chip have a small round CHECKMARK (tick) icon to the LEFT of its label, marking it as the selected bitrate, while the '128 kbps' chip has no checkmark?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the 'Bitrate:' chip row, does the '96 kbps' chip have a small round CHECKMARK (tick) icon to the LEFT of its label, marking it as the selected bitrate, while the '128 kbps' chip has no checkmark?", + "tag": "shape" + }, + { + "test": "states_bitrate_chip", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Recording-settings summary '...128 kbps...' -> '...96 kbps...'" + }, + { + "test": "states_sample_rate_chip", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Recording-settings summary '...44.1kHz...' -> '...48kHz...'" + }, + { + "test": "states_channel_chip", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Recording-settings summary trailing token 'Stereo' -> 'Mono'" + }, + { + "test": "states_record_pause", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Record: label 'Pause'+Stop+'Recording…'+timer advancing; Pause: label 'Resume' and the timer stops advancing" + }, + { + "test": "states_record_resume", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Resume: label reverts to 'Pause' and the timer advances again" + }, + { + "test": "states_play_glyph_vlm", + "passed": true, + "message": "VLM: Q='In the middle of the screen, just below the waveform and above the large time display, there is a small playback-control icon. Is that icon a PAUSE symbol (two short vertical bars side by side), rather than a triangular play (▶) arrow?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the middle of the screen, just below the waveform and above the large time display, there is a small playback-control icon. Is that icon a PAUSE symbol (two short vertical bars side by side), rather than a triangular play (▶) arrow?", + "tag": "shape" + }, + { + "test": "states_play_stop", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Play: a 'Stop' button appears; Stop: it disappears and 'Play' returns" + }, + { + "test": "states_dialog_write_desc_checkbox", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "'Write description into the audio file' checkbox checked true->false" + }, + { + "test": "states_dialog_dont_ask_checkbox", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "'Don't ask again' checkbox checked false->true" + } + ] +} \ No newline at end of file diff --git a/android/dimowner-audiorecorder/tests/android_structure_eval.json b/android/dimowner-audiorecorder/tests/android_structure_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..f0a093123c3d9102e72e59fa45d49a336f41b772 --- /dev/null +++ b/android/dimowner-audiorecorder/tests/android_structure_eval.json @@ -0,0 +1,247 @@ +{ + "module": "structure", + "total": 23, + "passed": 23, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 15, + "passed": 15, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 8, + "passed": 8, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.5333, + "audit": { + "kit_api_version": 1, + "existence": 12, + "liveness": 0, + "interactive": 11, + "depth_ge1": 5, + "depth_ge2": 1, + "value": 3, + "vlm_fine": 8 + }, + "results": [ + { + "test": "structure_gate_launch", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_gate_top_bar", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_gate_bottom_bar", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_gate_bottom_bar_vlm", + "passed": true, + "message": "VLM: Q='At the very bottom of the screen, is there a control bar with a large light-blue circular 'Record' button in the center, a gear/settings icon at the far left, and a list icon at the far right?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: At the very bottom of the screen, is there a control bar with a large light-blue circular 'Record' button in the center, a gear/settings icon at the far left, and a list icon at the far right?", + "tag": "position" + }, + { + "test": "structure_gate_center_panel", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "" + }, + { + "test": "structure_gate_center_panel_vlm", + "passed": true, + "message": "VLM: Q='In the middle area of the screen, above the large blue 00:00 timer digits, is an audio waveform visualization drawn (either a small equalizer-style glyph of vertical bars, or a wider waveform with a horizontal time axis)?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: In the middle area of the screen, above the large blue 00:00 timer digits, is an audio waveform visualization drawn (either a small equalizer-style glyph of vertical bars, or a wider waveform with a horizontal time axis)?", + "tag": "shape" + }, + { + "test": "structure_record_starts_shape", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "content-desc 'Stop' absent on Home -> present while recording -> absent again after Stop+Cancel" + }, + { + "test": "structure_record_starts_shape_vlm", + "passed": true, + "message": "VLM: Q='Is a live recording waveform being drawn in the upper half of the screen, showing a horizontal time axis with numeric time labels (like 00:02, 00:04, 00:06) and a bright vertical playhead line?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a live recording waveform being drawn in the upper half of the screen, showing a horizontal time axis with numeric time labels (like 00:02, 00:04, 00:06) and a bright vertical playhead line?", + "tag": "shape" + }, + { + "test": "structure_recording_labels_shape", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "Home has no 'Recording…'/'Pause' keys; recording adds both" + }, + { + "test": "structure_stop_opens_dialog", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "EditText 0->2 & CheckBox 0->2 with 'Update name and description' layer on Stop; back to 0 on Cancel" + }, + { + "test": "structure_stop_opens_dialog_vlm", + "passed": true, + "message": "VLM: Q='Is a rounded rectangular dialog card overlaid on top of the screen, horizontally centered, containing a title and two text input boxes stacked vertically, with the dimmed app screen visible behind it?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a rounded rectangular dialog card overlaid on top of the screen, horizontally centered, containing a title and two text input boxes stacked vertically, with the dimmed app screen visible behind it?", + "tag": "position" + }, + { + "test": "structure_rename_dialog_shape", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "EditText 0->1 with 'Update name' layer on pencil; back to 0 on Cancel" + }, + { + "test": "structure_rename_dialog_shape_vlm", + "passed": true, + "message": "VLM: Q='Is a single rounded dialog card centered on the screen showing an 'Update name' title and exactly one text field prefilled with a record name, above 'Cancel' and 'Save' buttons?' A=YES expect=YES", + "depth": 0, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is a single rounded dialog card centered on the screen showing an 'Update name' title and exactly one text field prefilled with a record name, above 'Cancel' and 'Save' buttons?", + "tag": "position" + }, + { + "test": "structure_records_list_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Home (Play panel) -> Records adds {Navigate back, Filter} + 'Today' header + Record row subtree" + }, + { + "test": "structure_records_list_shape_vlm", + "passed": true, + "message": "VLM: Q='Is this a records list screen where recording entries are laid out as a vertical list of rows beneath a centered 'Today' date header near the top, each row starting with a record name at the left?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is this a records list screen where recording entries are laid out as a vertical list of rows beneath a centered 'Today' date header near the top, each row starting with a record name at the left?", + "tag": "position" + }, + { + "test": "structure_row_context_menu_shape", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "Records shows 0 context items -> 7 after row 3-dot -> 0 after BACK" + }, + { + "test": "structure_settings_list_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Home ~13 keys -> Settings adds toggle rows (Dark theme, Dynamic theme colors, Keep screen ON) and >=+8 discriminating keys" + }, + { + "test": "structure_settings_list_shape_vlm", + "passed": true, + "message": "VLM: Q='Is this a settings screen with multiple option rows stacked vertically, where the top rows each have a toggle switch aligned to the far right of the row?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Is this a settings screen with multiple option rows stacked vertically, where the top rows each have a toggle switch aligned to the far right of the row?", + "tag": "position" + }, + { + "test": "structure_settings_scroll_shape", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "transition", + "tier": 2, + "expect": "Settings key set changes >=3 keys on scroll-down; 'Dark theme' row returns on scroll-up" + }, + { + "test": "structure_settings_chips", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": ">=1 chip-group label + >=2 chip options among Settings descs" + }, + { + "test": "structure_settings_chips_vlm", + "passed": true, + "message": "VLM: Q='Under a 'Recording format:' label, are the format options ('M4a', 'Wav', '3gp') rendered as separate rounded pill-shaped chips laid out in a single horizontal row?' A=YES expect=YES", + "depth": 1, + "jump_kind": "none", + "tier": 0, + "expect": "VLM YES: Under a 'Recording format:' label, are the format options ('M4a', 'Wav', '3gp') rendered as separate rounded pill-shaped chips laid out in a single horizontal row?", + "tag": "shape" + }, + { + "test": "structure_overflow_menu_shape", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "menu items in tree <=1 -> 7 on Menu tap -> <=1 after BACK" + }, + { + "test": "structure_menu_layer_added", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "overflow adds >=4 new menu-item keys vs Home; removed on BACK" + } + ] +} \ No newline at end of file diff --git a/android/dimowner-audiorecorder/tests/android_testgen_kit.py b/android/dimowner-audiorecorder/tests/android_testgen_kit.py new file mode 100644 index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6 --- /dev/null +++ b/android/dimowner-audiorecorder/tests/android_testgen_kit.py @@ -0,0 +1,1910 @@ +#!/usr/bin/env python3 +"""Android TestGen Kit — the single source of every test helper, so a test's +NAVIGATION 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 package +name differs): always use the module-level PACKAGE (argv[1]). Never write a package +name, an .apk path, a /data/data path, or a pixel coordinate as a literal. + python3 android_testgen_kit.py lint_sources # flags all of those + +SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery): + python3 android_testgen_kit.py audit + python3 android_testgen_kit.py lint + python3 android_testgen_kit.py lint_sources + python3 android_testgen_kit.py audit_depth [results_dir] +""" +from __future__ import annotations + +import ast +import base64 +import functools +import glob +import hashlib +import json +import math +import os +import re +import shlex +import subprocess +import sys +import time +import urllib.error +import 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.0 +SETTLE = { + "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 /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 " list[dict]: + """XML -> list of attribute dicts, each with _bounds and _center.""" + nodes = [] + for m in re.finditer(r"]+?)/?>", 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} \n" + " android_testgen_kit.py audit_depth [results_dir]\n" + " android_testgen_kit.py score [manifest_dir]") diff --git a/android/dimowner-audiorecorder/tests/android_text_eval.json b/android/dimowner-audiorecorder/tests/android_text_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..25c26c71ad019d6450ca5a2a9032c22ddf48b4b7 --- /dev/null +++ b/android/dimowner-audiorecorder/tests/android_text_eval.json @@ -0,0 +1,214 @@ +{ + "module": "text", + "total": 20, + "passed": 20, + "failed": 0, + "pass_rate": 1.0, + "rule": { + "total": 18, + "passed": 18, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm": { + "total": 2, + "passed": 2, + "failed": 0, + "pass_rate": 1.0 + }, + "vlm_ratio": 0.1111, + "audit": { + "kit_api_version": 1, + "existence": 0, + "liveness": 0, + "interactive": 20, + "depth_ge1": 17, + "depth_ge2": 2, + "value": 15, + "vlm_fine": 1 + }, + "results": [ + { + "test": "text_records_title", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "toolbar title reads 'Records'" + }, + { + "test": "text_settings_title", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "toolbar title reads 'Settings'" + }, + { + "test": "text_information_title", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "reach", + "tier": 2, + "expect": "screen title reads 'Information'" + }, + { + "test": "text_trash_title", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "reach", + "tier": 2, + "expect": "screen title reads 'Trash'" + }, + { + "test": "text_trash_empty_message", + "passed": true, + "message": "", + "depth": 2, + "jump_kind": "value", + "tier": 3, + "expect": "empty-state message contains 'permanently deleted after 60 days'" + }, + { + "test": "text_rename_dialog_title", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "dialog title reads 'Update name'" + }, + { + "test": "text_recording_status", + "passed": true, + "message": "", + "depth": 0, + "jump_kind": "transition", + "tier": 2, + "expect": "a status TextView reads 'Recording…' while recording" + }, + { + "test": "text_sort_subtitle_default", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "default sort subtitle reads 'By date (newest)'" + }, + { + "test": "text_sort_subtitle_byname", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "sort subtitle updates to 'By name (A-Z)'" + }, + { + "test": "text_info_labels", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Info shows labels Name:/Format:/Bitrate:/Channel count:/Sample rate:/Duration:/Size:/File location:" + }, + { + "test": "text_info_format_value", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Format value reads 'm4a'" + }, + { + "test": "text_info_channel_mono", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Channel count value reads 'Mono'" + }, + { + "test": "text_info_file_ext", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "the file-location value ends with '.m4a'" + }, + { + "test": "text_menu_labels_core", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "menu shows Share, Information, Rename" + }, + { + "test": "text_menu_labels_ellipsis", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "menu shows 'Edit description', 'Open with…', 'Save as…'" + }, + { + "test": "text_settings_section_labels", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Settings shows section headers Recording format:/Sample rate:/Bitrate:/Channel count:" + }, + { + "test": "text_settings_chip_labels", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "Settings recording-format chips read M4a, Wav, 3gp" + }, + { + "test": "text_desc_counter_suffix", + "passed": true, + "message": "", + "depth": 1, + "jump_kind": "value", + "tier": 3, + "expect": "description dialog char counter contains '/500'" + }, + { + "test": "text_waveform_axis_labels_vlm", + "passed": true, + "message": "VLM: Q='Along the horizontal waveform strip in the middle of the screen, are there small numeric time labels in mm:ss format such as '00:02', '00:04', '00:06'?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Along the horizontal waveform strip in the middle of the screen, are there small numeric time labels in mm:ss format such as '00:02', '00:04', '00:06'?", + "tag": "content" + }, + { + "test": "text_waveform_axis_row_vlm", + "passed": true, + "message": "VLM: Q='Are numeric mm:ss time labels (like '00:02', '00:04') arranged in a horizontal row across the CENTER waveform region of the screen, rather than at the very top title area or the bottom button bar?' A=YES expect=YES", + "depth": 0, + "jump_kind": "value", + "tier": 3, + "expect": "VLM YES: Are numeric mm:ss time labels (like '00:02', '00:04') arranged in a horizontal row across the CENTER waveform region of the screen, rather than at the very top title area or the bottom button bar?", + "tag": "position" + } + ] +} \ No newline at end of file diff --git a/android/dimowner-audiorecorder/tests/conftest.py b/android/dimowner-audiorecorder/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27 --- /dev/null +++ b/android/dimowner-audiorecorder/tests/conftest.py @@ -0,0 +1 @@ +pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"] diff --git a/android/dimowner-audiorecorder/tests/requirements.txt b/android/dimowner-audiorecorder/tests/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c --- /dev/null +++ b/android/dimowner-audiorecorder/tests/requirements.txt @@ -0,0 +1,2 @@ +pytest +pillow diff --git a/android/dimowner-audiorecorder/tests/test_android_computation.py b/android/dimowner-audiorecorder/tests/test_android_computation.py new file mode 100644 index 0000000000000000000000000000000000000000..5470df1ddc1c15bb246616af6d55e79743211f16 --- /dev/null +++ b/android/dimowner-audiorecorder/tests/test_android_computation.py @@ -0,0 +1,756 @@ +#!/usr/bin/env python3 +"""COMPUTATION lane — CORE FUNCTION input->output, the VALUE that CHANGED, for +AudioRecorder. + +Every test is TRIGGER -> an OBSERVED value that changed on the running original, +so this file is the sole owner of jump_kind="value" for this app. It covers the +app's genuine input->output surfaces: + + * the big recording timer counts UP from 00:00 (mm:ss parsed to seconds; later + strictly greater than earlier); + * the live recording size (kB) grows while recording; + * the "Update name and description" dialog's char counter goes 0/500 -> N/500 + as text is typed into the Description field; + * Settings "Total records count: N" is a parseable count consistent with the + real records that exist; + * the "Record name format" dialog's epoch-timestamp example has an all-digits + stem, while the fixed "Record-1.m4a" option is exact and a date option matches + a structural (never date-hardcoded) shape; + * playback position counts UP from 00:00 on the big timer and resets on Stop. + +Every asserted value is one OBSERVED on the original emulator, never derived from +source or computed by arithmetic. Values are dump-readable, so only the rendered- +only waveform canvas (which never reaches the view tree) uses the VLM — exactly +two vlm_assert records, both testing a specific rendered property. + +Package comes from argv[1]; never a literal. Read-only kit. +""" +import os +import re +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ── shared helpers ────────────────────────────────────────────────────────────── + +def _big_timer(nodes): + """The large central mm:ss timer TextView (recording elapsed / playback + position). Chosen by shape: a "MM:SS" text in the tallest (largest-font) + TextView box, never by a literal coordinate.""" + cands = [] + for n in nodes: + if not n.get("class", "").endswith("TextView"): + continue + t = n.get("text", "").strip() + if not re.fullmatch(r"\d{1,2}:\d{2}", t): + continue + b = n.get("_bounds") + if not b: + continue + cands.append((b[3] - b[1], n)) # box height + if not cands: + return None + cands.sort(key=lambda x: x[0], reverse=True) # tallest box = big timer + return cands[0][1] + + +def _mmss_to_seconds(t: str): + """'01:23' -> 83. None when not an mm:ss string.""" + m = re.fullmatch(r"\s*(\d{1,2}):(\d{2})\s*", t or "") + return int(m.group(1)) * 60 + int(m.group(2)) if m else None + + +def _format_line(nodes) -> str: + """The ', m4a, , ' format TextView text ("" if none).""" + for n in nodes: + t = n.get("text", "") + if "m4a" in t and "kHz" in t: + return t + return "" + + +def _size_kb(text: str): + """Extract the leading kB (or MB->kB) number from a format line. None if absent.""" + m = re.search(r"([\d.]+)\s*kB", text) + if m: + try: + return float(m.group(1)) + except ValueError: + return None + m = re.search(r"([\d.]+)\s*MB", text) + if m: + try: + return float(m.group(1)) * 1024.0 + except ValueError: + return None + return None + + +def _counter_value(nodes): + """Parse 'N/500' char counter -> N. None if absent.""" + for n in nodes: + m = re.fullmatch(r"\s*(\d+)\s*/\s*500\s*", n.get("text", "")) + if m: + return int(m.group(1)) + return None + + +def _start_recording() -> bool: + """Tap the Home 'Record' control and confirm recording started (a 'Stop' + control appears). Assumes Home is showing.""" + rec = find_node(ui(), text="Record") or find_node_ci(ui(), "Record") + if rec is None or not tap_node(rec): + return False + settle("tap") + return find_node(ui(), content_desc="Stop") is not None + + +def _stop_recording_and_cleanup() -> None: + """Stop an active recording and dismiss the post-record dialog WITHOUT deleting + anything (Cancel keeps the file but closes the dialog). Safe to call from any + recording/dialog state; never taps Delete.""" + stop = find_node(ui(), content_desc="Stop") + if stop is not None: + tap_node(stop) + settle("tap") + if keyboard_visible(): + hide_keyboard() + for _ in range(2): + nodes = ui() + if find_node_ci(nodes, "Update name and description") is None: + return + c = find_node(nodes, text="Cancel") or find_node_ci(nodes, "Cancel") + if c is not None and is_safe(c): + tap_node(c) + settle("tap") + else: + return + + +def _switch_is_on(row_label, save_path): + """Compose exposes NOTHING through the `checked` attribute for these Settings + switches (every node reads checked="false"), so the toggle state must be read + from the RENDERED SWITCH PIXEL. A Compose switch that is ON shows a blue thumb + shifted to the right; read a track pixel at x = 0.885*width, y = row center and + call it ON when (b - r) > 40. Returns True / False / None (None => unreadable, + e.g. row not found or PIL missing — in which case we don't tap, and the ON + default stands).""" + n = find_node(ui(), text=row_label) + if not n or "_center" not in n: + return None + if not screencap(save_path): + return None + try: + from PIL import Image + im = Image.open(save_path).convert("RGB") + except Exception: + return None + s = get_screen_info() + r, g, b = im.getpixel((int(s["width"] * 0.885), n["_center"][1])) + return (b - r) > 40 + + +def _tap_switch(row_label): + """Flip the toggle by tapping the far-right switch (x = 0.93*width — the label + itself is NOT the clickable target). The x factor is derived from the live + screen width, never a literal pixel.""" + n = find_node(ui(), text=row_label) + if not n or "_center" not in n: + return False + s = get_screen_info() + tap(int(s["width"] * 0.93), n["_center"][1]) + settle("tap") + return True + + +def and_ensure_rename_dialog_on(): + """Guarantee the Settings toggle 'Show rename dialog after recording is + completed' is ON, then return to Home, so a later Stop reliably raises the + post-record 'Update name and description' dialog. The FULL eval suite runs the + six lanes SEQUENTIALLY on one emulator and a sibling lane may leave this OFF, + so we cannot rely on the default — we read the rendered switch pixel and only + tap when we positively read OFF. Assumes we start on Home.""" + s = find_node(ui(), content_desc="Settings") + if not (s and tap_node(s)): + return False + settle("tap") + label = "Show rename dialog after recording is completed" + scroll_into_view(label) + path = os.path.join(RESULTS_DIR, "screenshots", "_comp_ensure.png") + cur = _switch_is_on(label, path) + if cur is False: # only tap when we positively read OFF + _tap_switch(label) + b = find_node(ui(), content_desc="Navigate back") + if b: + tap_node(b) + settle("tap") + wait_for_foreground() + return True + + +def and_reach_record_dialog() -> bool: + """Home -> Record -> (accumulate audio) -> Stop -> the 'Update name and + description' dialog. Backs a depth>=1 claim via the and_reach_* name; returns + True when the dialog's char counter is present. + + FIRST guarantees the 'Show rename dialog after recording is completed' setting + is ON: the full suite runs lanes sequentially and a sibling lane may have left + it OFF, in which case Stop would save silently with no dialog. We start from + Home (where restart_app leaves us), flip the setting on if needed, return to + Home, and only then record.""" + and_ensure_rename_dialog_on() + if not _start_recording(): + return False + time.sleep(1.4) # let audio accumulate before stopping + stop = find_node(ui(), content_desc="Stop") + if stop is None or not tap_node(stop): + return False + settle("tap") + if _counter_value(ui()) is not None or find_by_class(ui(), "EditText"): + and_enter("post_record_dialog") + return True + return False + + +def _description_field(nodes): + """The Description EditText is the LOWER (larger-y) of the dialog's two + EditTexts; the Rename field is the upper one. Chosen by y-order, not index.""" + edits = sorted(find_by_class(nodes, "EditText"), + key=lambda n: n.get("_center", (0, 0))[1]) + if not edits: + return None + return edits[-1] if len(edits) >= 2 else edits[0] + + +def _type_into_description(word: str) -> bool: + """Focus the Description field and type `word` into it, ROBUSTLY. + + The dialog has two look-alike EditTexts (Rename above, Description below) and + Compose does not always report focused=true up front, so the kit's default + focus-re-match can land text in the wrong field. We tap the lower field's + centre directly, confirm from a fresh dump that the LOWER EditText now reports + focused=true, then type with verify_focus=False so the kit does not re-select + the ambiguous node. Returns True when the lower field held focus before typing.""" + fld = _description_field(ui()) + if fld is None: + return False + if not tap_node(fld): + return False + settle("keyboard") + lower = _description_field(ui()) + focused = bool(lower and lower.get("focused") == "true") + target = lower or fld + type_text(target, word, verify_focus=False) + return focused + + +def _sample_positions(taps: int = 6): + """Sample the big timer `taps` times in immediate succession (each ui() dump + is ~1s, so this spans several seconds). Returns the list of seconds readings — + used to prove the playback position ADVANCED even for a short record that + finishes and resets to 0 partway through the sample.""" + out = [] + for _ in range(taps): + n = _big_timer(ui()) + out.append(_mmss_to_seconds(n.get("text", "")) if n else None) + return out + + +def _has_increasing_pair(seq) -> bool: + """True if the sequence contains a strictly-increasing consecutive pair before + it drops back toward zero (i.e. the value was observed to count up).""" + prev = None + for s in seq: + if s is None: + continue + if prev is not None and s > prev: + return True + if prev is not None and prev > 0 and s == 0: + break # playback ended and reset; stop + prev = s + return False + + +def and_reach_settings(): + """Home -> Settings. Backs a depth>=1 claim via the and_reach_* name.""" + s = find_node(ui(), content_desc="Settings") + if s is None or not tap_node(s): + return False + settle("tap") + if find_node_ci(ui(), "Settings") is None and scroll_into_view("Trash") is None: + return False + and_enter("settings") + return True + + +def and_reach_records(): + """Home -> Records list. Backs a depth>=1 claim via the and_reach_* name.""" + n = find_node(ui(), content_desc="Records") + if n is None or not tap_node(n): + return False + settle("tap") + and_enter("records") + return True + + +def _record_row_names(nodes): + """Distinct record-name rows visible in the Records list (below the toolbar).""" + seen, out = set(), [] + for n in sorted([x for x in nodes + if x.get("class", "").endswith("TextView") + and x.get("text", "").startswith("Record") + and x.get("_center", (0, 9999))[1] > 380], + key=lambda n: n["_center"][1]): + t = n.get("text", "") + if t not in seen: + seen.add(t) + out.append(t) + return out + + +def and_reach_name_format_dialog() -> bool: + """Settings -> tap the 'Record name format' selector -> Dialog C of example + names. Backs a depth>=2 claim (Settings + dialog). Returns True when at least + one '*.m4a' example is listed.""" + if not and_reach_settings(): + return False + row = scroll_into_view("Record name format") + if row is None: + return False + if not tap_node(row): + return False + settle("tap") + and_enter("name_format_dialog") + return any(n.get("text", "").endswith(".m4a") for n in ui()) + + +def _m4a_options(nodes): + """All '*.m4a' example strings currently listed (the name-format dialog rows).""" + return [n.get("text", "") for n in nodes + if n.get("text", "").endswith(".m4a")] + + +# ══════════════════════════════════════════════════════════════════════════════ +# Recording timer — counts UP from 00:00 +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_record_timer_advances",)) +def test_record_timer_advances(): + """CORE: tapping Record makes the big timer count UP. Observe the timer twice + (~2.5s apart) while recording and assert the later reading, parsed mm:ss -> + seconds, is STRICTLY GREATER than the earlier one. Positive/negative pair: the + timer reads 00:00 (0s) before recording and a larger value after.""" + restart_app() + wait_for_foreground() + idle = _big_timer(ui()) + idle_txt = idle.get("text", "") if idle else "" + idle_sec = _mmss_to_seconds(idle_txt) + if not _start_recording(): + record("computation_record_timer_advances", False, + "feature_missing: could not start recording (no Stop control appeared)", + depth=0, jump_kind="value", expect="big timer seconds increase while recording") + return + n1 = _big_timer(ui()) + t1 = _mmss_to_seconds(n1.get("text", "")) if n1 else None + time.sleep(2.6) + n2 = _big_timer(ui()) + t2 = _mmss_to_seconds(n2.get("text", "")) if n2 else None + _stop_recording_and_cleanup() + ok = (idle_sec == 0 and t1 is not None and t2 is not None and t2 > t1) + record("computation_record_timer_advances", ok, + "" if ok else f"behavior_wrong: timer idle={idle_txt!r} then " + f"t1={t1}s t2={t2}s (expected 0 then strictly increasing)", + depth=0, jump_kind="value", + expect=f"big timer 00:00 -> increasing seconds ({t1}s -> larger)") + + +@and_test(expects=("computation_record_size_grows",)) +def test_record_size_grows(): + """CORE: the live recording format line reports a size that GROWS. While + recording, read the kB from ', m4a, 128 kbps, 44 kHz' twice ~2.5s apart + and assert the second is strictly larger. Also confirms the recording bitrate + the ORIGINAL reports on this line ('128 kbps') as part of the observed value.""" + restart_app() + wait_for_foreground() + if not _start_recording(): + record("computation_record_size_grows", False, + "feature_missing: could not start recording (no Stop control appeared)", + depth=0, jump_kind="value", expect="recording size (kB) increases over time") + return + line1 = _format_line(ui()) + kb1 = _size_kb(line1) + time.sleep(2.6) + line2 = _format_line(ui()) + kb2 = _size_kb(line2) + has_rec_bitrate = "128 kbps" in line2 and "44 kHz" in line2 + _stop_recording_and_cleanup() + ok = (kb1 is not None and kb2 is not None and kb2 > kb1 and has_rec_bitrate) + record("computation_record_size_grows", ok, + "" if ok else f"behavior_wrong: size {kb1}->{kb2} kB (line2={line2!r}); " + f"expected growth on a '…128 kbps, 44 kHz' line", + depth=0, jump_kind="value", + expect=f"size grows ({kb1} kB -> larger) on a '128 kbps, 44 kHz' line") + + +@and_test(expects=("computation_record_timer_starts_at_zero",)) +def test_record_timer_present_and_zero_idle(): + """Negative/positive edge: on a freshly launched Home the big timer reads + exactly 00:00 (0 seconds) BEFORE any Record tap — the answer is ABSENT (no + elapsed time) before the operation, which the advance test proves PRESENT + after. Guards against a recreation that shows a stale non-zero timer at idle.""" + restart_app() + wait_for_foreground() + n = _big_timer(ui()) + txt = n.get("text", "") if n else "" + sec = _mmss_to_seconds(txt) + ok = (n is not None and sec == 0) + record("computation_record_timer_starts_at_zero", ok, + "" if ok else f"behavior_wrong: idle big timer reads {txt!r} (expected '00:00')", + depth=0, jump_kind="value", expect="idle big timer reads 00:00 (0 seconds)") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Char counter — 0/500 -> N/500 as you type +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_char_counter_updates",)) +def test_char_counter_updates(): + """CORE: the Description field's char counter is an input->output derivation. + Reach the post-record dialog, observe the counter reads 0 (0/500) with the + field empty, type a 5-char ASCII word, and assert the counter now reads 5 + (5/500). Positive/negative: 0 before typing, exactly len(text) after.""" + restart_app() + wait_for_foreground() + if not and_reach_record_dialog(): + record("computation_char_counter_updates", False, + "feature_missing: could not reach the post-record dialog (Record->Stop)", + depth=1, jump_kind="value", expect="char counter 0/500 -> 5/500") + return + before = _counter_value(ui()) + word = "hello" # 5 ASCII chars + focused = _type_into_description(word) + if keyboard_visible(): + hide_keyboard() + after = _counter_value(ui()) + _stop_recording_and_cleanup() + ok = (before == 0 and after == len(word)) + record("computation_char_counter_updates", ok, + "" if ok else f"behavior_wrong: counter {before}/500 -> {after}/500 " + f"after typing {len(word)} chars into Description " + f"(focused={focused}); expected 0 -> {len(word)}", + depth=1, jump_kind="value", + expect=f"char counter 0/500 -> {len(word)}/500 after typing '{word}'") + + +@and_test(expects=("computation_char_counter_two_lengths",)) +def test_char_counter_reflects_length(): + """CORE (stronger): the counter equals the EXACT typed length, not a fixed + increment. In the post-record dialog type a 3-char word and assert the counter + reads 3 (3/500) — a value derived from the input, distinct from the 5-char + case, so a recreation cannot hardcode one answer.""" + restart_app() + wait_for_foreground() + if not and_reach_record_dialog(): + record("computation_char_counter_two_lengths", False, + "feature_missing: could not reach the post-record dialog (Record->Stop)", + depth=1, jump_kind="value", expect="char counter reads 3/500 for a 3-char input") + return + word = "abc" # 3 ASCII chars + focused = _type_into_description(word) + if keyboard_visible(): + hide_keyboard() + after = _counter_value(ui()) + _stop_recording_and_cleanup() + ok = (after == len(word)) + record("computation_char_counter_two_lengths", ok, + "" if ok else f"behavior_wrong: counter reads {after}/500 after typing " + f"{len(word)} chars into Description (focused={focused}); " + f"expected {len(word)}", + depth=1, jump_kind="value", + expect=f"char counter reads {len(word)}/500 after typing '{word}'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Total records count — reflects reality +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_total_records_count_valid",)) +def test_total_records_count_is_valid_integer(): + """CORE: Settings shows 'Total records count: N', a value DERIVED from the DB. + Assert N parses to a non-negative integer AND is >= the number of distinct + record rows actually visible in the Records list (the count cannot claim fewer + records than exist). Ground truth = what the two screens show, not arithmetic.""" + restart_app() + wait_for_foreground() + visible = 0 + if and_reach_records(): + visible = len(_record_row_names(ui())) + restart_app() + wait_for_foreground() + and_reset_depth() + if not and_reach_settings(): + record("computation_total_records_count_valid", False, + "setup_failed: could not open Settings to read the count", + depth=1, jump_kind="value", expect="'Total records count: N' is a valid integer >= visible rows") + return + node = scroll_into_view("Total records count") + if node is None: + node = next((n for n in ui() + if n.get("text", "").startswith("Total records count")), None) + if node is None: + record("computation_total_records_count_valid", False, + "feature_missing: no 'Total records count' info line in Settings", + depth=1, jump_kind="value", expect="'Total records count: N' is a valid integer >= visible rows") + return + m = re.search(r"(\d+)", node.get("text", "")) + n = int(m.group(1)) if m else None + ok = (n is not None and n >= 0 and n >= visible) + record("computation_total_records_count_valid", ok, + "" if ok else f"behavior_wrong: count={n} but at least {visible} rows are " + f"visible in the list (count must reflect reality)", + depth=1, jump_kind="value", + expect=f"'Total records count: N' parses to an int >= {visible} visible rows") + + +@and_test(expects=("computation_total_duration_parseable",)) +def test_total_recorded_duration_parseable(): + """CORE: Settings shows 'Total recorded duration: ', a derived summary. + Assert it exists and its value carries a time unit (m / h / s / min) — a + non-empty derived string, not a raw placeholder. Value asserted = the shape + OBSERVED ('3m'-style), never a hardcoded number that drifts as records change.""" + restart_app() + wait_for_foreground() + if not and_reach_settings(): + record("computation_total_duration_parseable", False, + "setup_failed: could not open Settings", + depth=1, jump_kind="value", expect="'Total recorded duration:' shows a time value") + return + node = scroll_into_view("Total recorded duration") + if node is None: + node = next((n for n in ui() + if n.get("text", "").startswith("Total recorded duration")), None) + if node is None: + record("computation_total_duration_parseable", False, + "feature_missing: no 'Total recorded duration' info line in Settings", + depth=1, jump_kind="value", expect="'Total recorded duration:' shows a time value") + return + txt = node.get("text", "") + value = txt.split(":", 1)[1].strip() if ":" in txt else "" + ok = bool(re.search(r"\d", value)) and bool(re.search(r"\b\d+\s*(?:s|m|h|min)\b", value)) + record("computation_total_duration_parseable", ok, + "" if ok else f"behavior_wrong: duration value {value!r} is not a parseable " + f"time (expected a number + unit like '3m')", + depth=1, jump_kind="value", + expect=f"'Total recorded duration:' value {value!r} is a number + time unit") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Record name format — live-formatted example names (structure, never a date) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_name_format_epoch_all_digits",)) +def test_name_format_epoch_all_digits(): + """CORE: the 'Record name format' dialog lists live-formatted example names. + One is a pure epoch-ms timestamp + '.m4a'. Assert at least one option has an + all-digits stem (>= 10 digits, i.e. an epoch), proving the timestamp formatter + derives a numeric name. Dates are dynamic, so only STRUCTURE is asserted.""" + restart_app() + wait_for_foreground() + if not and_reach_name_format_dialog(): + record("computation_name_format_epoch_all_digits", False, + "feature_missing: could not open the 'Record name format' dialog", + depth=2, jump_kind="value", expect="one example has an all-digits (epoch) stem + .m4a") + return + opts = _m4a_options(ui()) + epoch_like = [o for o in opts if re.fullmatch(r"\d{10,}\.m4a", o)] + back() # dismiss dialog without changing the setting + ok = len(epoch_like) >= 1 + record("computation_name_format_epoch_all_digits", ok, + "" if ok else f"behavior_wrong: no all-digits epoch example among {opts}", + depth=2, jump_kind="value", + expect="one example name is an all-digits epoch stem + '.m4a'") + + +@and_test(expects=("computation_name_format_fixed_and_dated",)) +def test_name_format_fixed_and_date_options(): + """CORE: the same dialog offers the FIXED counter name and a DATE-based name. + Assert one option equals exactly 'Record-1.m4a' (the counter format) and at + least one other matches a date-and-time shape (digits/separators + time + + '.m4a') — a derived, live-formatted value. The date itself is NEVER + hardcoded; only the structural regex is asserted.""" + restart_app() + wait_for_foreground() + if not and_reach_name_format_dialog(): + record("computation_name_format_fixed_and_dated", False, + "feature_missing: could not open the 'Record name format' dialog", + depth=2, jump_kind="value", expect="'Record-1.m4a' plus a date-formatted example present") + return + opts = _m4a_options(ui()) + has_fixed = "Record-1.m4a" in opts + date_re = re.compile(r"^[\d.\- ]*\d{2}\.\d{2}\.\d{2}(?:AM|PM)?\.m4a$") + dated = [o for o in opts if date_re.match(o) and not re.fullmatch(r"\d{10,}\.m4a", o)] + back() # dismiss dialog without changing the setting + ok = has_fixed and len(dated) >= 1 + record("computation_name_format_fixed_and_dated", ok, + "" if ok else f"behavior_wrong: fixed_present={has_fixed} dated={dated} " + f"among {opts}", + depth=2, jump_kind="value", + expect="'Record-1.m4a' present and >=1 date-and-time formatted '*.m4a' example") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Playback position — counts UP from 00:00, resets on Stop +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_playback_position_advances",)) +def test_playback_position_advances(): + """CORE: playing a loaded record makes the big timer show a position that + counts UP. Tap Play, sample the position several times, and assert a strictly- + increasing consecutive pair was observed before any reset (robust to a short + record that finishes mid-sample). Positive/negative: 0 (00:00) before Play, + a larger value observed after.""" + restart_app() + wait_for_foreground() + play = find_node(ui(), content_desc="Play") + if play is None: + record("computation_playback_position_advances", False, + "feature_missing: no loaded record / Play control on Home", + depth=0, jump_kind="value", expect="playback position seconds increase from 00:00") + return + start = _big_timer(ui()) + start_sec = _mmss_to_seconds(start.get("text", "")) if start else None + tap_node(play) + readings = _sample_positions(6) + stop = find_node(ui(), content_desc="Stop") + if stop is not None: + tap_node(stop) + settle("tap") + advanced = _has_increasing_pair(readings) + ok = (start_sec == 0 and advanced) + record("computation_playback_position_advances", ok, + "" if ok else f"behavior_wrong: start={start_sec}s readings={readings} " + f"(expected 0 then an increasing pair)", + depth=0, jump_kind="value", + expect=f"playback position 00:00 -> increasing seconds (readings {readings})") + + +@and_test(expects=("computation_playback_stop_resets",)) +def test_playback_stop_resets_position(): + """CORE round-trip: after playing (position observed > 0), tapping Stop resets + the big timer back to 00:00. Read the position quickly right after Play (so a + short record is still playing), Stop, and assert it reads exactly 0 (00:00) + afterwards — the value returns to its known state.""" + restart_app() + wait_for_foreground() + play = find_node(ui(), content_desc="Play") + if play is None: + record("computation_playback_stop_resets", False, + "feature_missing: no loaded record / Play control on Home", + depth=0, jump_kind="value", expect="position >0 while playing, 00:00 after Stop") + return + tap_node(play) + # sample quickly to capture a >0 position before a short record can finish + seen_positive = 0 + for _ in range(3): + n = _big_timer(ui()) + s = _mmss_to_seconds(n.get("text", "")) if n else None + if s and s > 0: + seen_positive = s + break + stop = find_node(ui(), content_desc="Stop") + if stop is None or not tap_node(stop): + record("computation_playback_stop_resets", False, + "feature_missing: no Stop control appeared during playback", + depth=0, jump_kind="value", expect="position >0 while playing, 00:00 after Stop") + return + settle("tap") + after = _big_timer(ui()) + after_sec = _mmss_to_seconds(after.get("text", "")) if after else None + ok = (seen_positive > 0 and after_sec == 0) + record("computation_playback_stop_resets", ok, + "" if ok else f"behavior_wrong: playing_pos={seen_positive}s then after " + f"Stop={after_sec}s (expected >0 then 0)", + depth=0, jump_kind="value", + expect="big timer counted up during playback then reset to 00:00 on Stop") + + +# ══════════════════════════════════════════════════════════════════════════════ +# VLM (exactly two) — rendered-only waveform canvas that never reaches the tree +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("computation_recording_timeaxis_vlm",)) +def test_recording_time_axis_vlm(): + """While recording, the waveform canvas renders a horizontal TIME AXIS with + numeric labels (00:00, 00:02, 00:04 …) — a rendered-only property (the axis is + drawn on a canvas, never in the view tree). Asserts a POSITION property: the + axis labels run left-to-right across the middle of the screen.""" + restart_app() + wait_for_foreground() + if not _start_recording(): + record("computation_recording_timeaxis_vlm", False, + "feature_missing: could not start recording (no Stop control appeared)", + depth=0, jump_kind="value", tag="position") + return + time.sleep(2.2) # let the axis populate with labels + passed = vlm_assert( + "computation_recording_timeaxis", + "While recording, is a horizontal time axis with numeric time labels " + "(such as 00:00, 00:02, 00:04) drawn across the MIDDLE of the screen, " + "left to right, above the large 00:0X timer?", + expect="YES", depth=0, jump_kind="value", tag="position") + _stop_recording_and_cleanup() + return passed + + +@and_test(expects=("computation_recording_progress_line_vlm",)) +def test_recording_progress_line_vlm(): + """While recording, a bright vertical PROGRESS cursor (a yellow/coloured + vertical line) is drawn on the waveform, distinct from the darker grid ticks — + a rendered-only COLOR property that never reaches the view tree.""" + restart_app() + wait_for_foreground() + if not _start_recording(): + record("computation_recording_progress_line_vlm", False, + "feature_missing: could not start recording (no Stop control appeared)", + depth=0, jump_kind="value", tag="color") + return + time.sleep(2.2) # let the cursor advance onto the axis + passed = vlm_assert( + "computation_recording_progress_line", + "In the waveform area in the middle of the screen, is there a single " + "bright coloured (yellow/orange) VERTICAL line marking the current " + "recording position, standing out from the fainter grid marks?", + expect="YES", depth=0, jump_kind="value", tag="color") + _stop_recording_and_cleanup() + return passed + + +# ══════════════════════════════════════════════════════════════════════════════ + +TESTS = [ + # Recording timer + test_record_timer_advances, + test_record_size_grows, + test_record_timer_present_and_zero_idle, + # Char counter + test_char_counter_updates, + test_char_counter_reflects_length, + # Total records count / duration + test_total_records_count_is_valid_integer, + test_total_recorded_duration_parseable, + # Name format dialog + test_name_format_epoch_all_digits, + test_name_format_fixed_and_date_options, + # Playback position + test_playback_position_advances, + test_playback_stop_resets_position, + # VLM (exactly two) + test_recording_time_axis_vlm, + test_recording_progress_line_vlm, +] + +if __name__ == "__main__": + run_suite(TESTS, "computation") diff --git a/android/dimowner-audiorecorder/tests/test_android_interaction.py b/android/dimowner-audiorecorder/tests/test_android_interaction.py new file mode 100644 index 0000000000000000000000000000000000000000..ecc9a2b8c3b12ba4062f86ad03cce1158e07875b --- /dev/null +++ b/android/dimowner-audiorecorder/tests/test_android_interaction.py @@ -0,0 +1,1051 @@ +#!/usr/bin/env python3 +"""INTERACTION lane — EFFECT-BY-CONSEQUENCE on user DATA for AudioRecorder. + +Covers CRUD create (record->stop->save), rename (data mutation), description +mutation read back on a DIFFERENT surface, the per-record bookmark flag (asserted +via the bookmark-only filter — the DATA consequence, not the icon glyph), +multi-record integrity, the per-record context menu (this lane's sole territory), +multi-step data-integrity walks, and DATA persistence across process death (record +/ renamed-name / description / bookmark each survive a force-stop+relaunch). + +Every assertion re-reads a fresh ui() and compares to what was OBSERVED on the +original. Package comes from argv[1] — never a literal. Read-only kit. + +RENAME/DESCRIPTION DIALOGS: the "Update name" / "Description" dialogs render their +Cancel/Save buttons at the TOP of the card (above the EditText), so the soft +keyboard never covers Save. hide_keyboard() presses BACK, which on these dialogs +DISMISSES THE WHOLE DIALOG and aborts the edit — so we NEVER call hide_keyboard() +in an edit flow; we tap Save directly with the keyboard still up. + +CREATE: the post-record "Update name and description" dialog only appears when the +"Show rename dialog after recording" setting is ON (a sibling lane may leave it +OFF). _create_record_named() therefore works BOTH ways: if the dialog appears it +names the record there, otherwise it renames the freshly-loaded Home record via the +pencil. Either path yields a record whose name CONTAINS the unique marker. + +MARKER SEARCH: record names are 'Record-N' with our unique marker APPENDED, so the +marker is always a SUBSTRING of the row text (and list rows are TRUNCATED). The +kit's scroll_into_view / find_node_ci match EXACTLY, so we search by containment +via _find_substr_in_list(), which checks the top of the list first (newest rows +live there and must not be scrolled past) before swiping down. +""" +import os +import re +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ── shared helpers ────────────────────────────────────────────────────────────── + +def _stamp(prefix: str = "Kit") -> str: + """A short, unique, ASCII marker so a read-back cannot match pre-existing rows.""" + return prefix + str(int(time.time() * 1000) % 100000000) + + +def and_dismiss_permission_dialogs() -> None: + """After clear_data / first Record in a virgin state: tap Allow / While using + the app if present, then settle. Package-agnostic; safe to call always.""" + for _ in range(3): + nodes = ui() + n = (find_node_ci(nodes, "While using the app") + or find_node_ci(nodes, "Allow") + or find_node_ci(nodes, "Only this time")) + if n is None: + return + tap_node(n) + settle("tap") + + +def _record_rows(nodes) -> list: + """All record-name rows currently in the Records list, top-to-bottom. + A row name is a TextView whose text starts with 'Record' below the toolbar.""" + return sorted( + [n for n in nodes + if n.get("class", "").endswith("TextView") + and n.get("text", "").startswith("Record") + and n.get("_center", (0, 9999))[1] > 380], + key=lambda n: n["_center"][1]) + + +def _first_record_name(nodes) -> str: + """The name text of the top record row in the Records list ("" if none).""" + rows = _record_rows(nodes) + return rows[0]["text"] if rows else "" + + +def _bookmark_filter_node(nodes): + """The bookmark-only filter is the rightmost toolbar "Menu" icon (y in the + toolbar band). Located by geometry from the dump, never a literal pixel.""" + cands = [n for n in nodes + if n.get("content-desc") == "Menu" + and n.get("_center", (0, 9999))[1] < 300] + if not cands: + return None + return sorted(cands, key=lambda n: n["_center"][0])[-1] + + +def _row_bookmarks(nodes) -> list: + """Per-row Bookmarks controls, top-to-bottom.""" + return sorted([n for n in nodes if n.get("content-desc") == "Bookmarks"], + key=lambda n: n["_center"][1]) + + +def _visible_has_substr(marker: str) -> bool: + """True if any node's text on the CURRENT screen CONTAINS `marker`. The kit's + scroll_into_view / find_node_ci match EXACTLY, but our record names are + 'Record-N' + appended marker (and list rows are truncated), so the marker is + always a SUBSTRING — we must match by containment, never equality.""" + return any(marker in n.get("text", "") for n in ui()) + + +def _find_substr_in_list(marker: str, max_swipes: int = 8) -> bool: + """Substring-aware list search. Checks the CURRENT screen FIRST (newest rows + are at the top and must not be scrolled past), then swipes down only if not yet + found, re-dumping between swipes. Returns True once a row text contains the + marker. Replaces scroll_into_view(marker) for our appended-marker names.""" + if _visible_has_substr(marker): + return True + for _ in range(max_swipes): + scroll_down(0.4) + if _visible_has_substr(marker): + return True + return False + + +def and_enter_records(): + """Home -> Records list. Backs a depth>=1 claim via the and_enter_* name.""" + n = find_node(ui(), content_desc="Records") + if n is None or not tap_node(n): + return False + settle("tap") + if _first_record_name(ui()) == "" and find_node_ci(ui(), "Records") is None: + return False + and_enter("records") + return True + + +def _rename_field(nodes): + """The single edit field in the rename / description dialog is the top-most + (and usually only) EditText in the card.""" + edits = find_by_class(nodes, "EditText") + return sorted(edits, key=lambda n: n["_center"][1])[0] if edits else None + + +def _save_dialog() -> bool: + """Tap the dialog's Save button. Save renders at the TOP of the card, fully + visible WITH the keyboard up — so we do NOT call hide_keyboard() first (BACK + would dismiss the whole dialog and abort the edit).""" + n = find_node(ui(), text="Save") or find_node_ci(ui(), "Save") + return tap_node(n) if n else False + + +def _type_and_save(marker: str) -> str: + """In an OPEN rename/description dialog: type `marker` into the field (it + APPENDS at the cursor, so the saved value CONTAINS the marker), then Save + directly (keyboard stays up — never hide_keyboard here). Returns the field + text observed just before Save (which contains the marker).""" + fld = _rename_field(ui()) + if fld is None: + return "" + if not type_text(fld, marker): + type_text(fld, marker, method="ime") + seen = "" + f2 = _rename_field(ui()) + if f2: + seen = f2.get("text", "") + _save_dialog() + settle("tap") + settle("tap") + return seen or marker + + +def _make_recording() -> bool: + """Record -> Stop, leaving a freshly-created record LOADED on Home. Dismisses + the post-record dialog via Save if it appears (default name). Returns True if a + record is loaded on Home afterwards (Rename pencil present).""" + rec = find_node(ui(), text="Record") or find_node_ci(ui(), "Record") + if rec is None or not tap_node(rec): + return False + time.sleep(2.8) + stop = find_node(ui(), content_desc="Stop") + if stop is None or not tap_node(stop): + return False + settle("tap") + settle("tap") + if find_by_class(ui(), "EditText"): # post-record dialog present -> Save default + _save_dialog() + settle("tap") + settle("tap") + return find_node(ui(), content_desc="Rename") is not None + + +def _create_record_named(marker: str) -> str | None: + """Full CRUD-create yielding a record whose name CONTAINS `marker`. + + record->stop; if the post-record dialog appears, type marker + Save there; + otherwise rename the freshly-loaded Home record via the pencil. Returns the + saved name (contains marker) or None on failure. Assumes app is on Home.""" + rec = find_node(ui(), text="Record") or find_node_ci(ui(), "Record") + if rec is None or not tap_node(rec): + return None + time.sleep(2.8) + stop = find_node(ui(), content_desc="Stop") + if stop is None or not tap_node(stop): + return None + settle("tap") + settle("tap") + if find_by_class(ui(), "EditText"): # post-record dialog path + saved = _type_and_save(marker) + return saved or marker + # no-dialog path: rename the just-created, now-loaded Home record + pencil = find_node(ui(), content_desc="Rename") + if pencil is None or not tap_node(pencil): + return None + settle("tap") + if _rename_field(ui()) is None: + return None + saved = _type_and_save(marker) + return saved or marker + + +def and_reach_rename_dialog_from_home(): + """Home Rename pencil -> 'Update name' dialog. Counts one surface. Returns True + when the dialog EditText is present.""" + pencil = find_node(ui(), content_desc="Rename") + if pencil is None or not tap_node(pencil): + return False + settle("tap") + if _rename_field(ui()) is None: + return False + and_enter("rename_dialog") + return True + + +def and_reach_row_context_menu(): + """Records -> tap the top row's 3-dot 'Menu' -> the 7-item context popup. + Counts one surface (popup). Returns True when the popup items are present.""" + nodes = ui() + row_menus = sorted( + [n for n in nodes if n.get("content-desc") == "Menu" + and n.get("_center", (0, 0))[0] > 1000 + and n.get("_center", (0, 0))[1] > 350], + key=lambda n: n["_center"][1]) + if not row_menus or not tap_node(row_menus[0]): + return False + time.sleep(1.2) + if find_node_ci(ui(), "Information") is not None: + and_enter("context_menu") + return True + return False + + +def and_enter_settings_and_read_count() -> int | None: + """Home -> Settings (a real depth-1 surface crossing), scroll to and parse + "Total records count: N". Returns N. Named and_enter_* so the depth=1 claim in + test_create_increments_total_count is backed by the crossing it actually does.""" + s = find_node(ui(), content_desc="Settings") + if s is None or not tap_node(s): + return None + settle("tap") + node = scroll_into_view("Total records count:") + if node is None: + node = next((n for n in ui() + if n.get("text", "").startswith("Total records count")), None) + if node is None: + return None + m = re.search(r"(\d+)", node.get("text", "")) + return int(m.group(1)) if m else None + + +# ══════════════════════════════════════════════════════════════════════════════ +# CRUD — create +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_create_persists",)) +def test_create_survives_process_death(): + """Record a new clip, name it with a unique marker, save, then KILL the process + and relaunch — the record must still be in the Records list. An in-memory-only + recreation cannot pass this (highest-value data-persistence test).""" + restart_app() + wait_for_foreground() + mark = _stamp("KitP") + absent_before = not _visible_has_substr(mark) + saved = _create_record_named(mark) + if saved is None: + record("interaction_create_persists", False, + "feature_missing: could not reach record->stop->save to create a record", + depth=1, jump_kind="value", expect=f"Records row containing {mark!r}") + return + force_stop_and_relaunch() + wait_for_foreground() + and_reset_depth() + if not and_enter_records(): + record("interaction_create_persists", False, + "setup_failed: could not open Records after relaunch", + depth=1, jump_kind="value", expect=f"Records row containing {mark!r}") + return + found = _find_substr_in_list(mark) + ok = absent_before and found + record("interaction_create_persists", ok, + "" if ok else "behavior_wrong: created record did not survive process death", + depth=1, jump_kind="value", + expect=f"Records row containing {mark!r} present after force-stop+relaunch") + + +@and_test(expects=("interaction_create_increments_count",)) +def test_create_increments_total_count(): + """CRUD add proven by the Settings 'Total records count: N' incrementing by + exactly 1 after one record->stop(->save). Robust to any pre-existing count.""" + restart_app() + wait_for_foreground() + before = and_enter_settings_and_read_count() + if before is None: + record("interaction_create_increments_count", False, + "setup_failed: could not read 'Total records count' before creating", + depth=1, jump_kind="value", expect="Total records count increases by 1") + return + restart_app() # back to Home to create + wait_for_foreground() + if not _make_recording(): + record("interaction_create_increments_count", False, + "feature_missing: could not create a record via record->stop", + depth=1, jump_kind="value", expect="Total records count increases by 1") + return + after = and_enter_settings_and_read_count() + ok = after is not None and after == before + 1 + record("interaction_create_increments_count", ok, + "" if ok else f"behavior_wrong: total records count {before}->{after}, " + f"expected +1", depth=1, jump_kind="value", + expect=f"Total records count {before}->{before + 1}") + + +@and_test(expects=("interaction_multi_record_integrity",)) +def test_multi_record_integrity(): + """Create TWO records with distinct markers in one session; assert BOTH rows + are present in the list AND the most-recently created one is ordered ABOVE the + earlier one ('By date newest'). Catches a recreation that keeps only one row. + Reads the TOP of the list directly (newest rows live there); never scrolls past + them before checking.""" + restart_app() + wait_for_foreground() + m1 = _stamp("KitA") + n1 = _create_record_named(m1) + time.sleep(0.3) + m2 = _stamp("KitB") + n2 = _create_record_named(m2) + if n1 is None or n2 is None or m1 == m2: + record("interaction_multi_record_integrity", False, + "feature_missing: could not create two distinct records", + depth=1, jump_kind="value", + expect="both records present, newest ordered first") + return + if not and_enter_records(): + record("interaction_multi_record_integrity", False, + "setup_failed: could not open Records", + depth=1, jump_kind="value", + expect="both records present, newest ordered first") + return + rows = [r.get("text", "") for r in _record_rows(ui())] # top rows, no pre-scroll + has1 = any(m1 in t for t in rows) + has2 = any(m2 in t for t in rows) + + def _idx(mark): + for i, t in enumerate(rows): + if mark in t: + return i + return 10 ** 6 + + ordered = _idx(m2) < _idx(m1) + ok = has1 and has2 and ordered + record("interaction_multi_record_integrity", ok, + "" if ok else f"behavior_wrong: both records not intact/ordered " + f"(has1={has1} has2={has2} order_ok={ordered})", + depth=1, jump_kind="value", + expect=f"rows contain {m2!r} above {m1!r} (both intact, newest first)") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Rename — data mutation (Save tapped directly; NO hide_keyboard) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_rename_home",)) +def test_rename_via_home_pencil(): + """Rename the loaded record via the Home 'Rename' pencil, appending a unique + marker, and verify the Home record-name TextView now CONTAINS that marker. + The rename field appends at the cursor, so 'contains marker' is exact.""" + restart_app() + wait_for_foreground() + mark = _stamp("KitR") + pencil = find_node(ui(), content_desc="Rename") + if pencil is None: + record("interaction_rename_home", False, + "feature_missing: no loaded record / Rename pencil on Home", + depth=1, jump_kind="value", expect=f"Home name contains {mark!r}") + return + before = and_showing() + if not and_reach_rename_dialog_from_home(): + record("interaction_rename_home", False, + "setup_failed: Rename pencil did not open the 'Update name' dialog", + depth=1, jump_kind="value", expect=f"Home name contains {mark!r}") + return + after = and_showing() + if not and_reach(before, after, "Update name"): + record("interaction_rename_home", False, + "setup_failed: Rename pencil did not open the 'Update name' dialog", + depth=1, jump_kind="value", expect=f"Home name contains {mark!r}") + return + _type_and_save(mark) # tap Save directly, keyboard up + present = _visible_has_substr(mark) + record("interaction_rename_home", present, + "" if present else "behavior_wrong: Home record name did not update after rename", + depth=1, jump_kind="value", expect=f"Home record name contains {mark!r}") + + +@and_test(expects=("interaction_rename_persists",)) +def test_rename_survives_process_death(): + """Rename the loaded record (append a marker), then KILL the process and + relaunch — the NEW name must still be present in the Records list.""" + restart_app() + wait_for_foreground() + mark = _stamp("KitR") + pencil = find_node(ui(), content_desc="Rename") + if pencil is None: + record("interaction_rename_persists", False, + "feature_missing: no loaded record / Rename pencil on Home", + depth=1, jump_kind="value", + expect=f"renamed row containing {mark!r} after relaunch") + return + if not and_reach_rename_dialog_from_home(): + record("interaction_rename_persists", False, + "setup_failed: no EditText in the rename dialog", + depth=1, jump_kind="value", + expect=f"renamed row containing {mark!r} after relaunch") + return + _type_and_save(mark) # tap Save directly, keyboard up + if not _visible_has_substr(mark): + record("interaction_rename_persists", False, + "behavior_wrong: rename did not apply before the kill", + depth=1, jump_kind="value", + expect=f"renamed row containing {mark!r} after relaunch") + return + force_stop_and_relaunch() + wait_for_foreground() + and_reset_depth() + if not and_enter_records(): + record("interaction_rename_persists", False, + "setup_failed: could not open Records after relaunch", + depth=1, jump_kind="value", + expect=f"renamed row containing {mark!r} after relaunch") + return + found = _find_substr_in_list(mark) + record("interaction_rename_persists", found, + "" if found else "behavior_wrong: renamed name did not survive process death", + depth=1, jump_kind="value", + expect=f"Records row containing {mark!r} present after force-stop+relaunch") + + +@and_test(expects=("interaction_rename_cross_surface",)) +def test_rename_cross_surface_consistency(): + """Rename the loaded record via the Home pencil, then verify the SAME new name + shows on BOTH surfaces: the Home playback panel AND the Records list row. A + recreation that updates only one view fails this cross-surface consistency.""" + restart_app() + wait_for_foreground() + mark = _stamp("KitX") + if find_node(ui(), content_desc="Rename") is None: + record("interaction_rename_cross_surface", False, + "feature_missing: no loaded record / Rename pencil on Home", + depth=1, jump_kind="value", + expect=f"{mark!r} shown on BOTH Home and the Records list") + return + if not and_reach_rename_dialog_from_home(): + record("interaction_rename_cross_surface", False, + "setup_failed: Rename pencil did not open the dialog", + depth=1, jump_kind="value", + expect=f"{mark!r} shown on BOTH Home and the Records list") + return + _type_and_save(mark) + on_home = _visible_has_substr(mark) + and_reset_depth() + in_list = False + if and_enter_records(): + in_list = _find_substr_in_list(mark) + ok = on_home and in_list + record("interaction_rename_cross_surface", ok, + "" if ok else f"behavior_wrong: rename not consistent across surfaces " + f"(home={on_home} list={in_list})", + depth=1, jump_kind="value", + expect=f"record name {mark!r} present on Home AND in the Records list") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Per-record context menu — this lane's sole territory (3-dot / long-press) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_context_menu_items",)) +def test_context_menu_items_present(): + """Open a Records-row 3-dot context menu and assert all 7 documented items + (Share, Information, Rename, Edit description, Open with…, Save as…, Delete) + are present and tappable. Owns the context menu; NEVER taps Delete.""" + restart_app() + wait_for_foreground() + if not and_enter_records(): + record("interaction_context_menu_items", False, + "setup_failed: could not open Records", + depth=2, jump_kind="value", expect="7 context-menu items present") + return + if not and_reach_row_context_menu(): + record("interaction_context_menu_items", False, + "feature_missing: row 3-dot did not open a context menu", + depth=2, jump_kind="value", expect="7 context-menu items present") + return + nodes = ui() + wanted = ["Share", "Information", "Rename", "Edit description", + "Open with…", "Save as…", "Delete"] + present = [w for w in wanted if find_node_ci(nodes, w) is not None] + actionable = all( + (find_node(nodes, content_desc=w) or find_node_ci(nodes, w)) is not None + and "_center" in (find_node(nodes, content_desc=w) or find_node_ci(nodes, w)) + for w in present) + back() # dismiss popup without choosing anything + ok = len(present) == len(wanted) and actionable + record("interaction_context_menu_items", ok, + "" if ok else f"behavior_wrong: context menu items = {present}", + depth=2, jump_kind="value", + expect="Share/Information/Rename/Edit description/Open with…/Save as…/Delete all present") + + +@and_test(expects=("interaction_context_information",)) +def test_context_menu_information_navigates(): + """Choosing the NON-dangerous 'Information' item from a row's context menu + performs its action: the Information screen opens showing its label:value + fields. The jump is verified against 'File location' — a label UNIQUE to the + Info screen (the menu itself also contains an 'Information' item, so that word + cannot distinguish the surfaces).""" + restart_app() + wait_for_foreground() + if not and_enter_records(): + record("interaction_context_information", False, + "setup_failed: could not open Records", + depth=2, jump_kind="value", expect="Information screen with 'File location' field") + return + if not and_reach_row_context_menu(): + record("interaction_context_information", False, + "feature_missing: row 3-dot did not open a context menu", + depth=2, jump_kind="value", expect="Information screen with 'File location' field") + return + info = find_node(ui(), content_desc="Information") or find_node_ci(ui(), "Information") + before = and_showing() + if info is None or not tap_node(info): + record("interaction_context_information", False, + "feature_missing: no Information item in the context menu", + depth=2, jump_kind="value", expect="Information screen with 'File location' field") + return + settle("tap") + and_enter("information") + after = and_showing() + reached = and_reach(before, after, "File location") + has_fields = any(n.get("text", "").startswith("File location") for n in ui()) \ + and any(n.get("text", "").startswith("Name") for n in ui()) + ok = reached and has_fields + record("interaction_context_information", ok, + "" if ok else "behavior_wrong: Information item did not open the Info screen", + depth=2, jump_kind="value", + expect="Information screen shown with 'Name:' and 'File location:' labels") + + +@and_test(expects=("interaction_context_rename",)) +def test_context_menu_rename_action(): + """Choose 'Rename' from a row's context menu, append a unique marker, Save + (keyboard up, no hide_keyboard) — that record's name in the LIST now contains + the marker. A DATA mutation driven entirely from the per-record context menu, + read back out of the list (a different path than the Home pencil).""" + restart_app() + wait_for_foreground() + mark = _stamp("KitC") + if not and_enter_records(): + record("interaction_context_rename", False, + "setup_failed: could not open Records", + depth=2, jump_kind="value", expect=f"list row name contains {mark!r}") + return + if not and_reach_row_context_menu(): + record("interaction_context_rename", False, + "feature_missing: row 3-dot did not open a context menu", + depth=2, jump_kind="value", expect=f"list row name contains {mark!r}") + return + rn = find_node(ui(), content_desc="Rename") or find_node_ci(ui(), "Rename") + if rn is None or not tap_node(rn): + record("interaction_context_rename", False, + "feature_missing: no Rename item in the context menu", + depth=2, jump_kind="value", expect=f"list row name contains {mark!r}") + return + settle("tap") + and_enter("rename_dialog") + if _rename_field(ui()) is None: + record("interaction_context_rename", False, + "setup_failed: no EditText in the rename dialog", + depth=2, jump_kind="value", expect=f"list row name contains {mark!r}") + return + _type_and_save(mark) # tap Save directly, keyboard up + present = _find_substr_in_list(mark) + record("interaction_context_rename", present, + "" if present else "behavior_wrong: context-menu Rename did not update the row name", + depth=2, jump_kind="value", + expect=f"Records row name now contains {mark!r} after context-menu Rename") + + +@and_test(expects=("interaction_context_edit_description",)) +def test_context_edit_description_read_back_in_info(): + """Set a record's description via the context-menu 'Edit description' dialog, + Save, then REOPEN that record's Information screen and assert the typed + description now appears there (it was the empty placeholder before). A real + DATA mutation read back on a DIFFERENT surface (dialog -> Information).""" + restart_app() + wait_for_foreground() + desc = _stamp("Kitdesc") + if not and_enter_records(): + record("interaction_context_edit_description", False, + "setup_failed: could not open Records", + depth=2, jump_kind="value", expect=f"Information shows description {desc!r}") + return + if not and_reach_row_context_menu(): + record("interaction_context_edit_description", False, + "feature_missing: row 3-dot did not open a context menu", + depth=2, jump_kind="value", expect=f"Information shows description {desc!r}") + return + ed = find_node(ui(), content_desc="Edit description") or find_node_ci(ui(), "Edit description") + if ed is None or not tap_node(ed): + record("interaction_context_edit_description", False, + "feature_missing: no 'Edit description' item in the context menu", + depth=2, jump_kind="value", expect=f"Information shows description {desc!r}") + return + settle("tap") + and_enter("description_dialog") + if _rename_field(ui()) is None: + record("interaction_context_edit_description", False, + "setup_failed: no EditText in the description dialog", + depth=2, jump_kind="value", expect=f"Information shows description {desc!r}") + return + _type_and_save(desc) # tap Save directly, keyboard up + # reopen the SAME row's Information and read the description back + and_reset_depth() + and_enter("records") + if not and_reach_row_context_menu(): + record("interaction_context_edit_description", False, + "setup_failed: could not reopen the context menu to view Information", + depth=2, jump_kind="value", expect=f"Information shows description {desc!r}") + return + info = find_node(ui(), content_desc="Information") or find_node_ci(ui(), "Information") + if info is None or not tap_node(info): + record("interaction_context_edit_description", False, + "setup_failed: no Information item to verify the description", + depth=2, jump_kind="value", expect=f"Information shows description {desc!r}") + return + settle("tap") + and_enter("information") + present = _visible_has_substr(desc) + record("interaction_context_edit_description", present, + "" if present else "behavior_wrong: typed description did not appear on the Info screen", + depth=2, jump_kind="value", + expect=f"Information screen shows the typed description {desc!r}") + + +@and_test(expects=("interaction_description_persists",)) +def test_description_survives_process_death(): + """Set a record's description via the context menu, KILL the process and + relaunch, then reopen its Information — the description must still be there. + An in-memory-only recreation cannot pass this.""" + restart_app() + wait_for_foreground() + desc = _stamp("Kitdp") + if not and_enter_records(): + record("interaction_description_persists", False, + "setup_failed: could not open Records", + depth=2, jump_kind="value", expect=f"description {desc!r} after relaunch") + return + if not and_reach_row_context_menu(): + record("interaction_description_persists", False, + "feature_missing: row 3-dot did not open a context menu", + depth=2, jump_kind="value", expect=f"description {desc!r} after relaunch") + return + ed = find_node(ui(), content_desc="Edit description") or find_node_ci(ui(), "Edit description") + if ed is None or not tap_node(ed): + record("interaction_description_persists", False, + "feature_missing: no 'Edit description' item in the context menu", + depth=2, jump_kind="value", expect=f"description {desc!r} after relaunch") + return + settle("tap") + if _rename_field(ui()) is None: + record("interaction_description_persists", False, + "setup_failed: no EditText in the description dialog", + depth=2, jump_kind="value", expect=f"description {desc!r} after relaunch") + return + _type_and_save(desc) + force_stop_and_relaunch() + wait_for_foreground() + and_reset_depth() + if not and_enter_records(): + record("interaction_description_persists", False, + "setup_failed: could not open Records after relaunch", + depth=2, jump_kind="value", expect=f"description {desc!r} after relaunch") + return + if not and_reach_row_context_menu(): + record("interaction_description_persists", False, + "setup_failed: could not reopen the context menu after relaunch", + depth=2, jump_kind="value", expect=f"description {desc!r} after relaunch") + return + info = find_node(ui(), content_desc="Information") or find_node_ci(ui(), "Information") + if info is None or not tap_node(info): + record("interaction_description_persists", False, + "setup_failed: no Information item to verify the description", + depth=2, jump_kind="value", expect=f"description {desc!r} after relaunch") + return + settle("tap") + and_enter("information") + present = _visible_has_substr(desc) + record("interaction_description_persists", present, + "" if present else "behavior_wrong: description did not survive process death", + depth=2, jump_kind="value", + expect=f"Information shows description {desc!r} after force-stop+relaunch") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Bookmark — per-record data flag, asserted via the bookmark-only filter +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_bookmark_filter",)) +def test_bookmark_shows_under_filter(): + """Bookmark the top record, then enable the bookmark-only filter: the record is + STILL present under the filter (its DATA flag was set). Asserts the data effect + via the filter, not the icon glyph.""" + restart_app() + wait_for_foreground() + if not and_enter_records(): + record("interaction_bookmark_filter", False, + "setup_failed: could not open Records", + depth=1, jump_kind="transition", + expect="bookmarked row present under bookmark filter") + return + nodes = ui() + name = _first_record_name(nodes) + bm = _row_bookmarks(nodes) + if not bm or not name: + record("interaction_bookmark_filter", False, + "feature_missing: no per-row Bookmarks control", + depth=1, jump_kind="transition", + expect="bookmarked row present under bookmark filter") + return + tap_node(bm[0]) # set bookmark on the top record + settle("tap") + bf = _bookmark_filter_node(ui()) + if bf is None: + record("interaction_bookmark_filter", False, + "feature_missing: no bookmark-only filter control in the toolbar", + depth=1, jump_kind="transition", + expect="bookmarked row present under bookmark filter") + return + tap_node(bf) # enable bookmark-only filter + settle("tap") + present = scroll_into_view(name) is not None or find_node_ci(ui(), name) is not None + # restore state: filter off, then un-bookmark + bf2 = _bookmark_filter_node(ui()) + if bf2: + tap_node(bf2) + settle("tap") + bm2 = _row_bookmarks(ui()) + if bm2: + tap_node(bm2[0]) + record("interaction_bookmark_filter", present, + "" if present else "behavior_wrong: bookmarked record absent under the bookmark-only filter", + depth=1, jump_kind="transition", + expect=f"row {name!r} present after enabling the bookmark-only filter") + + +@and_test(expects=("interaction_bookmark_persists",)) +def test_bookmark_survives_process_death(): + """Bookmark a record, KILL the process and relaunch, then enable the + bookmark-only filter — the record is still shown, proving the bookmark flag + persisted in the DB across process death.""" + restart_app() + wait_for_foreground() + if not and_enter_records(): + record("interaction_bookmark_persists", False, + "setup_failed: could not open Records", + depth=1, jump_kind="value", expect="bookmarked row survives relaunch under filter") + return + nodes = ui() + name = _first_record_name(nodes) + bm = _row_bookmarks(nodes) + if not bm or not name: + record("interaction_bookmark_persists", False, + "feature_missing: no per-row Bookmarks control", + depth=1, jump_kind="value", expect="bookmarked row survives relaunch under filter") + return + tap_node(bm[0]) + settle("tap") + force_stop_and_relaunch() + wait_for_foreground() + and_reset_depth() + if not and_enter_records(): + record("interaction_bookmark_persists", False, + "setup_failed: could not open Records after relaunch", + depth=1, jump_kind="value", expect="bookmarked row survives relaunch under filter") + return + bf = _bookmark_filter_node(ui()) + present = False + if bf is not None: + tap_node(bf) + settle("tap") + present = scroll_into_view(name) is not None or find_node_ci(ui(), name) is not None + bf2 = _bookmark_filter_node(ui()) # restore + if bf2: + tap_node(bf2) + settle("tap") + bm2 = _row_bookmarks(ui()) + if bm2: + tap_node(bm2[0]) + record("interaction_bookmark_persists", present, + "" if present else "behavior_wrong: bookmark flag did not survive process death", + depth=1, jump_kind="value", + expect=f"row {name!r} still bookmarked (shown under filter) after relaunch") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Multi-step sequences (3+ dependent actions) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_sequence_record_info_back",)) +def test_sequence_record_info_back(): + """3+-step data-integrity walk: Home -> Records -> open a row's Information -> + back -> back to Home. Assert we returned to Home AND the record still exists in + the list afterwards (data survived the round trip).""" + restart_app() + wait_for_foreground() + if not and_enter_records(): + record("interaction_sequence_record_info_back", False, + "setup_failed: could not open Records", + depth=2, jump_kind="value", expect="returned to Home; record still listed") + return + name = _first_record_name(ui()) + if not and_reach_row_context_menu(): + record("interaction_sequence_record_info_back", False, + "feature_missing: row 3-dot did not open a context menu", + depth=2, jump_kind="value", expect="returned to Home; record still listed") + return + info = find_node(ui(), content_desc="Information") or find_node_ci(ui(), "Information") + if info is None or not tap_node(info): + record("interaction_sequence_record_info_back", False, + "feature_missing: no Information item", + depth=2, jump_kind="value", expect="returned to Home; record still listed") + return + settle("tap") + and_enter("information") + on_info = find_node_ci(ui(), "Information") is not None + and_back() # Info -> Records + settle("tap") + and_back() # Records -> Home + settle("tap") + back_home = (find_node(ui(), text="Record") is not None + and find_node(ui(), content_desc="Records") is not None) + still = False + and_reset_depth() + if and_enter_records(): + still = scroll_into_view(name) is not None or find_node_ci(ui(), name) is not None + ok = on_info and back_home and still + record("interaction_sequence_record_info_back", ok, + "" if ok else f"behavior_wrong: 3-step walk failed " + f"(on_info={on_info} home={back_home} intact={still})", + depth=2, jump_kind="value", + expect=f"returned to Home and row {name!r} still listed after Info round-trip") + + +@and_test(expects=("interaction_row_starts_playback",)) +def test_row_tap_starts_playback(): + """Tapping a Records row starts INLINE playback of THAT record: a 'Stop' control + appears while staying on the Records surface, and tapping it ends playback. You + can only play a record that exists, so this is a data-carrying interaction on the + row. (This build plays in place rather than popping to Home — asserted from the + observed behavior, not recon.)""" + restart_app() + wait_for_foreground() + if not and_enter_records(): + record("interaction_row_starts_playback", False, + "setup_failed: could not open Records", + depth=1, jump_kind="value", expect="row tap raises a Stop (playback) control") + return + rows = _record_rows(ui()) + if not rows: + record("interaction_row_starts_playback", False, + "feature_missing: no record rows to tap", + depth=1, jump_kind="value", expect="row tap raises a Stop (playback) control") + return + target_full = rows[0].get("text", "") + m = re.match(r"(Record-\d+)", target_full) + key = m.group(1) if m else target_full[:12] + stop_before = find_node(ui(), content_desc="Stop") is not None + on_records = find_node(ui(), content_desc="Navigate back") is not None + tap_node(rows[0]) + settle("tap") + settle("tap") + stop_after = find_node(ui(), content_desc="Stop") is not None + still_records = find_node(ui(), content_desc="Navigate back") is not None + # end playback to restore idle state + st = find_node(ui(), content_desc="Stop") + if st: + tap_node(st) + settle("tap") + ok = on_records and (not stop_before) and stop_after and still_records + record("interaction_row_starts_playback", ok, + "" if ok else f"behavior_wrong: tapping row {key!r} did not start inline playback " + f"(stop_before={stop_before} stop_after={stop_after} on_records={still_records})", + depth=1, jump_kind="value", + expect=f"tapping row {key!r} raises a Stop control (inline playback) on the Records screen") + + +# ══════════════════════════════════════════════════════════════════════════════ +# VLM — rendered-only properties (fine-grained). Never for dump-readable data. +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("interaction_bookmark_icon_vlm",)) +def test_bookmark_icon_filled_vlm(): + """After tapping a row's bookmark control, that row's bookmark icon renders as a + FILLED/solid shape (vs the empty outline before). The content-desc does NOT flip + (recon), so the fill is only observable visually — a legitimate VLM shape check. + The DATA consequence itself is covered by test_bookmark_shows_under_filter.""" + restart_app() + wait_for_foreground() + if not and_enter_records(): + record("interaction_bookmark_icon_vlm", False, + "setup_failed: could not open Records", + depth=1, jump_kind="value", tag="shape") + return + bm = _row_bookmarks(ui()) + if not bm: + record("interaction_bookmark_icon_vlm", False, + "feature_missing: no per-row Bookmarks control", + depth=1, jump_kind="value", tag="shape") + return + tap_node(bm[0]) # set bookmark -> icon fills + settle("tap") + passed = vlm_assert( + "interaction_bookmark_icon", + "On the first record row, is the bookmark icon (to the right of the record " + "name, left of the 3-dot menu) drawn as a SOLID/FILLED bookmark shape " + "rather than a hollow outline?", + expect="YES", depth=1, jump_kind="value", tag="shape") + bm2 = _row_bookmarks(ui()) # restore: un-bookmark + if bm2: + tap_node(bm2[0]) + return passed + + +@and_test(expects=("interaction_recording_cursor_vlm",)) +def test_recording_cursor_vlm(): + """During an active recording the waveform view draws a bright YELLOW vertical + line (the current-position cursor) over the scrolling time axis. On the emulator + the amplitude trace itself is flat (silent mic), but the yellow cursor line is + always drawn on the canvas and never reaches the view tree — a legitimate, + rendered-only colour check.""" + restart_app() + wait_for_foreground() + rec = find_node(ui(), text="Record") or find_node_ci(ui(), "Record") + if rec is None or not tap_node(rec): + record("interaction_recording_cursor_vlm", False, + "feature_missing: no Record control on Home", + depth=0, jump_kind="none", tag="color") + return + time.sleep(3.2) + recording = find_node(ui(), content_desc="Stop") is not None + passed = False + if recording: + passed = vlm_assert( + "interaction_recording_cursor", + "In the waveform area in the upper-middle of the screen, is there a " + "bright YELLOW vertical line drawn (the recording position cursor), " + "distinct from the darker background and the pale time-axis gridlines?", + expect="YES", depth=0, jump_kind="none", tag="color") + else: + record("interaction_recording_cursor_vlm", False, + "setup_failed: recording did not start (no Stop control)", + depth=0, jump_kind="none", tag="color") + # stop the recording; if the post-record dialog appears, Cancel to avoid a stray record + stop = find_node(ui(), content_desc="Stop") + if stop: + tap_node(stop) + settle("tap") + settle("tap") + c = find_node(ui(), text="Cancel") or find_node_ci(ui(), "Cancel") + if c: + tap_node(c) + return passed + + +@and_test(expects=("interaction_playback_started_vlm",)) +def test_playback_started_vlm(): + """Starting playback on a loaded record: the central control shows a PAUSE glyph + (shape). The content-desc stays 'Play' (recon quirk), so the glyph flip is only + observable visually. The rule-side data consequence (a 'Stop' control appearing) + is proven from the dump before the VLM question.""" + restart_app() + wait_for_foreground() + play = find_node(ui(), content_desc="Play") + if play is None: + record("interaction_playback_started_vlm", False, + "feature_missing: no loaded record / Play control on Home", + depth=0, jump_kind="none", tag="shape") + return + tap_node(play) + time.sleep(1.4) + playing = find_node(ui(), content_desc="Stop") is not None + passed = False + if playing: + passed = vlm_assert( + "interaction_playback_started", + "Is the central round play/pause button now showing a PAUSE icon (two " + "vertical bars) rather than a triangular play arrow, indicating playback " + "is in progress?", + expect="YES", depth=0, jump_kind="none", tag="shape") + else: + record("interaction_playback_started_vlm", False, + "behavior_wrong: playback did not start (no Stop control appeared)", + depth=0, jump_kind="none", tag="shape") + stop = find_node(ui(), content_desc="Stop") # restore idle state + if stop: + tap_node(stop) + return passed + + +# ══════════════════════════════════════════════════════════════════════════════ + +TESTS = [ + # CRUD create + persistence + test_create_survives_process_death, + test_create_increments_total_count, + test_multi_record_integrity, + # Rename (data mutation) + test_rename_via_home_pencil, + test_rename_survives_process_death, + test_rename_cross_surface_consistency, + # Per-record context menu (sole owner) + test_context_menu_items_present, + test_context_menu_information_navigates, + test_context_menu_rename_action, + test_context_edit_description_read_back_in_info, + test_description_survives_process_death, + # Bookmark (per-record data flag) + test_bookmark_shows_under_filter, + test_bookmark_survives_process_death, + # Multi-step sequences + test_sequence_record_info_back, + test_row_tap_starts_playback, + # VLM — rendered-only (shape / colour) + test_bookmark_icon_filled_vlm, + test_recording_cursor_vlm, + test_playback_started_vlm, +] + +if __name__ == "__main__": + run_suite(TESTS, "interaction") diff --git a/android/dimowner-audiorecorder/tests/test_android_navigation.py b/android/dimowner-audiorecorder/tests/test_android_navigation.py new file mode 100644 index 0000000000000000000000000000000000000000..134be738d97a550bca78eefebdd49f6bc3981441 --- /dev/null +++ b/android/dimowner-audiorecorder/tests/test_android_navigation.py @@ -0,0 +1,452 @@ +#!/usr/bin/env python3 +"""NAVIGATION lane — Audio Recorder (Jetpack Compose, single-Activity). + +This lane owns SURFACE REACHABILITY and BACK-STACK INTEGRITY: + * every top-level destination (Records, Settings, Record Info) is reachable from Home; + * depth>=2 chains (Home->Records->Info, Home->Settings->Trash) with BACK unwinding them; + * the back stack pops each surface back to its parent; + * Import launches the EXTERNAL system file picker (leaves the app). + +get_current_activity() NEVER changes across in-app navigation (Compose destinations), +so every jump is proven with and_showing()/and_reach(): the TARGET surface's +discriminating element APPEARED *and* the SOURCE surface's DISAPPEARED. Discriminators +are chosen to be unique to their surface (substring, case-insensitive matching in the +kit) so a screen that was in the tree all along can never fake a reach. + +Each test opens its own entry with restart_app() for isolation, then NAVIGATES to the +asserted surface — the restart only resets to Home; the reach itself is always a real +and_reach* verdict, never "the screen was there after relaunch". + +We assert only surfaces and the back stack here — never content values (text lane), +toggles/selection (states lane), or CRUD (interaction lane). +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +require_kit(1) + + +# ── Surface discriminators ─────────────────────────────────────────────────── +# Each is a substring the kit matches case-insensitively against surface keys. +# Chosen so it is present on exactly the intended surface and absent on the others. +HOME_SRC = "Import" # Home top-bar content-desc; absent from every destination +RECORDS_TGT = "By date" # Records subtitle "By date (newest)"; absent from Home/Info +SETTINGS_TGT = "Dark theme" # a Settings row; absent from Home (title "Settings" would +# collide with Home's bottom-bar "Settings" content-desc) +INFO_TGT = "Record author" # a Record Info LABEL. NB the Info *title* "Information" +# also names the overflow menu item that launches it, so +# the title cannot discriminate a menu->Info jump; this +# label is Info-only (absent from menu, Records, Home). +MENU_SRC = "Share" # a context/overflow menu item; present while the menu popup +# is open, gone once we land on the Info surface. The Home +# bar / Records subtitle are HIDDEN behind the popup, so +# they cannot serve as the source for the menu->Info hop. +TRASH_TGT = "permanently deleted" # Trash empty-state msg; the title "Trash" collides +# with the Settings "Trash" row, so we key off the message +PICKER_TGT = "Show roots" # documentsui affordance; the app never renders it + + +# ── Trigger locators (each re-dumps; never a stale coordinate) ──────────────── +def _home_overflow(nodes): + """The top-right overflow trigger on Home (content-desc 'Menu').""" + return find_node(nodes, content_desc="Menu") + + +def _bottom_records(nodes): + return find_node(nodes, content_desc="Records") + + +def _bottom_settings(nodes): + return find_node(nodes, content_desc="Settings") + + +def _import_trigger(nodes): + return find_node(nodes, content_desc="Import") + + +def _menu_information(nodes): + return find_node(nodes, content_desc="Information") or find_node_ci(nodes, "Information") + + +# ── Named depth helpers. The and_reach_* NAME is what the depth audit keys off; +# each does snapshot -> tap -> snapshot -> and_reach* verdict and counts one surface. +def and_reach_records(): + """Home -> Records. True on a proven reach (target appeared, source vanished).""" + trig = _bottom_records(ui()) + return bool(trig) and and_reach_surface(trig, RECORDS_TGT, HOME_SRC) + + +def and_reach_settings(): + """Home -> Settings.""" + trig = _bottom_settings(ui()) + return bool(trig) and and_reach_surface(trig, SETTINGS_TGT, HOME_SRC) + + +def and_reach_overflow(): + """Open the Home overflow menu, proving the 'Information' item appeared over Home.""" + trig = _home_overflow(ui()) + if not trig: + return False + before = and_showing() + if not tap_node(trig): + return False + after = and_showing() + ok = and_reach(before, after, "Information", None) # menu adds items over Home + if ok: + and_enter("overflow") + return ok + + +def and_reach_info_from_home(): + """Home -> overflow -> Information (Record Info surface). + + The final hop's source is a MENU item (MENU_SRC), not the Home bar: opening the + overflow popup hides the Home top bar from the tree, so 'Import' is already gone + before we tap Information. The target is an Info-only LABEL (INFO_TGT), because + the Info title reuses the menu item's own 'Information' text. + """ + if not and_reach_overflow(): + return False + item = _menu_information(ui()) + return bool(item) and and_reach_surface(item, INFO_TGT, MENU_SRC) + + +def and_reach_info_from_records(): + """Home -> Records -> row 3-dot -> Information (depth 2).""" + if not and_reach_records(): + return False + row_menu = find_node(ui(), content_desc="Menu") # first per-row 3-dot on Records + if not row_menu: + return False + before = and_showing() + if not tap_node(row_menu): + return False + after = and_showing() + if not and_reach(before, after, "Information", None): # context menu opened + return False + and_enter("row-menu") + item = _menu_information(ui()) + return bool(item) and and_reach_surface(item, INFO_TGT, MENU_SRC) + + +def and_reach_trash(): + """Home -> Settings -> Trash (depth 2).""" + if not and_reach_settings(): + return False + row = find_node(ui(), content_desc="Trash") or find_node_ci(ui(), "Trash") + return bool(row) and and_reach_surface(row, TRASH_TGT, SETTINGS_TGT) + + +# ══════════════════════════════════════════════════════════════════════════════ +# DEPTH-1 reaches from Home +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_reach_records", "navigation_reach_records_vlm")) +def test_reach_records(): + restart_app() + if not wait_for_foreground(): + record("navigation_reach_records", False, + "setup_failed: app never reached foreground", + depth=1, jump_kind="reach", expect="Records surface from Home") + vlm_assert("navigation_reach_records", + "Does the top of this screen show two small horizontal-line " + "sort/filter icons and a bookmark (ribbon) icon in a row at the " + "top-right?", RESULTS_DIR, tag="position") + return + ok = and_reach_records() + record("navigation_reach_records", ok, + "" if ok else "behavior_wrong: Records surface not reached from Home", + depth=1, jump_kind="reach", + expect="Records subtitle 'By date (newest)' appeared; Home 'Import' gone") + vlm_assert("navigation_reach_records", + "Does the top of this screen show two small horizontal-line " + "sort/filter icons and a bookmark (ribbon) icon in a row at the " + "top-right?", RESULTS_DIR, tag="position") + + +@and_test(expects=("navigation_reach_settings", "navigation_reach_settings_vlm")) +def test_reach_settings(): + restart_app() + ok = and_reach_settings() if wait_for_foreground() else False + record("navigation_reach_settings", ok, + "" if ok else "behavior_wrong: Settings surface not reached from Home", + depth=1, jump_kind="reach", + expect="Settings row 'Dark theme' appeared; Home 'Import' gone") + vlm_assert("navigation_reach_settings", + "Is this a settings screen showing a vertical list of labelled rows " + "with pill-shaped ON/OFF toggle switches on the right side of some " + "rows?", RESULTS_DIR, tag="layout") + + +@and_test(expects=("navigation_reach_info_home",)) +def test_reach_info_from_home(): + restart_app() + ok = and_reach_info_from_home() if wait_for_foreground() else False + record("navigation_reach_info_home", ok, + "" if ok else "behavior_wrong: Record Info not reached via Home overflow", + depth=1, jump_kind="reach", + expect="Info label 'Record author' appeared; overflow 'Share' gone") + + +# ══════════════════════════════════════════════════════════════════════════════ +# DEPTH-2 chains (this lane's specialty) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_chain_records_info", "navigation_chain_records_info_vlm")) +def test_chain_records_to_info(): + """Home -> Records -> Info: two proven hops.""" + restart_app() + ok = and_reach_info_from_records() if wait_for_foreground() else False + record("navigation_chain_records_info", ok, + "" if ok else "behavior_wrong: Home->Records->Info chain not traversed", + depth=2, jump_kind="reach", + expect="Info 'Record author' appeared after leaving Records via the row menu") + vlm_assert("navigation_chain_records_info", + "Does this detail screen show label/value pairs such as 'Format:' " + "and 'Bitrate:' stacked vertically beneath a header?", + RESULTS_DIR, tag="content") + + +@and_test(expects=("navigation_chain_settings_trash", "navigation_chain_settings_trash_vlm")) +def test_chain_settings_to_trash(): + """Home -> Settings -> Trash: two proven hops.""" + restart_app() + ok = and_reach_trash() if wait_for_foreground() else False + record("navigation_chain_settings_trash", ok, + "" if ok else "behavior_wrong: Home->Settings->Trash chain not traversed", + depth=2, jump_kind="reach", + expect="Trash empty-state 'permanently deleted' appeared; Settings 'Dark theme' gone") + vlm_assert("navigation_chain_settings_trash", + "Does this screen show a large trash-can icon centered in the middle " + "with a short message below it and no list of items?", + RESULTS_DIR, tag="position") + + +# ══════════════════════════════════════════════════════════════════════════════ +# BACK-STACK integrity (each BACK pops one surface; reverse reaches) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_back_records_home", "navigation_back_records_home_vlm")) +def test_back_records_to_home(): + restart_app() + deep = and_reach_records() if wait_for_foreground() else False + ok = False + if deep: + before = and_showing() + and_back() # pop Records -> Home + after = and_showing() + ok = and_reach(before, after, HOME_SRC, RECORDS_TGT) + record("navigation_back_records_home", deep and ok, + "" if deep and ok else "behavior_wrong: BACK from Records did not restore Home", + depth=1, jump_kind="reach", + expect="Home 'Import' restored; Records 'By date' gone after one BACK") + vlm_assert("navigation_back_records_home", + "Does this screen show a large round 'Record' button near the bottom " + "center with a gear (settings) icon at the bottom-left?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("navigation_back_settings_home",)) +def test_back_settings_to_home(): + restart_app() + deep = and_reach_settings() if wait_for_foreground() else False + ok = False + if deep: + before = and_showing() + and_back() # pop Settings -> Home + after = and_showing() + ok = and_reach(before, after, HOME_SRC, SETTINGS_TGT) + record("navigation_back_settings_home", deep and ok, + "" if deep and ok else "behavior_wrong: BACK from Settings did not restore Home", + depth=1, jump_kind="reach", + expect="Home 'Import' restored; Settings 'Dark theme' gone after one BACK") + + +@and_test(expects=("navigation_back_info_home",)) +def test_back_info_to_home(): + restart_app() + deep = and_reach_info_from_home() if wait_for_foreground() else False + ok = False + if deep: + before = and_showing() + and_back() # pop Info -> Home + after = and_showing() + ok = and_reach(before, after, HOME_SRC, INFO_TGT) + record("navigation_back_info_home", deep and ok, + "" if deep and ok else "behavior_wrong: BACK from Record Info did not restore Home", + depth=1, jump_kind="reach", + expect="Home 'Import' restored; Info 'Record author' gone after one BACK") + + +@and_test(expects=("navigation_backstack_unwind_2hop",)) +def test_backstack_unwind_two_hops(): + """Home -> Settings -> Trash, then BACK twice, asserting each pop lands on the + expected parent surface (Trash -> Settings -> Home).""" + restart_app() + reached_trash = and_reach_trash() if wait_for_foreground() else False + pop1 = pop2 = False + if reached_trash: + before = and_showing() + and_back() # Trash -> Settings + mid = and_showing() + pop1 = and_reach(before, mid, SETTINGS_TGT, TRASH_TGT) + if pop1: + and_back() # Settings -> Home + after = and_showing() + pop2 = and_reach(mid, after, HOME_SRC, SETTINGS_TGT) + ok = reached_trash and pop1 and pop2 + record("navigation_backstack_unwind_2hop", ok, + "" if ok else "behavior_wrong: 2-hop back stack did not unwind Trash->Settings->Home", + depth=2, jump_kind="reach", + expect="Trash->Settings then Settings->Home restored, one surface per BACK") + + +@and_test(expects=("navigation_backstack_records_info_unwind",)) +def test_backstack_records_info_unwind(): + """Home -> Records -> Info, then BACK unwinds Info -> Records -> Home hop by hop.""" + restart_app() + reached = and_reach_info_from_records() if wait_for_foreground() else False + pop1 = pop2 = False + if reached: + before = and_showing() + and_back() # Info -> Records + mid = and_showing() + pop1 = and_reach(before, mid, RECORDS_TGT, INFO_TGT) + if pop1: + and_back() # Records -> Home + after = and_showing() + pop2 = and_reach(mid, after, HOME_SRC, RECORDS_TGT) + ok = reached and pop1 and pop2 + record("navigation_backstack_records_info_unwind", ok, + "" if ok else "behavior_wrong: Info->Records->Home did not unwind hop by hop", + depth=2, jump_kind="reach", + expect="Info->Records then Records->Home restored, one surface per BACK") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Cross-surface reachability (Info reachable from BOTH Home and Records) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_info_reachable_two_paths",)) +def test_info_reachable_from_two_paths(): + """Record Info is reachable via the Home overflow AND via a Records row — + two independent proven reaches to the same surface in one run.""" + restart_app() + if not wait_for_foreground(): + record("navigation_info_reachable_two_paths", False, + "setup_failed: app never reached foreground", + depth=2, jump_kind="reach", expect="Info reached via two paths") + return + via_home = and_reach_info_from_home() + # return to Home and try the Records path + restart_app() + via_records = and_reach_info_from_records() if wait_for_foreground() else False + ok = via_home and via_records + record("navigation_info_reachable_two_paths", ok, + "" if ok else "behavior_wrong: Info not reachable via both Home overflow and Records row", + depth=2, jump_kind="reach", + expect="'Record author' Info surface reached from the Home overflow and from a Records row") + + +@and_test(expects=("navigation_settings_records_sibling",)) +def test_settings_and_records_are_siblings(): + """Both bottom-bar destinations are reachable from the SAME Home instance: + reach Records, BACK to Home, then reach Settings — proving Home is the shared host.""" + restart_app() + ok = False + if wait_for_foreground(): + to_records = and_reach_records() + back_home = False + if to_records: + before = and_showing() + and_back() + after = and_showing() + back_home = and_reach(before, after, HOME_SRC, RECORDS_TGT) + to_settings = and_reach_settings() if back_home else False + ok = to_records and back_home and to_settings + record("navigation_settings_records_sibling", ok, + "" if ok else "behavior_wrong: Home is not the shared host for Records and Settings", + depth=1, jump_kind="reach", + expect="Records reached, BACK to Home, then Settings reached from the same Home") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Overflow menu host + Information item presence (navigation trigger surface) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_overflow_opens",)) +def test_overflow_menu_opens(): + """The Home overflow ('Menu') opens a menu surface exposing the 'Information' + navigation trigger — the launch point for the Info surface.""" + restart_app() + ok = and_reach_overflow() if wait_for_foreground() else False + record("navigation_overflow_opens", ok, + "" if ok else "behavior_wrong: Home overflow did not open a menu with Information", + depth=1, jump_kind="reach", + expect="'Information' menu item appeared over Home after tapping overflow") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Import -> EXTERNAL system file picker (reach-to-external; app leaves foreground) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("navigation_import_external_picker", + "navigation_import_external_picker_vlm")) +def test_import_launches_external_picker(): + restart_app() + reached = left = False + if wait_for_foreground(): + trig = _import_trigger(ui()) + if trig: + before = and_showing() + if tap_node(trig): + settle("launch") # SAF picker cold-starts + after = and_showing() + # a genuine surface jump OUT of the app to documentsui + reached = and_reach(before, after, PICKER_TGT, HOME_SRC) + if reached: + and_enter("external-picker") + left = not is_app_foreground() # app really backgrounded + ok = reached or left + # screenshot the picker for the VLM record BEFORE returning + vlm_assert("navigation_import_external_picker", + "Is this a system file browser (light/white background) with a " + "search magnifier icon at the top-right and a hamburger menu at the " + "top-left, clearly different chrome from a dark audio-recorder app?", + RESULTS_DIR, tag="color") + # record the verdict BEFORE the cleanup relaunch, so it flushes even under a + # tight overall time budget + record("navigation_import_external_picker", ok, + "" if ok else "feature_missing: Import did not launch the external system picker", + depth=1, jump_kind="reach", + expect="documentsui 'Show roots' appeared and the app left the foreground") + # return to a clean app state so no later test inherits the picker + back() + restart_app() + + +TESTS = [ + test_reach_records, + test_reach_settings, + test_reach_info_from_home, + test_chain_records_to_info, + test_chain_settings_to_trash, + test_back_records_to_home, + test_back_settings_to_home, + test_back_info_to_home, + test_backstack_unwind_two_hops, + test_backstack_records_info_unwind, + test_info_reachable_from_two_paths, + test_settings_and_records_are_siblings, + test_overflow_menu_opens, + test_import_launches_external_picker, +] + + +if __name__ == "__main__": + if not device_online(): + print("device offline — the tunnel may have dropped") + run_suite(TESTS, "navigation") diff --git a/android/dimowner-audiorecorder/tests/test_android_states.py b/android/dimowner-audiorecorder/tests/test_android_states.py new file mode 100644 index 0000000000000000000000000000000000000000..30d9e11d1fd390cd49fa1714cf6b6bfde663b270 --- /dev/null +++ b/android/dimowner-audiorecorder/tests/test_android_states.py @@ -0,0 +1,1095 @@ +#!/usr/bin/env python3 +"""STATE-CHANGE lane — Audio Recorder (Jetpack Compose single-Activity recorder). + +This lane owns CHECKED / SELECTED / ENABLED / FOCUSED transitions PAIRED WITH +THEIR APP-AUTHORED CONSEQUENCE, page-level state machines, and SETTINGS/mode +persistence across process death. + +GROUND TRUTH probed on the running ORIGINAL before authoring (this is why several +"state reads" go through a rendered-pixel helper rather than the `checked` +attribute — the app hides its state from the accessibility tree): + + * Compose exposes NOTHING through `checked`/`selected` for the Settings toggles + and chips: every node reports checked="false" selected="false" before AND + after a flip. The toggle is an ImageView whose *drawable* changes; the chip is + a TextView whose *pill fill* changes. So toggle/chip STATE is rendered-only. + - A toggle's ON/OFF is read from the rendered switch: sample a pixel in the + LEFT third of the track (x≈0.885*W, y=row-center). ON = blue thumb has + shifted there (b-r > 40); OFF = grey (balanced RGB). Validated against all + four defaults (Dark ON, Dynamic OFF, Keep OFF, Show-rename ON). + - A chip group's selection is read from the "Recording settings" SUMMARY + card text, which IS in the dump and updates on every chip tap: + M4a -> "M4a, 44.1kHz, 128 kbps, Stereo" + Wav -> "Wav, 44.1kHz, Stereo" (no bitrate token) + 3gp -> "3gp, 16kHz, Mono" + bitrate 128->96 -> "...128 kbps..." becomes "...96 kbps..." + sample 44.1->48 -> "...44.1kHz..." becomes "...48kHz..." + channel Stereo->Mono -> "...Stereo" becomes "...Mono". + Toggles must be TAPPED on the far-right switch (x≈0.93*W); tapping the label + text does NOT flip them. The switch x is DERIVED from get_screen_info(), never + a literal. + + * The post-record dialog checkboxes ARE real CheckBox nodes with a readable + `checked` attribute ("Write description" default checked=true; "Don't ask + again" default checked=false) — so those are pure rule `checked` transitions. + + * "Show rename dialog after recording is completed" has a clean behavioural + consequence: OFF -> Stop saves silently (no "Update name and description" + dialog); ON -> Stop raises it. + + * Settings persist across force-stop+relaunch (Keep-screen-ON flip survives). + Sort mode does NOT persist (relaunch reverts to "By date (newest)"), so sort + is tested as a same-session subtitle transition, never as persistence. + + * State machines: Record -> label "Pause" + content-desc "Stop" + "Recording…" + + timer advances; Pause -> label "Resume" + timer FREEZES + a "Delete" button + appears (NEVER tapped); Resume -> label "Pause" + timer advances again. + Play -> a "Stop" content-desc appears + position advances + glyph ▶→❚❚; + Stop -> "Stop" disappears, "Play" returns. + +We CEDE record/data persistence -> interaction, consequence WORDING -> text, +numeric consequences -> computation, screen reachability -> navigation. We never +tap Delete/Reset/Clear (Reset carries "reset" -> DANGEROUS_TEXTS). +""" +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + +try: + from PIL import Image + _HAVE_PIL = True +except Exception: # pragma: no cover + _HAVE_PIL = False + + +# ── Local helpers (READ-ONLY kit stays untouched) ─────────────────────────────── +def _clear_startup_dialogs(): + """A fresh launch may raise a 'Recording interrupted' restore dialog (harmless + residue of a killed recording). Dismiss it so the Home surface is clean. Only + ever taps the safe 'Dismiss'.""" + n = find_node_ci(ui(), "Dismiss") + if n and is_safe(n): + tap_node(n) + + +def and_enter_settings(): + """Tap the bottom-left 'Settings' control and confirm the surface changed. + Counts one crossed surface (Home -> Settings = depth 1). Returns True/False. + NAMED and_enter_* so a declared depth>=1 is backed by a real nav call.""" + btn = find_node(ui(), content_desc="Settings") + if not btn: + return False + before = and_showing() + if not tap_node(btn): + return False + if not surface_changed(before, and_showing()): + return False + and_enter("Settings") + return True + + +def and_enter_records(): + """Tap the bottom-right 'Records' control; confirm the surface changed. + Counts one crossed surface (Home -> Records = depth 1).""" + btn = find_node(ui(), content_desc="Records") + if not btn: + return False + before = and_showing() + if not tap_node(btn): + return False + if not surface_changed(before, and_showing()): + return False + and_enter("Records") + return True + + +def _summary_text(nodes=None): + """The 'Recording settings' summary line, e.g. 'M4a, 44.1kHz, 128 kbps, + Stereo'. This is the rule-readable consequence of a chip selection.""" + nodes = ui() if nodes is None else nodes + for n in nodes: + t = n.get("text", "") + if (t.count(",") >= 2 + and ("kHz" in t or "kbps" in t or "Stereo" in t or "Mono" in t) + and n.get("class", "").endswith("TextView")): + return t + return None + + +def _read_summary(max_up=4): + """Read the 'Recording settings' summary, scrolling UP first if a chip + selection pushed the card above the viewport. The summary sits ABOVE every + chip group, so after tapping a chip we may need to scroll back up to it.""" + for _ in range(max_up + 1): + t = _summary_text() + if t is not None: + return t + scroll_up(0.5) + return _summary_text() + + +def _tap_switch(row_label): + """Flip the toggle whose row TEXT is `row_label` by tapping the far-right + switch (the label/icon nodes are NOT the clickable target). The x is derived + from screen width, never a literal. Returns the row y on success, else None.""" + n = find_node(ui(), text=row_label) + if not n or "_center" not in n: + return None + s = get_screen_info() + tap(int(s["width"] * 0.93), n["_center"][1]) + settle("tap") + return n["_center"][1] + + +def _switch_is_on(row_label, save_path): + """Read a Compose switch ON/OFF from a screenshot: ON => the blue thumb has + shifted into the LEFT third of the track (b-r > 40); OFF => grey. Returns + True/False/None. Screenshot is saved so a VLM question can reuse the moment.""" + n = find_node(ui(), text=row_label) + if not n or "_center" not in n: + return None + if not screencap(save_path) or not _HAVE_PIL: + return None + try: + im = Image.open(save_path).convert("RGB") + except Exception: + return None + s = get_screen_info() + r, g, b = im.getpixel((int(s["width"] * 0.885), n["_center"][1])) + return (b - r) > 40 + + +def _ensure_switch(row_label, want_on, tmp_name="_ensure.png"): + """Bring the toggle `row_label` to the desired ON/OFF state via the GUI, so a + test never depends on the state a previous test left behind (isolation rule). + Returns the resulting bool state, or None if the switch could not be read.""" + scroll_into_view(row_label) + path = os.path.join(RESULTS_DIR, "screenshots", tmp_name) + cur = _switch_is_on(row_label, path) + if cur is None: + return None + if cur != want_on: + _tap_switch(row_label) + cur = _switch_is_on(row_label, path) + return cur + + +def _ensure_rename_dialog_on(): + """Guarantee the 'Show rename dialog after recording is completed' setting is ON + (its default), via Settings, then return to Home — so the post-record dialog + reliably appears. Isolation: a checkbox test must not fail because an earlier + test left the setting OFF. Returns True on success.""" + if not and_enter_settings(): + return False + _ensure_switch("Show rename dialog after recording is completed", True) + b = find_node(ui(), content_desc="Navigate back") + if b: + tap_node(b) + settle("tap") + return find_node(ui(), text="Record") is not None + + +def _big_timer(nodes=None): + """The large centre timer (mm:ss) shown while recording (y≈1733).""" + nodes = ui() if nodes is None else nodes + for n in nodes: + if (n.get("text", "").count(":") == 1 and "_center" in n + and 1650 < n["_center"][1] < 1820): + return n.get("text") + return None + + +def _record_label(nodes=None): + """The bottom-centre record button label: 'Record' | 'Pause' | 'Resume'.""" + nodes = ui() if nodes is None else nodes + for lbl in ("Pause", "Resume", "Record"): + n = find_node(nodes, text=lbl) + if n and "_center" in n and n["_center"][1] > 2100: + return lbl + return None + + +def _abandon_recording_cleanly(): + """Stop any in-progress/paused recording and dismiss the post-record dialog + with Cancel (NEVER Delete). Leaves the app on a clean Home surface.""" + for _ in range(2): + stop = find_node(ui(), content_desc="Stop") + if stop: + tap_node(stop) + settle("tap") + break + c = find_node_ci(ui(), "Cancel") + if c and is_safe(c): + tap_node(c) + settle("tap") + + +def _select_chip(label): + """Scroll a chip with text `label` into view and tap it. Returns True/False.""" + n = scroll_into_view(label) + return tap_node(n) if n else False + + +# ════════════════════════════════════════════════════════════════════════════════ +# 1. Dark theme toggle — flip + rendered-colour consequence (the flagship) +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("states_dark_theme", "states_dark_theme_on_vlm", + "states_dark_theme_off_vlm")) +def test_dark_theme_flip_changes_background(): + restart_app() + wait_for_foreground() + _clear_startup_dialogs() + if not and_enter_settings(): + record("states_dark_theme", False, + "setup_failed: could not open Settings", + depth=1, jump_kind="transition", + expect="Dark theme switch on->off; background dark->light") + vlm_assert("states_dark_theme_on", "unreached", RESULTS_DIR, tag="color") + vlm_assert("states_dark_theme_off", "unreached", RESULTS_DIR, tag="color") + return + if find_node(ui(), content_desc="Dark theme") is None: + record("states_dark_theme", False, + "feature_missing: no 'Dark theme' toggle", + depth=1, jump_kind="transition", + expect="Dark theme switch on->off; background dark->light") + vlm_assert("states_dark_theme_on", "unreached", RESULTS_DIR, tag="color") + vlm_assert("states_dark_theme_off", "unreached", RESULTS_DIR, tag="color") + return + + on_shot = os.path.join(RESULTS_DIR, "screenshots", "states_dark_theme_on_vlm.png") + off_shot = os.path.join(RESULTS_DIR, "screenshots", "states_dark_theme_off_vlm.png") + before = _switch_is_on("Dark theme", on_shot) # default ON (dark) + # VLM #1: dark background while the switch is ON + vlm_assert("states_dark_theme_on", + "Is the whole screen background a very dark, near-black colour " + "(dark theme), with light-coloured text on top of it?", + RESULTS_DIR, tag="color") + + _tap_switch("Dark theme") # -> OFF (light) + after = _switch_is_on("Dark theme", off_shot) + # VLM #2: light background after turning the switch OFF + vlm_assert("states_dark_theme_off", + "Is the whole screen background now a light, near-white colour " + "(light theme), rather than dark?", + RESULTS_DIR, tag="color") + + ok = (before is True and after is False) + record("states_dark_theme", ok, + "" if ok else "behavior_wrong: Dark-theme switch did not flip " + f"on->off (before={before}, after={after})", + depth=1, jump_kind="transition", + expect="Dark theme switch on->off; background changed dark->light") + + # restore Dark theme ON + _tap_switch("Dark theme") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 2. Dynamic theme colors toggle — flip OFF->ON, paired with a rendered-switch read +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("states_dynamic_theme", "states_dynamic_theme_on_vlm")) +def test_dynamic_theme_toggle_flips(): + restart_app() + wait_for_foreground() + _clear_startup_dialogs() + if not and_enter_settings(): + record("states_dynamic_theme", False, + "setup_failed: could not open Settings", + depth=1, jump_kind="transition", + expect="Dynamic theme colors switch off->on") + vlm_assert("states_dynamic_theme_on", "unreached", RESULTS_DIR, tag="color") + return + if find_node(ui(), content_desc="Dynamic theme colors") is None: + record("states_dynamic_theme", False, + "feature_missing: no 'Dynamic theme colors' toggle", + depth=1, jump_kind="transition", + expect="Dynamic theme colors switch off->on") + vlm_assert("states_dynamic_theme_on", "unreached", RESULTS_DIR, tag="color") + return + + off_shot = os.path.join(RESULTS_DIR, "screenshots", "_dyn_off.png") + on_shot = os.path.join(RESULTS_DIR, "screenshots", "states_dynamic_theme_on_vlm.png") + before = _switch_is_on("Dynamic theme colors", off_shot) # default OFF + _tap_switch("Dynamic theme colors") # -> ON + after = _switch_is_on("Dynamic theme colors", on_shot) + + ok = (before is False and after is True) + record("states_dynamic_theme", ok, + "" if ok else "behavior_wrong: 'Dynamic theme colors' switch did not " + f"flip off->on (before={before}, after={after})", + depth=1, jump_kind="transition", + expect="Dynamic theme colors switch off->on") + + # VLM: the switch is rendered ON (blue track, thumb to the right) + vlm_assert("states_dynamic_theme_on", + "Look at the 'Dynamic theme colors' row. Is its toggle switch in " + "the ON state — a filled blue/coloured track with the round thumb " + "positioned on the RIGHT side?", + RESULTS_DIR, tag="color") + + _tap_switch("Dynamic theme colors") # restore OFF + + +# ════════════════════════════════════════════════════════════════════════════════ +# 3. Keep-screen-ON toggle — flip OFF->ON + a rendered OFF-switch VLM +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("states_keep_screen_on", "states_keep_screen_off_vlm")) +def test_keep_screen_on_toggle_flips(): + restart_app() + wait_for_foreground() + _clear_startup_dialogs() + if not and_enter_settings(): + record("states_keep_screen_on", False, + "setup_failed: could not open Settings", + depth=1, jump_kind="transition", + expect="Keep screen ON switch off->on") + vlm_assert("states_keep_screen_off", "unreached", RESULTS_DIR, tag="color") + return + if find_node(ui(), content_desc="Keep screen ON while recording") is None: + record("states_keep_screen_on", False, + "feature_missing: no 'Keep screen ON while recording' toggle", + depth=1, jump_kind="transition", + expect="Keep screen ON switch off->on") + vlm_assert("states_keep_screen_off", "unreached", RESULTS_DIR, tag="color") + return + + off_shot = os.path.join(RESULTS_DIR, "screenshots", "states_keep_screen_off_vlm.png") + on_shot = os.path.join(RESULTS_DIR, "screenshots", "_keep_on.png") + before = _switch_is_on("Keep screen ON while recording", off_shot) # default OFF + # VLM: switch rendered OFF (grey track, thumb LEFT) in the default state + vlm_assert("states_keep_screen_off", + "Look at the 'Keep screen ON while recording' row. Is its toggle " + "switch in the OFF state — a grey/unfilled track with the round " + "thumb positioned on the LEFT side?", + RESULTS_DIR, tag="color") + + _tap_switch("Keep screen ON while recording") # -> ON + after = _switch_is_on("Keep screen ON while recording", on_shot) + + ok = (before is False and after is True) + record("states_keep_screen_on", ok, + "" if ok else "behavior_wrong: 'Keep screen ON' switch did not flip " + f"off->on (before={before}, after={after})", + depth=1, jump_kind="transition", + expect="Keep screen ON switch off->on") + + _tap_switch("Keep screen ON while recording") # restore OFF + + +# ════════════════════════════════════════════════════════════════════════════════ +# 4. SETTINGS PERSISTENCE — Keep-screen-ON survives force-stop + relaunch +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("states_keep_screen_persists",)) +def test_keep_screen_on_persists_across_process_death(): + restart_app() + wait_for_foreground() + _clear_startup_dialogs() + if not and_enter_settings(): + record("states_keep_screen_persists", False, + "setup_failed: could not open Settings", + depth=1, jump_kind="transition", + expect="Keep screen ON stays ON after force-stop+relaunch") + return + if find_node(ui(), content_desc="Keep screen ON while recording") is None: + record("states_keep_screen_persists", False, + "feature_missing: no 'Keep screen ON while recording' toggle", + depth=1, jump_kind="transition", + expect="Keep screen ON stays ON after force-stop+relaunch") + return + + before = _switch_is_on("Keep screen ON while recording", + os.path.join(RESULTS_DIR, "screenshots", "_persist_pre.png")) + _tap_switch("Keep screen ON while recording") # flip it (default OFF -> ON) + flipped = _switch_is_on("Keep screen ON while recording", + os.path.join(RESULTS_DIR, "screenshots", "_persist_flip.png")) + + # kill the process and relaunch, then re-navigate to Settings + force_stop_and_relaunch() + wait_for_foreground() + _clear_startup_dialogs() + reopened = and_enter_settings() + scroll_into_view("Keep screen ON while recording") + persisted = _switch_is_on("Keep screen ON while recording", + os.path.join(RESULTS_DIR, "screenshots", "_persist_post.png")) + + ok = (reopened and flipped is True and persisted == flipped) + record("states_keep_screen_persists", ok, + "" if ok else "behavior_wrong: 'Keep screen ON' did not persist across " + f"process death (flipped={flipped}, " + f"after_relaunch={persisted})", + depth=1, jump_kind="transition", + expect="Keep screen ON flipped to ON stays ON after force-stop+relaunch") + + # restore OFF + _tap_switch("Keep screen ON while recording") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 5. Show-rename-dialog toggle — behavioural consequence on Stop (flagship rule) +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("states_show_rename_dialog",)) +def test_show_rename_dialog_toggle_controls_post_record_dialog(): + restart_app() + wait_for_foreground() + _clear_startup_dialogs() + if not and_enter_settings(): + record("states_show_rename_dialog", False, + "setup_failed: could not open Settings", + depth=1, jump_kind="transition", + expect="toggle OFF -> Stop shows NO dialog; ON -> dialog appears") + return + label = "Show rename dialog after recording is completed" + if find_node(ui(), content_desc=label) is None: + record("states_show_rename_dialog", False, + "feature_missing: no 'Show rename dialog' toggle", + depth=1, jump_kind="transition", + expect="toggle OFF -> Stop shows NO dialog; ON -> dialog appears") + return + + # Force the toggle OFF (regardless of the persisted starting state), then record + # a short clip and Stop -> the post-record dialog must NOT appear. + if _ensure_switch(label, False) is not False: + record("states_show_rename_dialog", False, + "setup_failed: could not set 'Show rename dialog' to OFF", + depth=1, jump_kind="transition", + expect="toggle OFF -> Stop shows NO dialog; ON -> dialog appears") + return + tap_node(find_node(ui(), content_desc="Navigate back")) + settle("tap") + rec = find_node(ui(), text="Record") + if rec is None: + # restore & bail + if and_enter_settings(): + _tap_switch(label) + record("states_show_rename_dialog", False, + "setup_failed: Record button not found on Home", + depth=1, jump_kind="transition", + expect="toggle OFF -> Stop shows NO dialog; ON -> dialog appears") + return + tap_node(rec) + time.sleep(2) + stop = find_node(ui(), content_desc="Stop") + if stop: + tap_node(stop) + settle("tap") + settle("tap") + dialog_when_off = find_node(ui(), text="Update name and description") is not None + # if a dialog unexpectedly showed, cancel it (never Delete) + c = find_node_ci(ui(), "Cancel") + if c and is_safe(c): + tap_node(c) + settle("tap") + + # Turn the toggle back ON, record again, Stop -> dialog MUST appear. + if not and_enter_settings(): + record("states_show_rename_dialog", False, + "setup_failed: could not re-open Settings to restore toggle", + depth=1, jump_kind="transition", + expect="toggle OFF -> Stop shows NO dialog; ON -> dialog appears") + return + _ensure_switch(label, True) # force ON (the default) + tap_node(find_node(ui(), content_desc="Navigate back")) + settle("tap") + tap_node(find_node(ui(), text="Record")) + time.sleep(2) + stop = find_node(ui(), content_desc="Stop") + if stop: + tap_node(stop) + settle("tap") + settle("tap") + dialog_when_on = find_node(ui(), text="Update name and description") is not None + c = find_node_ci(ui(), "Cancel") + if c and is_safe(c): + tap_node(c) + settle("tap") + + ok = (dialog_when_off is False and dialog_when_on is True) + record("states_show_rename_dialog", ok, + "" if ok else "behavior_wrong: toggling 'Show rename dialog' did not " + f"gate the post-record dialog (OFF->dialog={dialog_when_off}, " + f"ON->dialog={dialog_when_on})", + depth=1, jump_kind="transition", + expect="toggle OFF -> Stop shows NO 'Update name and description' " + "dialog; toggle ON -> the dialog appears") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 6. Sort-mode selection — subtitle transition (same session; sort does NOT persist) +# ════════════════════════════════════════════════════════════════════════════════ +def _sort_subtitle(nodes=None): + nodes = ui() if nodes is None else nodes + for n in nodes: + if n.get("text", "").startswith("By "): + return n.get("text") + return None + + +@and_test(expects=("states_sort_mode",)) +def test_sort_mode_changes_subtitle(): + restart_app() + wait_for_foreground() + _clear_startup_dialogs() + if not and_enter_records(): + record("states_sort_mode", False, + "setup_failed: could not open Records", + depth=1, jump_kind="value", + expect="subtitle 'By date (newest)' -> 'By name (A-Z)'") + return + before = _sort_subtitle() + # sort menu = the left-most toolbar 'Menu' icon (after 'Filter'), in the top band + toolbar_menus = sorted( + (m for m in find_nodes(ui(), content_desc="Menu") + if m.get("_center") and m["_center"][1] < 300), + key=lambda m: m["_center"][0]) + if not toolbar_menus: + record("states_sort_mode", False, + "feature_missing: no sort menu icon in the Records toolbar", + depth=1, jump_kind="value", + expect="subtitle 'By date (newest)' -> 'By name (A-Z)'") + return + tap_node(toolbar_menus[0]) + settle("tap") + opt = find_node_ci(ui(), "By name (A-Z)") + if opt is None: + record("states_sort_mode", False, + "feature_missing: no 'By name (A-Z)' sort option", + depth=1, jump_kind="value", + expect="subtitle 'By date (newest)' -> 'By name (A-Z)'") + return + tap_node(opt) + settle("tap") + after = _sort_subtitle() + + ok = (before is not None and after is not None and after != before + and "name" in after.lower()) + record("states_sort_mode", ok, + "" if ok else "behavior_wrong: choosing 'By name (A-Z)' did not update " + f"the sort subtitle (before={before!r}, after={after!r})", + depth=1, jump_kind="value", + expect="toolbar sort subtitle 'By date (newest)' -> 'By name (A-Z)'") + + # restore to By date (newest) + toolbar_menus = sorted( + (m for m in find_nodes(ui(), content_desc="Menu") + if m.get("_center") and m["_center"][1] < 300), + key=lambda m: m["_center"][0]) + if toolbar_menus: + tap_node(toolbar_menus[0]) + settle("tap") + d = find_node_ci(ui(), "By date (newest)") + if d: + tap_node(d) + + +# ════════════════════════════════════════════════════════════════════════════════ +# 7. Recording-format chip — selection + summary consequence + selected-pill VLM +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("states_format_chip", "states_format_chip_wav_vlm")) +def test_format_chip_selection_updates_summary(): + restart_app() + wait_for_foreground() + _clear_startup_dialogs() + if not and_enter_settings(): + record("states_format_chip", False, + "setup_failed: could not open Settings", + depth=1, jump_kind="value", + expect="summary leading token M4a -> Wav") + vlm_assert("states_format_chip_wav", "unreached", RESULTS_DIR, tag="shape") + return + # ensure pristine M4a first, capture the M4a summary + _select_chip("M4a") + before = _read_summary() + if find_node(ui(), text="Wav") is None: + record("states_format_chip", False, + "feature_missing: no 'Wav' recording-format chip", + depth=1, jump_kind="value", + expect="summary leading token M4a -> Wav") + vlm_assert("states_format_chip_wav", "unreached", RESULTS_DIR, tag="shape") + return + + _select_chip("Wav") + # VLM FIRST, while the 'Recording format:' row is on-screen: the selected 'Wav' + # chip is marked with a round checkmark (tick) icon; the unselected '3gp' chip + # has none. Reading the summary scrolls the list up, so it comes AFTER. + scroll_into_view("Wav") + vlm_assert("states_format_chip_wav", + "In the 'Recording format:' chip row, does the 'Wav' chip have a " + "small round CHECKMARK (tick) icon to the LEFT of the word 'Wav', " + "marking it as the selected chip, while the '3gp' chip has no such " + "checkmark?", + RESULTS_DIR, tag="shape") + after = _read_summary() + + ok = (before is not None and after is not None + and before.strip().lower().startswith("m4a") + and after.strip().lower().startswith("wav")) + record("states_format_chip", ok, + "" if ok else "behavior_wrong: selecting 'Wav' did not change the " + f"recording-settings summary (before={before!r}, " + f"after={after!r})", + depth=1, jump_kind="value", + expect="Recording-settings summary leading token 'M4a...' -> 'Wav...'") + + _select_chip("M4a") # restore default format + + +# ════════════════════════════════════════════════════════════════════════════════ +# 8. Bitrate chip — 128 -> 96 summary consequence + selected-pill VLM +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("states_bitrate_chip", "states_bitrate_chip_96_vlm")) +def test_bitrate_chip_selection_updates_summary(): + restart_app() + wait_for_foreground() + _clear_startup_dialogs() + if not and_enter_settings(): + record("states_bitrate_chip", False, + "setup_failed: could not open Settings", + depth=1, jump_kind="value", + expect="summary '128 kbps' -> '96 kbps'") + vlm_assert("states_bitrate_chip_96", "unreached", RESULTS_DIR, tag="shape") + return + # normalise to the recon default (128 kbps) so before is deterministic + _select_chip("128 kbps") + before = _read_summary() + if scroll_into_view("96 kbps") is None: + record("states_bitrate_chip", False, + "feature_missing: no '96 kbps' bitrate chip", + depth=1, jump_kind="value", + expect="summary '128 kbps' -> '96 kbps'") + vlm_assert("states_bitrate_chip_96", "unreached", RESULTS_DIR, tag="shape") + return + + _select_chip("96 kbps") + # VLM FIRST, while the Bitrate row is still on-screen: the selected '96 kbps' + # chip carries a round checkmark (tick) icon to the left of its label; the + # now-unselected '128 kbps' chip does not. (Reading the summary scrolls the + # list back to the top, so it must come AFTER the screenshot.) + scroll_into_view("96 kbps") + vlm_assert("states_bitrate_chip_96", + "In the 'Bitrate:' chip row, does the '96 kbps' chip have a small " + "round CHECKMARK (tick) icon to the LEFT of its label, marking it as " + "the selected bitrate, while the '128 kbps' chip has no checkmark?", + RESULTS_DIR, tag="shape") + after = _read_summary() + + ok = (before is not None and after is not None + and "128 kbps" in before and "96 kbps" in after + and "128 kbps" not in after) + record("states_bitrate_chip", ok, + "" if ok else "behavior_wrong: selecting '96 kbps' did not change the " + f"summary bitrate (before={before!r}, after={after!r})", + depth=1, jump_kind="value", + expect="Recording-settings summary '...128 kbps...' -> '...96 kbps...'") + + _select_chip("128 kbps") # restore default bitrate + + +# ════════════════════════════════════════════════════════════════════════════════ +# 9. Sample-rate chip — 44.1kHz -> 48kHz summary consequence +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("states_sample_rate_chip",)) +def test_sample_rate_chip_selection_updates_summary(): + restart_app() + wait_for_foreground() + _clear_startup_dialogs() + if not and_enter_settings(): + record("states_sample_rate_chip", False, + "setup_failed: could not open Settings", + depth=1, jump_kind="value", + expect="summary '44.1kHz' -> '48kHz'") + return + _select_chip("44.1kHz") + before = _read_summary() + if scroll_into_view("48kHz") is None: + record("states_sample_rate_chip", False, + "feature_missing: no '48kHz' sample-rate chip", + depth=1, jump_kind="value", + expect="summary '44.1kHz' -> '48kHz'") + return + + _select_chip("48kHz") + after = _read_summary() + + ok = (before is not None and after is not None + and "44.1kHz" in before and "48kHz" in after and "44.1kHz" not in after) + record("states_sample_rate_chip", ok, + "" if ok else "behavior_wrong: selecting '48kHz' did not change the " + f"summary sample rate (before={before!r}, after={after!r})", + depth=1, jump_kind="value", + expect="Recording-settings summary '...44.1kHz...' -> '...48kHz...'") + + _select_chip("44.1kHz") # restore default sample rate + + +# ════════════════════════════════════════════════════════════════════════════════ +# 10. Channel-count chip — Stereo -> Mono summary consequence +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("states_channel_chip",)) +def test_channel_chip_selection_updates_summary(): + restart_app() + wait_for_foreground() + _clear_startup_dialogs() + if not and_enter_settings(): + record("states_channel_chip", False, + "setup_failed: could not open Settings", + depth=1, jump_kind="value", + expect="summary trailing token 'Stereo' -> 'Mono'") + return + _select_chip("Stereo") + before = _read_summary() + if scroll_into_view("Mono") is None: + record("states_channel_chip", False, + "feature_missing: no 'Mono' channel-count chip", + depth=1, jump_kind="value", + expect="summary trailing token 'Stereo' -> 'Mono'") + return + + _select_chip("Mono") + after = _read_summary() + + ok = (before is not None and after is not None + and before.strip().endswith("Stereo") and after.strip().endswith("Mono")) + record("states_channel_chip", ok, + "" if ok else "behavior_wrong: selecting 'Mono' did not change the " + f"summary channel count (before={before!r}, after={after!r})", + depth=1, jump_kind="value", + expect="Recording-settings summary trailing token 'Stereo' -> 'Mono'") + + _select_chip("Stereo") # restore default channel + + +# ════════════════════════════════════════════════════════════════════════════════ +# 11. Record -> Pause state machine (label + timer-freeze consequence) +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("states_record_pause",)) +def test_record_then_pause_freezes_timer(): + restart_app() + wait_for_foreground() + _clear_startup_dialogs() + activity = get_current_activity() + rec = find_node(ui(), text="Record") + if rec is None: + record("states_record_pause", False, + "setup_failed: Record button not found on Home", + depth=0, jump_kind="transition", + expect="label Record->Pause, Stop appears; Pause freezes the timer") + return + + tap_node(rec) + settle("tap") + rec_label = _record_label() + stop_present = find_node(ui(), content_desc="Stop") is not None + recording_text = find_node(ui(), text="Recording…") is not None + t_run = _big_timer() + time.sleep(2.2) + t_run2 = _big_timer() + advanced = (t_run is not None and t_run2 is not None and t_run2 != t_run) + + # Pause -> timer must FREEZE and the label must become 'Resume' + pause_btn = find_node(ui(), text="Pause") + if pause_btn is None: + _abandon_recording_cleanly() + record("states_record_pause", False, + "behavior_wrong: no 'Pause' label after starting a recording " + f"(label was {rec_label!r})", + depth=0, jump_kind="transition", + expect="label Record->Pause, Stop appears; Pause freezes the timer") + return + tap_node(pause_btn) + settle("tap") + paused_label = _record_label() + t_pause = _big_timer() + time.sleep(2.5) + t_pause2 = _big_timer() + frozen = (t_pause is not None and t_pause2 is not None and t_pause2 == t_pause) + + same_activity = (get_current_activity() == activity) + ok = (rec_label == "Pause" and stop_present and recording_text and advanced + and paused_label == "Resume" and frozen and same_activity) + record("states_record_pause", ok, + "" if ok else "behavior_wrong: Record->Pause did not transition as " + f"observed (rec_label={rec_label}, stop={stop_present}, " + f"advanced={advanced}, paused_label={paused_label}, " + f"frozen={frozen})", + depth=0, jump_kind="transition", + expect="Record: label 'Pause'+Stop+'Recording…'+timer advancing; " + "Pause: label 'Resume' and the timer stops advancing") + + _abandon_recording_cleanly() + + +# ════════════════════════════════════════════════════════════════════════════════ +# 12. Pause -> Resume state machine (timer advances again) +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("states_record_resume",)) +def test_pause_then_resume_advances_timer(): + restart_app() + wait_for_foreground() + _clear_startup_dialogs() + rec = find_node(ui(), text="Record") + if rec is None: + record("states_record_resume", False, + "setup_failed: Record button not found on Home", + depth=0, jump_kind="transition", + expect="Resume: label 'Resume'->'Pause' and timer advances again") + return + tap_node(rec) + settle("tap") + time.sleep(1.2) + pause_btn = find_node(ui(), text="Pause") + if pause_btn is None: + _abandon_recording_cleanly() + record("states_record_resume", False, + "behavior_wrong: no 'Pause' label after starting a recording", + depth=0, jump_kind="transition", + expect="Resume: label 'Resume'->'Pause' and timer advances again") + return + tap_node(pause_btn) + settle("tap") + resume_btn = find_node(ui(), text="Resume") + if resume_btn is None: + _abandon_recording_cleanly() + record("states_record_resume", False, + "behavior_wrong: no 'Resume' label after pausing", + depth=0, jump_kind="transition", + expect="Resume: label 'Resume'->'Pause' and timer advances again") + return + + t_before = _big_timer() + tap_node(resume_btn) + settle("tap") + resumed_label = _record_label() + time.sleep(2.5) + t_after = _big_timer() + advanced_again = (t_before is not None and t_after is not None + and t_after != t_before) + + ok = (resumed_label == "Pause" and advanced_again) + record("states_record_resume", ok, + "" if ok else "behavior_wrong: Resume did not restart the timer / label " + f"(resumed_label={resumed_label}, " + f"t_before={t_before}, t_after={t_after})", + depth=0, jump_kind="transition", + expect="Resume: label reverts to 'Pause' and the timer advances again") + + _abandon_recording_cleanly() + + +# ════════════════════════════════════════════════════════════════════════════════ +# 13. Play -> Stop state machine on a loaded record + play/pause glyph VLM +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("states_play_stop", "states_play_glyph_vlm")) +def test_play_then_stop_state_machine(): + restart_app() + wait_for_foreground() + _clear_startup_dialogs() + play = find_node(ui(), content_desc="Play") + if play is None: + # create a record so Home has a loaded playback panel + rec = find_node(ui(), text="Record") + if rec: + tap_node(rec) + time.sleep(2) + stop = find_node(ui(), content_desc="Stop") + if stop: + tap_node(stop) + settle("tap") + # save silently or via dialog Save (NEVER Delete) so a record loads + save = find_node_ci(ui(), "Save") + if save and is_safe(save): + tap_node(save) + settle("tap") + play = find_node(ui(), content_desc="Play") + if play is None: + record("states_play_stop", False, + "setup_failed: no 'Play' control (no loaded record on Home)", + depth=0, jump_kind="transition", + expect="Play -> 'Stop' appears; Stop -> 'Stop' disappears") + vlm_assert("states_play_glyph", "unreached", RESULTS_DIR, tag="shape") + return + + stop_before = find_node(ui(), content_desc="Stop") is not None + tap_node(play) + settle("tap") + stop_after = find_node(ui(), content_desc="Stop") is not None + # VLM: the centre transport glyph is now a PAUSE icon (two vertical bars), + # not the triangular play icon. + vlm_assert("states_play_glyph", + "In the middle of the screen, just below the waveform and above the " + "large time display, there is a small playback-control icon. Is that " + "icon a PAUSE symbol (two short vertical bars side by side), rather " + "than a triangular play (▶) arrow?", + RESULTS_DIR, tag="shape") + + # Stop -> the 'Stop' affordance disappears and 'Play' returns + stop = find_node(ui(), content_desc="Stop") + if stop: + tap_node(stop) + settle("tap") + stop_final = find_node(ui(), content_desc="Stop") is not None + play_final = find_node(ui(), content_desc="Play") is not None + + ok = (stop_before is False and stop_after is True + and stop_final is False and play_final is True) + record("states_play_stop", ok, + "" if ok else "behavior_wrong: Play/Stop did not transition as observed " + f"(stop_before={stop_before}, stop_after={stop_after}, " + f"stop_final={stop_final}, play_final={play_final})", + depth=0, jump_kind="transition", + expect="Play: a 'Stop' button appears; Stop: it disappears and 'Play' " + "returns") + + +# ════════════════════════════════════════════════════════════════════════════════ +# 14. Post-record dialog — 'Write description' checkbox flip (checked true->false) +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("states_dialog_write_desc_checkbox",)) +def test_post_record_write_description_checkbox_flips(): + restart_app() + wait_for_foreground() + _clear_startup_dialogs() + if not _ensure_rename_dialog_on(): + record("states_dialog_write_desc_checkbox", False, + "setup_failed: could not enable the post-record dialog setting", + depth=1, jump_kind="transition", + expect="'Write description' checkbox checked true->false") + return + rec = find_node(ui(), text="Record") + if rec is None: + record("states_dialog_write_desc_checkbox", False, + "setup_failed: Record button not found on Home", + depth=1, jump_kind="transition", + expect="'Write description' checkbox checked true->false") + return + tap_node(rec) + time.sleep(2) + stop = find_node(ui(), content_desc="Stop") + if stop: + tap_node(stop) + settle("tap") + settle("tap") + and_enter("Update name and description dialog") + + dialog = find_node(ui(), text="Update name and description") + checks = find_by_class(ui(), "CheckBox") + if dialog is None or not checks: + _abandon_recording_cleanly() + record("states_dialog_write_desc_checkbox", False, + "setup_failed: post-record dialog / checkboxes not found", + depth=1, jump_kind="transition", + expect="'Write description' checkbox checked true->false") + return + + # 'Write description into the audio file' is the checkbox next to that label; + # locate it by the checkbox whose y is closest to the label's y. + lbl = find_node(ui(), text="Write description into the audio file") + cb = None + if lbl and "_center" in lbl: + cb = min(checks, key=lambda c: abs(c.get("_center", (0, 0))[1] + - lbl["_center"][1])) + cb = cb or checks[0] + before = cb.get("checked") + tap_node(cb) + settle("tap") + fresh = find_closest_match(find_by_class(ui(), "CheckBox") or ui(), cb) or {} + after = fresh.get("checked") + + ok = (before in ("true", "false") and after in ("true", "false") + and after != before) + record("states_dialog_write_desc_checkbox", ok, + "" if ok else "behavior_wrong: 'Write description' checkbox did not " + f"flip its checked attribute (before={before}, " + f"after={after})", + depth=1, jump_kind="transition", + expect="'Write description into the audio file' checkbox " + "checked true->false") + + _abandon_recording_cleanly() + + +# ════════════════════════════════════════════════════════════════════════════════ +# 15. Post-record dialog — "Don't ask again" checkbox flip (checked false->true) +# (flip it then CANCEL so the dialog stays enabled for later runs) +# ════════════════════════════════════════════════════════════════════════════════ +@and_test(expects=("states_dialog_dont_ask_checkbox",)) +def test_post_record_dont_ask_checkbox_flips(): + restart_app() + wait_for_foreground() + _clear_startup_dialogs() + if not _ensure_rename_dialog_on(): + record("states_dialog_dont_ask_checkbox", False, + "setup_failed: could not enable the post-record dialog setting", + depth=1, jump_kind="transition", + expect="'Don't ask again' checkbox checked false->true") + return + rec = find_node(ui(), text="Record") + if rec is None: + record("states_dialog_dont_ask_checkbox", False, + "setup_failed: Record button not found on Home", + depth=1, jump_kind="transition", + expect="'Don't ask again' checkbox checked false->true") + return + tap_node(rec) + time.sleep(2) + stop = find_node(ui(), content_desc="Stop") + if stop: + tap_node(stop) + settle("tap") + settle("tap") + and_enter("Update name and description dialog") + + dialog = find_node(ui(), text="Update name and description") + checks = find_by_class(ui(), "CheckBox") + if dialog is None or len(checks) < 2: + _abandon_recording_cleanly() + record("states_dialog_dont_ask_checkbox", False, + "setup_failed: post-record dialog / 'Don't ask again' checkbox " + "not found", + depth=1, jump_kind="transition", + expect="'Don't ask again' checkbox checked false->true") + return + + # "Don't ask again" is the LOWER checkbox (default unchecked = false). + cb = max(checks, key=lambda c: c.get("_center", (0, 0))[1]) + before = cb.get("checked") + tap_node(cb) + settle("tap") + fresh = find_closest_match(find_by_class(ui(), "CheckBox") or ui(), cb) or {} + after = fresh.get("checked") + + ok = (before == "false" and after == "true") + record("states_dialog_dont_ask_checkbox", ok, + "" if ok else "behavior_wrong: 'Don't ask again' checkbox did not flip " + f"checked false->true (before={before}, after={after})", + depth=1, jump_kind="transition", + expect="'Don't ask again' checkbox checked false->true") + + # CANCEL (never Save) so 'Don't ask again' is NOT persisted and the dialog + # stays enabled for every later test/lane. + _abandon_recording_cleanly() + + +# ════════════════════════════════════════════════════════════════════════════════ +TESTS = [ + test_dark_theme_flip_changes_background, + test_dynamic_theme_toggle_flips, + test_keep_screen_on_toggle_flips, + test_keep_screen_on_persists_across_process_death, + test_show_rename_dialog_toggle_controls_post_record_dialog, + test_sort_mode_changes_subtitle, + test_format_chip_selection_updates_summary, + test_bitrate_chip_selection_updates_summary, + test_sample_rate_chip_selection_updates_summary, + test_channel_chip_selection_updates_summary, + test_record_then_pause_freezes_timer, + test_pause_then_resume_advances_timer, + test_play_then_stop_state_machine, + test_post_record_write_description_checkbox_flips, + test_post_record_dont_ask_checkbox_flips, +] + +if __name__ == "__main__": + run_suite(TESTS, "states") diff --git a/android/dimowner-audiorecorder/tests/test_android_structure.py b/android/dimowner-audiorecorder/tests/test_android_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..4d145e75ad1a5bd4a99013d3d9d476a8ddbdeee5 --- /dev/null +++ b/android/dimowner-audiorecorder/tests/test_android_structure.py @@ -0,0 +1,731 @@ +#!/usr/bin/env python3 +"""STRUCTURE lane — Audio Recorder (Jetpack Compose single-Activity recorder). + +This lane owns exactly two things: + 1. THE GATE — the app launches, is foreground, and its top-level surfaces exist + (Home title bar + the three bottom controls + the centre waveform panel). + jump_kind "none", kept <=30% of the suite's RULE cases. + 2. TREE-SHAPE deltas — an interaction that changes the tree's SHAPE: a mode that + adds/removes a class of widget (Record -> "Stop"/"Pause"/"Recording…"), a + dialog that adds a new window layer (Stop -> post-record dialog EditText+ + CheckBox subtree; pencil -> rename EditText), an empty->populated surface + (Home -> Records rows; Home -> Settings toggle list; overflow -> 7-item menu; + Records row 3-dot -> context menu at depth 2; Settings scroll -> different + node set). Recorded as jump_kind="transition" (or "value" for an asserted + count) and REVERSED to assert restore where a reverse exists. + +We CEDE strings->text, checked/selected->states, reachability->navigation, +computed values->computation, CRUD->interaction. We may CROSS to a surface but we +assert only SHAPE there. + +GROUND TRUTH (probed on the running original before authoring): + * Compose renders NO "ViewGroup"/"Switch"; the tree is View/Button/TextView/ + FrameLayout/LinearLayout/ComposeView/SeekBar. Toggles are View+content-desc. + So shape is measured by content-desc set / and_showing() size / EditText / + CheckBox counts, never by ViewGroup/Switch counts. + * Home with a record loaded (both this install and a fresh eval emulator that + ships 'Record-1' land here): content-descs {Import, Menu, Play, Rename, + Settings, Records}; texts include "Audio Recorder", "00:00", record name, + "Record"; a SeekBar; and_showing~13. A wider waveform of the loaded file is + drawn centre-screen with a time axis. (Idle/no-record Home instead draws a + small equalizer-style glyph — either way a waveform visualization is rendered.) + * Record tap -> content-desc "Stop" appears, texts "Recording…"/"Pause" appear, + Play/Rename/Menu/Import disappear. + * Stop -> "Update name and description" dialog: 2 EditText + 2 CheckBox appear + (Home has 0 of each). NOTE: this dialog is GATED by the Settings toggle "Show + rename dialog after recording is completed"; a sibling lane toggles it OFF, so + the post-record-dialog tests ensure it ON first (and_ensure_rename_dialog_on). + * Home pencil ("Rename") -> "Update name" dialog: EditText 0->1. This dialog is + UNCONDITIONAL (no setting guards it). + * Records (bottom-right) -> content-desc "Navigate back" + "Filter" + row texts + ("Today", "Record-1") appear; and_showing ~14. + * Records row 3-dot ("Menu", right-edge icon below the toolbar) -> the 7-item + context menu (depth 2). + * Settings (bottom-left) -> long toggle+chip list; and_showing jumps to ~38 and + changes again on scroll. + * Overflow "Menu" -> 7 items {Share, Information, Rename, Edit description, + Open with…, Save as…, Delete}. We never TAP Delete/Information — we only tap + the safe "Menu" trigger and assert the menu SHAPE. +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ── Local shape helpers (READ-ONLY kit stays untouched) ───────────────────────── +def _desc_set(nodes): + """Set of non-empty content-descs — the discriminating icon/control keys.""" + return {n.get("content-desc", "").strip() + for n in nodes if n.get("content-desc", "").strip()} + + +def _n_editable(nodes): + return len(find_by_class(nodes, "EditText")) + + +def _n_checkbox(nodes): + return len(find_by_class(nodes, "CheckBox")) + + +# ── Settings self-isolation (this lane runs SEQUENTIALLY after the states lane in +# the full suite; a sibling lane toggles 'Show rename dialog…' and may leave it +# OFF. When OFF, Stop saves silently with NO post-record dialog, so the +# post-record-dialog tests must GUARANTEE the setting themselves rather than +# trusting the default. Compose exposes NOTHING through the `checked` attribute +# for these Settings switches — state is read from the RENDERED switch PIXEL. +# Copied (NOT imported — the kit is read-only and cross-test imports are banned) +# from the proven states-lane technique. All coordinates are DERIVED from +# get_screen_info(), never written as literals. ───────────────────────────────── +def _switch_is_on(row_label, save_path): + """Compose switch ON => blue thumb shifted right; read a pixel on the track. + ON when (b - r) > 40 at x≈0.885*width, y = row center. Returns True/False/None.""" + n = find_node(ui(), text=row_label) + if not n or "_center" not in n: + return None + if not screencap(save_path): + return None + try: + from PIL import Image + except Exception: + return None + try: + im = Image.open(save_path).convert("RGB") + except Exception: + return None + s = get_screen_info() + r, g, b = im.getpixel((int(s["width"] * 0.885), n["_center"][1])) + return (b - r) > 40 + + +def _tap_switch(row_label): + """Flip the toggle by tapping the far-right switch (x = 0.93*width — the label + is NOT the clickable target). x derived from screen width, never a literal.""" + n = find_node(ui(), text=row_label) + if not n or "_center" not in n: + return False + s = get_screen_info() + tap(int(s["width"] * 0.93), n["_center"][1]) + settle("tap") + return True + + +def and_ensure_rename_dialog_on(): + """Guarantee 'Show rename dialog after recording is completed' is ON, then return + to Home, so Stop reliably raises the post-record dialog. Self-isolation: the FULL + suite runs lanes sequentially and a sibling lane may leave this OFF.""" + s = find_node(ui(), content_desc="Settings") + if not (s and tap_node(s)): + return False + settle("tap") + label = "Show rename dialog after recording is completed" + scroll_into_view(label) + path = os.path.join(RESULTS_DIR, "screenshots", "_struct_ensure.png") + cur = _switch_is_on(label, path) + if cur is False: # only tap if we can READ it as OFF + _tap_switch(label) + # return to Home + b = find_node(ui(), content_desc="Navigate back") + if b: + tap_node(b) + settle("tap") + return True + + +# ── depth-family helpers (NAMED and_enter_*/and_reach_* so a declared depth>=1 is +# backed by a real navigation call, per the audit contract) ──────────────────── +def and_enter_records(nodes): + """Tap the bottom-right 'Records' control and confirm the surface changed. + Counts one crossed surface. Returns (ok, records_nodes).""" + btn = find_node(nodes, content_desc="Records") + if not btn: + return False, nodes + before = and_showing(nodes) + if not tap_node(btn): + return False, nodes + after_nodes = ui() + if not surface_changed(before, and_showing(after_nodes)): + return False, after_nodes + and_enter("Records") + return True, after_nodes + + +def and_enter_settings(nodes): + """Tap the bottom-left 'Settings' control and confirm the surface changed. + Counts one crossed surface. Returns (ok, settings_nodes).""" + btn = find_node(nodes, content_desc="Settings") + if not btn: + return False, nodes + before = and_showing(nodes) + if not tap_node(btn): + return False, nodes + after_nodes = ui() + if not surface_changed(before, and_showing(after_nodes)): + return False, after_nodes + and_enter("Settings") + return True, after_nodes + + +def and_reach_row_menu(records_nodes): + """From the Records surface, tap a per-row 3-dot 'Menu' (a right-edge 'Menu' + icon sitting BELOW the toolbar band) and PROVE the context-menu layer opened: + a menu item ('Share') appeared that Records did not show. Counts one more + crossed surface (Home -> Records -> row context menu = depth 2). and_reach_surface + already increments the depth counter. Returns (ok, menu_nodes).""" + row_menus = sorted( + (m for m in find_nodes(records_nodes, content_desc="Menu") + if m.get("_center") and m["_center"][1] > 260), + key=lambda m: m["_center"][1]) + if not row_menus: + return False, records_nodes + if not and_reach_surface(row_menus[0], target="Share"): + return False, ui() + return True, ui() + + +# ════════════════════════════════════════════════════════════════════════════════ +# GATE (jump_kind="none", depth=0) — existence baseline. 4 of the tests. +# ════════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("structure_gate_launch",)) +def test_gate_launch(): + """App launches, reaches foreground, and Home's main Compose container exists.""" + restart_app() + nodes = ui() + fg = wait_for_foreground() + # Compose host: a ComposeView (the single-Activity content root) plus at least + # one framing layout. NOT ViewGroup — this app has none. + host = bool(find_by_class(nodes, "ComposeView") + or find_by_class(nodes, "FrameLayout")) + ok = bool(fg and host and nodes) + record("structure_gate_launch", ok, + "" if ok else "setup_failed: app did not reach the foreground with a " + "Compose content host", + depth=0, jump_kind="none") + + +@and_test(expects=("structure_gate_top_bar",)) +def test_gate_top_bar(): + """Home top bar host exists: the 'Audio Recorder' title with the Import (left) + and Menu (right, overflow) controls flanking it.""" + restart_app() + wait_for_foreground() + nodes = ui() + title = find_node(nodes, text="Audio Recorder") or find_node_ci(nodes, "Audio Recorder") + imp = find_node(nodes, content_desc="Import") + menu = find_node(nodes, content_desc="Menu") + ok = bool(title and imp and menu) + record("structure_gate_top_bar", ok, + "" if ok else "feature_missing: Home top bar (title + Import + Menu) " + "not all present", + depth=0, jump_kind="none") + + +@and_test(expects=("structure_gate_bottom_bar", "structure_gate_bottom_bar_vlm")) +def test_gate_bottom_bar(): + """Home bottom bar is the nav host: three controls Settings/Record/Records + laid out left/center/right, with the big central Record button.""" + restart_app() + wait_for_foreground() + nodes = ui() + settings = find_node(nodes, content_desc="Settings") + records = find_node(nodes, content_desc="Records") + rec = find_node(nodes, content_desc="Record") or find_node(nodes, text="Record") + ok = bool(settings and records and rec) + # Positional sanity from the dump (not a literal): Settings left of Record, + # Record left of Records. + if ok: + sx = settings["_center"][0] + cx = rec["_center"][0] + rx = records["_center"][0] + ok = sx < cx < rx + record("structure_gate_bottom_bar", ok, + "" if ok else "feature_missing: bottom bar Settings dialog may appear (if the setting is ON) -> Cancel it, so no + # record is created and the 'Stop' control disappears again. When the setting is + # OFF Stop saves silently (no dialog); either way 'Stop' must vanish. + restored = False + stop = find_node(during, content_desc="Stop") + if stop and tap_node(stop): + settle("tap") + cancel = find_node(ui(), text="Cancel") + if cancel: + tap_node(cancel) + settle("tap") + restored = "Stop" not in _desc_set(ui()) + ok = ok and restored + record("structure_record_starts_shape", ok, + "" if ok else "behavior_wrong: 'Stop' control did not appear on Record " + "and/or did not disappear on Stop", + depth=0, jump_kind="transition", + expect="content-desc 'Stop' absent on Home -> present while recording " + "-> absent again after Stop+Cancel") + # VLM must fire on the recording surface — re-enter it for the screenshot. + home2 = ui() + rec2 = find_node(home2, content_desc="Record") or find_node(home2, text="Record") + if rec2: + tap_node(rec2) + settle("tap") + vlm_assert("structure_record_starts_shape", + "Is a live recording waveform being drawn in the upper half of the " + "screen, showing a horizontal time axis with numeric time labels " + "(like 00:02, 00:04, 00:06) and a bright vertical playhead line?", + RESULTS_DIR, tag="shape") + # cleanup: stop + cancel so no stray dialog/record persists + st = find_node(ui(), content_desc="Stop") + if st and tap_node(st): + settle("tap") + c = find_node(ui(), text="Cancel") + if c: + tap_node(c) + settle("tap") + + +@and_test(expects=("structure_recording_labels_shape",)) +def test_recording_labels_shape(): + """Recording adds a class of status widgets absent on idle Home: the + 'Recording…' status TextView and the 'Pause' label. Assert PRESENCE of both + keys (leave the exact string equality to the text lane).""" + restart_app() + wait_for_foreground() + home = ui() + home_keys = and_showing(home) + had_recording = any("recording" in k.lower() for k in home_keys) + had_pause = any(k.lower().endswith("|pause") for k in home_keys) + rec = find_node(home, content_desc="Record") or find_node(home, text="Record") + tapped = tap_node(rec) if rec else False + settle("tap") + during = ui() + keys = and_showing(during) + now_recording = any("recording" in k.lower() for k in keys) + now_pause = any(k.lower().endswith("|pause") for k in keys) + ok = bool(tapped and not had_recording and not had_pause + and now_recording and now_pause) + record("structure_recording_labels_shape", ok, + "" if ok else "behavior_wrong: 'Recording…' and 'Pause' status nodes did " + "not both appear when recording started", + depth=0, jump_kind="transition", + expect="Home has no 'Recording…'/'Pause' keys; recording adds both") + # cleanup + st = find_node(during, content_desc="Stop") + if st and tap_node(st): + settle("tap") + c = find_node(ui(), text="Cancel") + if c: + tap_node(c) + settle("tap") + + +@and_test(expects=("structure_stop_opens_dialog", "structure_stop_opens_dialog_vlm")) +def test_stop_opens_dialog(): + """Stopping a recording adds a DIALOG window layer: the post-record card + contributes 2 EditText + 2 CheckBox that Home has 0 of. Reverse via Cancel and + assert the editable subtree collapses back to 0. + + SELF-ISOLATION: this dialog only appears when the Settings toggle 'Show rename + dialog after recording is completed' is ON. The FULL suite runs lanes + sequentially and a sibling lane may leave it OFF, so we GUARANTEE it ON via the + GUI first (and_ensure_rename_dialog_on) before recording — never trusting the + default. Cleanup dismisses only via Cancel (never Delete).""" + restart_app() + wait_for_foreground() + and_ensure_rename_dialog_on() # guarantee the post-record dialog is enabled + wait_for_foreground() + home = ui() + edits0, checks0 = _n_editable(home), _n_checkbox(home) + rec = find_node(home, content_desc="Record") or find_node(home, text="Record") + tap_node(rec) + settle("tap") + stop = find_node(ui(), content_desc="Stop") + opened = tap_node(stop) if stop else False + settle("tap") + dlg = ui() + edits1, checks1 = _n_editable(dlg), _n_checkbox(dlg) + dlg_key = any("update name and description" in k.lower() for k in and_showing(dlg)) + grew = bool(opened and edits0 == 0 and checks0 == 0 + and edits1 == 2 and checks1 == 2 and dlg_key) + + # Reverse + cancel = find_node(dlg, text="Cancel") + restored = False + if cancel and tap_node(cancel): + settle("tap") + restored = _n_editable(ui()) == 0 + ok = grew and restored + record("structure_stop_opens_dialog", ok, + "" if ok else "behavior_wrong: post-record dialog subtree (2 EditText + " + "2 CheckBox) did not appear on Stop / collapse on Cancel", + depth=0, jump_kind="transition", + expect="EditText 0->2 & CheckBox 0->2 with 'Update name and description' " + "layer on Stop; back to 0 on Cancel") + # VLM must fire on the dialog surface — re-open it for the screenshot. + home2 = ui() + rec2 = find_node(home2, content_desc="Record") or find_node(home2, text="Record") + if rec2: + tap_node(rec2) + settle("tap") + st2 = find_node(ui(), content_desc="Stop") + if st2: + tap_node(st2) + settle("tap") + vlm_assert("structure_stop_opens_dialog", + "Is a rounded rectangular dialog card overlaid on top of the screen, " + "horizontally centered, containing a title and two text input boxes " + "stacked vertically, with the dimmed app screen visible behind it?", + RESULTS_DIR, tag="position") + # cleanup: dismiss dialog + c = find_node(ui(), text="Cancel") + if c: + tap_node(c) + settle("tap") + + +@and_test(expects=("structure_rename_dialog_shape", "structure_rename_dialog_shape_vlm")) +def test_rename_dialog_shape(): + """The Home pencil ('Rename' content-desc) opens the 'Update name' dialog, + adding exactly one EditText where Home had none. Reverse via Cancel. This dialog + is UNCONDITIONAL — no Settings toggle gates it — so no ensure-guard is needed.""" + restart_app() + wait_for_foreground() + home = ui() + edits0 = _n_editable(home) + pencil = find_node(home, content_desc="Rename") + opened = tap_node(pencil) if pencil else False + settle("tap") + dlg = ui() + edits1 = _n_editable(dlg) + dlg_key = any("update name" in k.lower() for k in and_showing(dlg)) + grew = bool(opened and edits0 == 0 and edits1 == 1 and dlg_key) + + cancel = find_node(dlg, text="Cancel") + restored = False + if cancel and tap_node(cancel): + settle("tap") + restored = _n_editable(ui()) == 0 + ok = grew and restored + record("structure_rename_dialog_shape", ok, + "" if ok else "behavior_wrong: 'Update name' dialog (one EditText) did " + "not appear from the Rename pencil / collapse on Cancel", + depth=0, jump_kind="transition", + expect="EditText 0->1 with 'Update name' layer on pencil; back to 0 on Cancel") + # VLM on the dialog — re-open. + home2 = ui() + p2 = find_node(home2, content_desc="Rename") + if p2: + tap_node(p2) + settle("tap") + vlm_assert("structure_rename_dialog_shape", + "Is a single rounded dialog card centered on the screen showing an " + "'Update name' title and exactly one text field prefilled with a " + "record name, above 'Cancel' and 'Save' buttons?", + RESULTS_DIR, tag="position") + c = find_node(ui(), text="Cancel") + if c: + tap_node(c) + settle("tap") + + +@and_test(expects=("structure_records_list_shape", "structure_records_list_shape_vlm")) +def test_records_list_shape(): + """Opening Records (bottom-right) replaces Home's playback shape with a list + surface: a 'Navigate back' + 'Filter' toolbar and a row subtree under a 'Today' + header appear (Home had none). depth=1, backed by and_enter_records.""" + restart_app() + wait_for_foreground() + home = ui() + home_descs = _desc_set(home) + ok_enter, rl = and_enter_records(home) + rl_descs = _desc_set(rl) + rl_keys = and_showing(rl) + # SHAPE deltas: toolbar controls that Home lacks + a date-group header row. + toolbar_grew = ("Navigate back" not in home_descs + and "Filter" not in home_descs + and "Navigate back" in rl_descs and "Filter" in rl_descs) + has_row_area = any(k.lower().endswith("|today") for k in rl_keys) \ + and any("|record-" in k.lower() for k in rl_keys) + changed = surface_changed(and_showing(home), rl_keys) + ok = bool(ok_enter and toolbar_grew and has_row_area and changed) + record("structure_records_list_shape", ok, + "" if ok else "behavior_wrong: Records surface did not add the " + "Navigate-back/Filter toolbar + a 'Today' row subtree", + depth=1, jump_kind="transition", + expect="Home (Play panel) -> Records adds {Navigate back, Filter} + " + "'Today' header + Record row subtree") + vlm_assert("structure_records_list_shape", + "Is this a records list screen where recording entries are laid out " + "as a vertical list of rows beneath a centered 'Today' date header " + "near the top, each row starting with a record name at the left?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("structure_row_context_menu_shape",)) +def test_row_context_menu_shape(): + """Depth-2 shape delta: from the Records surface, a per-row 3-dot opens the + same 7-item context-menu subtree (Share…Delete) that the Records surface did + not show. Backed by and_enter_records + and_reach_row_menu (both depth-family + calls), so depth=2 is real. Reversed with BACK. We tap only the safe 3-dot + trigger and NEVER any destructive item.""" + restart_app() + wait_for_foreground() + home = ui() + ok_rec, rl = and_enter_records(home) + if not ok_rec: + record("structure_row_context_menu_shape", False, + "setup_failed: could not open the Records surface", depth=1, + jump_kind="value", + expect="Records row 3-dot opens a 7-item context menu; removed on BACK") + return + items = ["Share", "Information", "Rename", "Edit description", + "Open with…", "Save as…", "Delete"] + present_before = sum(1 for it in items if find_node(rl, text=it)) + ok_menu, cm = and_reach_row_menu(rl) + present_after = sum(1 for it in items if find_node(cm, text=it)) + grew = bool(ok_menu and present_before == 0 and present_after == 7) + # Reverse with BACK (dismisses the menu, back to the Records surface). + back() + settle("tap") + present_restored = sum(1 for it in items if find_node(ui(), text=it)) + ok = grew and present_restored == 0 + record("structure_row_context_menu_shape", ok, + "" if ok else "behavior_wrong: Records row 3-dot did not open the 7-item " + "context-menu subtree / it did not collapse on BACK", + depth=2, jump_kind="value", + expect="Records shows 0 context items -> 7 after row 3-dot -> 0 after BACK") + + +@and_test(expects=("structure_settings_list_shape", "structure_settings_list_shape_vlm")) +def test_settings_list_shape(): + """Opening Settings (bottom-left) swaps the small Home surface for a long + scrollable settings surface: the discriminating key set balloons and toggle-row + controls (content-desc 'Dark theme' etc.) that Home lacks appear. depth=1, + backed by and_enter_settings.""" + restart_app() + wait_for_foreground() + home = ui() + home_keys = and_showing(home) + ok_enter, st = and_enter_settings(home) + st_keys = and_showing(st) + st_descs = _desc_set(st) + # Settings-specific toggle rows (rendered as View+content-desc, not Switch). + toggle_rows = {"Dark theme", "Dynamic theme colors", + "Keep screen ON while recording"} & st_descs + # The list is materially larger than Home's tiny surface. + much_bigger = len(st_keys) >= len(home_keys) + 8 + ok = bool(ok_enter and len(toggle_rows) >= 2 and much_bigger + and surface_changed(home_keys, st_keys)) + record("structure_settings_list_shape", ok, + "" if ok else "behavior_wrong: Settings surface did not add its toggle-" + "row list / grow the node set materially vs Home", + depth=1, jump_kind="transition", + expect="Home ~13 keys -> Settings adds toggle rows (Dark theme, Dynamic " + "theme colors, Keep screen ON) and >=+8 discriminating keys") + vlm_assert("structure_settings_list_shape", + "Is this a settings screen with multiple option rows stacked " + "vertically, where the top rows each have a toggle switch aligned to " + "the far right of the row?", + RESULTS_DIR, tag="position") + + +@and_test(expects=("structure_settings_scroll_shape",)) +def test_settings_scroll_shape(): + """Scrolling the Settings surface recycles content: the discriminating key set + changes materially (rows scroll off, new chip rows scroll in). depth=1, backed + by and_enter_settings. Reversed by scrolling back up.""" + restart_app() + wait_for_foreground() + home = ui() + ok_enter, st = and_enter_settings(home) + if not ok_enter: + record("structure_settings_scroll_shape", False, + "setup_failed: could not enter Settings", depth=1, + jump_kind="transition", + expect="Settings key set changes on scroll and restores on scroll-back") + return + before = and_showing(st) + scroll_down(0.6) + after = and_showing(ui()) + changed = surface_changed(before, after, min_delta=3) + # Reverse: scroll back to the top and expect the top-anchored keys to return. + scroll_up(0.6) + scroll_up(0.6) + restored_keys = and_showing(ui()) + restored = any("dark theme" in k.lower() for k in restored_keys) + ok = bool(changed and restored) + record("structure_settings_scroll_shape", ok, + "" if ok else "behavior_wrong: Settings key set did not change on scroll " + "or top rows did not return on scroll-back", + depth=1, jump_kind="transition", + expect="Settings key set changes >=3 keys on scroll-down; 'Dark theme' " + "row returns on scroll-up") + + +@and_test(expects=("structure_settings_chips_vlm", "structure_settings_chips")) +def test_settings_chips(): + """The Settings chip groups (Recording format / Sample rate / Bitrate / Channel + count) each contribute a row of pill options. Rule anchor: the group-label + content-descs plus multiple option chips are present in the tree. The pill + RENDERING (horizontal rounded chips) is VLM-only.""" + restart_app() + wait_for_foreground() + home = ui() + ok_enter, st = and_enter_settings(home) + st_descs = _desc_set(st) + # Group labels are content-descs; individual chip options are content-descs too. + group_labels = {"Recording format:", "Sample rate:"} & st_descs + chip_opts = {"M4a", "3gp", "44.1kHz"} & st_descs + ok = bool(ok_enter and len(group_labels) >= 1 and len(chip_opts) >= 2) + record("structure_settings_chips", ok, + "" if ok else "feature_missing: Settings chip-group labels/options " + "(Recording format:/Sample rate: + chips) not present", + depth=1, jump_kind="value", + expect=">=1 chip-group label + >=2 chip options among Settings descs") + vlm_assert("structure_settings_chips", + "Under a 'Recording format:' label, are the format options ('M4a', " + "'Wav', '3gp') rendered as separate rounded pill-shaped chips laid " + "out in a single horizontal row?", + RESULTS_DIR, tag="shape") + + +@and_test(expects=("structure_overflow_menu_shape",)) +def test_overflow_menu_shape(): + """The top-right overflow 'Menu' opens a menu subtree of the 7 context items + (Share/Information/Rename/Edit description/Open with…/Save as…/Delete). Assert + the COUNT delta (value). We tap only the safe 'Menu' trigger and reverse with + BACK — we NEVER tap Delete/Information/etc.""" + restart_app() + wait_for_foreground() + home = ui() + items = ["Share", "Information", "Rename", "Edit description", + "Open with…", "Save as…", "Delete"] + present_before = sum(1 for it in items if find_node(home, text=it)) + menu = find_node(home, content_desc="Menu") + opened = safe_tap(menu) if menu else False + settle("tap") + mn = ui() + present_after = sum(1 for it in items if find_node(mn, text=it)) + grew = bool(opened and present_before <= 1 and present_after == 7) + # Reverse with BACK (dismisses the menu without touching any item). + back() + settle("tap") + present_restored = sum(1 for it in items if find_node(ui(), text=it)) + restored = present_restored <= 1 + ok = grew and restored + record("structure_overflow_menu_shape", ok, + "" if ok else "behavior_wrong: overflow Menu did not expand to the 7-item " + "context menu / did not collapse on BACK", + depth=0, jump_kind="value", + expect="menu items in tree <=1 -> 7 on Menu tap -> <=1 after BACK") + + +@and_test(expects=("structure_menu_layer_added",)) +def test_menu_layer_added(): + """Complementary to the count test: opening the overflow menu adds a NEW window + layer whose key set materially differs from Home (a fresh subtree, not just a + highlighted state). Uses surface_changed on the key sets. Reversed with BACK.""" + restart_app() + wait_for_foreground() + home = ui() + home_keys = and_showing(home) + menu = find_node(home, content_desc="Menu") + opened = safe_tap(menu) if menu else False + settle("tap") + open_keys = and_showing(ui()) + added = surface_changed(home_keys, open_keys, min_delta=4) + # the menu items are genuinely NEW keys, not present before + new_items = {k for k in (open_keys - home_keys) + if any(w in k.lower() for w in ("share", "rename", "information", + "edit description", "open with", + "save as", "delete"))} + grew = bool(opened and added and len(new_items) >= 4) + back() + settle("tap") + restored = surface_changed(open_keys, and_showing(ui()), min_delta=4) + ok = grew and restored + record("structure_menu_layer_added", ok, + "" if ok else "behavior_wrong: overflow menu did not add a new key layer " + "(>=4 new item keys) / collapse on BACK", + depth=0, jump_kind="transition", + expect="overflow adds >=4 new menu-item keys vs Home; removed on BACK") + + +# ════════════════════════════════════════════════════════════════════════════════ +if __name__ == "__main__": + TESTS = [ + # GATE (existence, jump_kind="none") + test_gate_launch, + test_gate_top_bar, + test_gate_bottom_bar, + test_gate_center_panel, + # SHAPE deltas + test_record_starts_shape, + test_recording_labels_shape, + test_stop_opens_dialog, + test_rename_dialog_shape, + test_records_list_shape, + test_row_context_menu_shape, + test_settings_list_shape, + test_settings_scroll_shape, + test_settings_chips, + test_overflow_menu_shape, + test_menu_layer_added, + ] + run_suite(TESTS, "structure") diff --git a/android/dimowner-audiorecorder/tests/test_android_text.py b/android/dimowner-audiorecorder/tests/test_android_text.py new file mode 100644 index 0000000000000000000000000000000000000000..d6a2de687540bd410c38a24b670a09d7ada00834 --- /dev/null +++ b/android/dimowner-audiorecorder/tests/test_android_text.py @@ -0,0 +1,698 @@ +#!/usr/bin/env python3 +"""TEXT lane — CONTENT / OUTPUT text for com.dimowner.audiorecorder.debug. + +Owns exact-string equality: content strings a navigation/action PRODUCES +(surface titles, dialog titles, section headers, menu-item labels, an +empty-state message, a dynamic sort subtitle, a "Recording…" status, an +info label:value pair). Every asserted string was OBSERVED live on the +original app — never derived from the source tree, never a version number. + +Two VLM records cover the ONE opaque core: the mm:ss time-axis labels the +live recording waveform draws on canvas (they never reach the view tree). + +Invoke: + python3 test_android_text.py +""" +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from android_testgen_kit import * # noqa: F403,E402 + + +# ── helpers (local; the kit is read-only) ─────────────────────────────────────── +def all_text(nodes): + """Every visible text string, joined — for substring presence checks.""" + return " | ".join(n.get("text", "") for n in nodes if n.get("text")) + + +def all_labels(nodes): + """text AND content-desc, lowercased — for case-insensitive presence checks.""" + out = [] + for n in nodes: + t = n.get("text", "").strip() + cd = n.get("content-desc", "").strip() + if t: + out.append(t.lower()) + if cd: + out.append(cd.lower()) + return out + + +def has_label(nodes, s): + """True if `s` appears (case-insensitively) as a full text/content-desc.""" + return find_node_ci(nodes, s) is not None + + +def open_home(): + """Fresh Home surface; own entry point for every test.""" + restart_app() + wait_for_foreground() + return ui() + + +def and_reach_child(node, title_text=""): + """Tap `node`, PROVE a real child-surface jump, and back one depth level. + + Home has no 'Navigate back' control; every child surface (Records, Settings, + Information, Trash) does. A generic and_reach() source/target check is unusable + here because record names like 'Record-85' collide with the substrings + 'Record'/'Records', so this uses the back-affordance as the discriminator: the + jump is real iff a 'Navigate back' control NEWLY appears (and, when given, the + target title TextView is present). Naming this `and_reach_*` keeps the declared + depth backed by a depth-family call (see and_audit_depth). + + Returns (ok, after_nodes). + """ + before = and_showing() + if not tap_node(node): + return False, ui() + after_nodes = ui() + after = and_showing(after_nodes) + back_new = (any("navigate back" in k.lower() for k in after) + and not any("navigate back" in k.lower() for k in before)) + title_ok = True if not title_text else find_node(after_nodes, text=title_text) is not None + if back_new and title_ok: + and_enter(title_text or "child") + return True, after_nodes + return False, after_nodes + + +def and_reach_grandchild(node, title_text="", gone_text=""): + """A second hop from an already-child surface (e.g. Settings → Trash). + + Both surfaces carry a 'Navigate back', and the target title can even exist as a + ROW label on the parent (Settings has a 'Trash' row AND the Trash screen has a + 'Trash' title), so neither is a reliable discriminator on its own. The honest + verdict here: a PARENT-ONLY marker (`gone_text`, e.g. a Settings toggle label) + DISAPPEARS while the target title is present afterwards. Backs one more depth + level. Returns (ok, after_nodes).""" + before_nodes = ui() + parent_had_marker = (find_node(before_nodes, text=gone_text) is not None + if gone_text else True) + if not tap_node(node): + return False, ui() + after_nodes = ui() + title_present = (find_node(after_nodes, text=title_text) is not None + if title_text else True) + marker_gone = (find_node(after_nodes, text=gone_text) is None + if gone_text else True) + ok = parent_had_marker and title_present and marker_gone + if ok: + and_enter(title_text or "grandchild") + return ok, after_nodes + + +def open_overflow_menu(nodes): + """Tap the top-right Home overflow ('Menu') and return the menu's dump. + Returns (nodes, ok).""" + menu = find_node(nodes, content_desc="Menu") + if not menu: + return nodes, False + tap_node(menu) + fresh = ui() + # The menu is open once its item labels are present. + return fresh, has_label(fresh, "Share") or has_label(fresh, "Information") + + +def dismiss_menu_or_dialog(): + """Best-effort return to a stable surface WITHOUT tapping Delete.""" + nodes = ui() + c = find_node_ci(nodes, "Cancel") + if c and is_safe(c): + tap_node(c) + return + back() + + +# ══════════════════════════════════════════════════════════════════════════════ +# Surface titles produced by navigating there +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_records_title",)) +def test_records_title(): + nodes = open_home() + trigger = find_node(nodes, content_desc="Records") + if not trigger: + record("text_records_title", False, + "setup_failed: no 'Records' control on Home", + depth=1, jump_kind="reach", expect="toolbar title 'Records'") + return + reached, nodes = and_reach_child(trigger, "Records") + # The Records SURFACE shows a toolbar title exactly "Records". + title = find_node(nodes, text="Records") + ok = reached and title is not None + record("text_records_title", ok, + "" if ok else "behavior_wrong: Records surface has no toolbar title " + "reading 'Records'", + depth=1, jump_kind="reach", expect="toolbar title reads 'Records'") + + +@and_test(expects=("text_settings_title",)) +def test_settings_title(): + nodes = open_home() + trigger = find_node(nodes, content_desc="Settings") + if not trigger: + record("text_settings_title", False, + "setup_failed: no 'Settings' control on Home", + depth=1, jump_kind="reach", expect="toolbar title 'Settings'") + return + reached, nodes = and_reach_child(trigger, "Settings") + title = find_node(nodes, text="Settings") + ok = reached and title is not None + record("text_settings_title", ok, + "" if ok else "behavior_wrong: Settings surface has no title 'Settings'", + depth=1, jump_kind="reach", expect="toolbar title reads 'Settings'") + + +@and_test(expects=("text_information_title",)) +def test_information_title(): + nodes = open_home() + menu = find_node(nodes, content_desc="Menu") + if not menu: + record("text_information_title", False, + "setup_failed: no overflow 'Menu' on Home", + depth=1, jump_kind="reach", expect="title 'Information'") + return + tap_node(menu) + nodes = ui() + info = find_node(nodes, content_desc="Information") or find_node(nodes, text="Information") + if not info: + record("text_information_title", False, + "feature_missing: no 'Information' item in the overflow menu", + depth=1, jump_kind="reach", expect="title 'Information'") + return + reached, nodes = and_reach_child(info, "Information") + # Title AND a body label prove it is the Info screen, not just the menu item. + body_present = has_label(nodes, "File location:") + ok = reached and body_present + record("text_information_title", ok, + "" if ok else "behavior_wrong: Information screen title/body not shown " + "after choosing Information", + depth=1, jump_kind="reach", expect="screen title reads 'Information'") + + +@and_test(expects=("text_trash_title",)) +def test_trash_title(): + nodes = open_home() + st = find_node(nodes, content_desc="Settings") + ok_settings, nodes = (and_reach_child(st, "Settings") if st else (False, nodes)) + if not ok_settings: + record("text_trash_title", False, + "setup_failed: could not reach Settings on the way to Trash", + depth=2, jump_kind="reach", expect="title 'Trash'") + return + trash = find_node(nodes, content_desc="Trash") or find_node(nodes, text="Trash") + if not trash: + record("text_trash_title", False, + "feature_missing: no 'Trash' row in Settings", + depth=2, jump_kind="reach", expect="title 'Trash'") + return + # 'Dark theme' is a Settings-only toggle label; it vanishes on the Trash screen. + reached, nodes = and_reach_grandchild(trash, "Trash", gone_text="Dark theme") + title = find_node(nodes, text="Trash") + ok = reached and title is not None + record("text_trash_title", ok, + "" if ok else "behavior_wrong: Deleted-records screen has no 'Trash' title", + depth=2, jump_kind="reach", expect="screen title reads 'Trash'") + + +@and_test(expects=("text_trash_empty_message",)) +def test_trash_empty_message(): + expected = "Recordings in the trash are permanently deleted after 60 days." + nodes = open_home() + st = find_node(nodes, content_desc="Settings") + ok_settings, nodes = (and_reach_child(st, "Settings") if st else (False, nodes)) + if not ok_settings: + record("text_trash_empty_message", False, + "setup_failed: could not reach Settings on the way to Trash", + depth=2, jump_kind="value", expect=f"message '{expected}'") + return + trash = find_node(nodes, content_desc="Trash") or find_node(nodes, text="Trash") + if not trash: + record("text_trash_empty_message", False, + "feature_missing: no 'Trash' row in Settings", + depth=2, jump_kind="value", expect=f"message '{expected}'") + return + _reached, nodes = and_reach_grandchild(trash, "Trash", gone_text="Dark theme") + blob = all_text(nodes) + # Match the distinctive core of the sentence; tolerant of trailing punctuation. + core = "permanently deleted after 60 days" + ok = core.casefold() in blob.casefold() + record("text_trash_empty_message", ok, + "" if ok else "behavior_wrong: Trash screen missing the 60-day " + f"empty-state message (saw: {blob[:80]!r})", + depth=2, jump_kind="value", + expect=f"empty-state message contains '{core}'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Dialog title produced by an action +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_rename_dialog_title",)) +def test_rename_dialog_title(): + nodes = open_home() + absent = not has_label(nodes, "Update name") + pencil = find_node(nodes, content_desc="Rename") + if not pencil: + record("text_rename_dialog_title", False, + "setup_failed: no 'Rename' pencil on Home (no loaded record?)", + depth=1, jump_kind="value", expect="dialog title 'Update name'") + return + tap_node(pencil) + and_enter("rename dialog") + nodes = ui() + present = has_label(nodes, "Update name") + ok = absent and present + # Leave without renaming (Cancel), NEVER Delete. + c = find_node_ci(nodes, "Cancel") + if c: + tap_node(c) + record("text_rename_dialog_title", ok, + "" if ok else "behavior_wrong: rename pencil did not raise a dialog " + "titled 'Update name'", + depth=1, jump_kind="value", expect="dialog title reads 'Update name'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Status / dynamic labels produced by an action +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_recording_status",)) +def test_recording_status(): + nodes = open_home() + absent = "recording" not in all_text(nodes).lower() + rec_btn = find_node(nodes, text="Record") or find_node(nodes, content_desc="Record") + if not rec_btn: + record("text_recording_status", False, + "setup_failed: no 'Record' button on Home", + depth=0, jump_kind="transition", + expect="status text 'Recording…' appears") + return + tap_node(rec_btn) + time.sleep(1.5) # let the recording status settle in + nodes = ui() + # The status uses a real ellipsis ("Recording…"); match on the stable stem so + # a recreation using "..." still passes, but require the specific word. + status = next((n.get("text", "") for n in nodes + if n.get("text", "").strip().lower().startswith("recording")), "") + present = status != "" + ok = absent and present + # Clean up: Stop, then dismiss any post-record dialog via Cancel (never Delete). + stop = find_node(ui(), content_desc="Stop") + if stop: + tap_node(stop) + time.sleep(1) + dismiss_menu_or_dialog() + record("text_recording_status", ok, + "" if ok else "behavior_wrong: no 'Recording…' status appeared after " + f"tapping Record (saw: {status!r})", + depth=0, jump_kind="transition", + expect="a status TextView reads 'Recording…' while recording") + + +@and_test(expects=("text_sort_subtitle_default",)) +def test_sort_subtitle_default(): + nodes = open_home() + rec = find_node(nodes, content_desc="Records") + ok_rec, nodes = (and_reach_child(rec, "Records") if rec else (False, nodes)) + if not ok_rec: + record("text_sort_subtitle_default", False, + "setup_failed: could not reach the Records list", + depth=1, jump_kind="value", expect="subtitle 'By date (newest)'") + return + ok = has_label(nodes, "By date (newest)") + record("text_sort_subtitle_default", ok, + "" if ok else "behavior_wrong: Records toolbar subtitle is not " + "'By date (newest)' on entry", + depth=1, jump_kind="value", + expect="default sort subtitle reads 'By date (newest)'") + + +@and_test(expects=("text_sort_subtitle_byname",)) +def test_sort_subtitle_byname(): + nodes = open_home() + rec = find_node(nodes, content_desc="Records") + ok_rec, nodes = (and_reach_child(rec, "Records") if rec else (False, nodes)) + if not ok_rec: + record("text_sort_subtitle_byname", False, + "setup_failed: could not reach the Records list", + depth=1, jump_kind="value", expect="subtitle 'By name (A-Z)'") + return + before = has_label(nodes, "By name (A-Z)") # should be absent (default is by date) + # The 2nd toolbar icon (sort) is a 'Menu' desc high up and left of the bookmark one. + sort_icon = None + for n in nodes: + if (n.get("content-desc") == "Menu" and n.get("_center") + and n["_center"][1] < 320 and n["_center"][0] < 950): + sort_icon = n + break + if not sort_icon: + record("text_sort_subtitle_byname", False, + "setup_failed: sort menu icon not found in Records toolbar", + depth=1, jump_kind="value", expect="subtitle 'By name (A-Z)'") + return + tap_node(sort_icon) + menu = ui() + opt = find_node(menu, content_desc="By name (A-Z)") or find_node(menu, text="By name (A-Z)") + if not opt: + record("text_sort_subtitle_byname", False, + "feature_missing: no 'By name (A-Z)' option in the sort menu", + depth=1, jump_kind="value", expect="subtitle 'By name (A-Z)'") + return + tap_node(opt) + nodes = ui() + after = has_label(nodes, "By name (A-Z)") + ok = (not before) and after + # Restore default sort so no test leaks a changed sort mode. + sort_icon = next((n for n in ui() + if n.get("content-desc") == "Menu" and n.get("_center") + and n["_center"][1] < 320 and n["_center"][0] < 950), None) + if sort_icon: + tap_node(sort_icon) + back_opt = find_node(ui(), content_desc="By date (newest)") \ + or find_node(ui(), text="By date (newest)") + if back_opt: + tap_node(back_opt) + record("text_sort_subtitle_byname", ok, + "" if ok else "behavior_wrong: toolbar subtitle did not change to " + "'By name (A-Z)' after selecting that sort option", + depth=1, jump_kind="value", + expect="sort subtitle updates to 'By name (A-Z)'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Record-Info label:value strings (all dump-readable TEXT — this lane's) +# ══════════════════════════════════════════════════════════════════════════════ + +def _reach_info_from_home(): + """Home overflow → Information. Returns the Info-screen dump, or None.""" + nodes = ui() + menu = find_node(nodes, content_desc="Menu") + if not menu: + return None + tap_node(menu) + nodes = ui() + info = find_node(nodes, content_desc="Information") or find_node(nodes, text="Information") + if not info: + return None + ok, nodes = and_reach_child(info, "Information") + return nodes if ok else None + + +@and_test(expects=("text_info_labels",)) +def test_info_labels(): + open_home() + nodes = _reach_info_from_home() + if nodes is None: + record("text_info_labels", False, + "setup_failed: could not reach the Information screen", + depth=1, jump_kind="value", expect="Info label set present") + return + # The stable label column of the Info screen. + labels = ["Name:", "Format:", "Bitrate:", "Channel count:", + "Sample rate:", "Duration:", "Size:", "File location:"] + present = [lb for lb in labels if find_node(nodes, text=lb)] + missing = [lb for lb in labels if lb not in present] + ok = not missing + record("text_info_labels", ok, + "" if ok else f"behavior_wrong: Info screen missing label(s): {missing}", + depth=1, jump_kind="value", + expect="Info shows labels Name:/Format:/Bitrate:/Channel count:/" + "Sample rate:/Duration:/Size:/File location:") + + +@and_test(expects=("text_info_format_value",)) +def test_info_format_value(): + open_home() + nodes = _reach_info_from_home() + if nodes is None: + record("text_info_format_value", False, + "setup_failed: could not reach the Information screen", + depth=1, jump_kind="value", expect="Format value 'm4a'") + return + fmt_label = find_node(nodes, text="Format:") + val = find_node(nodes, text="m4a") + ok = fmt_label is not None and val is not None + record("text_info_format_value", ok, + "" if ok else "behavior_wrong: Info screen does not report Format value " + "'m4a'", + depth=1, jump_kind="value", expect="Format value reads 'm4a'") + + +@and_test(expects=("text_info_channel_mono",)) +def test_info_channel_mono(): + open_home() + nodes = _reach_info_from_home() + if nodes is None: + record("text_info_channel_mono", False, + "setup_failed: could not reach the Information screen", + depth=1, jump_kind="value", expect="Channel count value 'Mono'") + return + ch_label = find_node(nodes, text="Channel count:") + val = find_node(nodes, text="Mono") + ok = ch_label is not None and val is not None + record("text_info_channel_mono", ok, + "" if ok else "behavior_wrong: Info screen does not report Channel count " + "'Mono'", + depth=1, jump_kind="value", expect="Channel count value reads 'Mono'") + + +@and_test(expects=("text_info_file_ext",)) +def test_info_file_ext(): + open_home() + nodes = _reach_info_from_home() + if nodes is None: + record("text_info_file_ext", False, + "setup_failed: could not reach the Information screen", + depth=1, jump_kind="value", expect="file location ends '.m4a'") + return + if find_node(nodes, text="File location:") is None: + record("text_info_file_ext", False, + "behavior_wrong: no 'File location:' label on the Info screen", + depth=1, jump_kind="value", expect="file location ends '.m4a'") + return + # The path itself contains the package name (not portable), so assert only that + # SOME text on the screen is a file path ending in the recorded extension. + ends_m4a = any(n.get("text", "").strip().lower().endswith(".m4a") for n in nodes) + record("text_info_file_ext", ends_m4a, + "" if ends_m4a else "behavior_wrong: no file path ending in '.m4a' on the " + "Info screen", + depth=1, jump_kind="value", + expect="the file-location value ends with '.m4a'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Context / overflow menu item labels +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_menu_labels_core",)) +def test_menu_labels_core(): + nodes = open_home() + absent = not has_label(nodes, "Edit description") + nodes, opened = open_overflow_menu(nodes) + if not opened: + record("text_menu_labels_core", False, + "setup_failed: could not open the Home overflow menu", + depth=1, jump_kind="value", expect="menu items Share/Information/Rename") + return + and_enter("overflow menu") + wanted = ["Share", "Information", "Rename"] + present = [w for w in wanted if has_label(nodes, w)] + missing = [w for w in wanted if w not in present] + ok = absent and not missing + dismiss_menu_or_dialog() + record("text_menu_labels_core", ok, + "" if ok else f"behavior_wrong: overflow menu missing item(s): {missing}", + depth=1, jump_kind="value", + expect="menu shows Share, Information, Rename") + + +@and_test(expects=("text_menu_labels_ellipsis",)) +def test_menu_labels_ellipsis(): + nodes = open_home() + nodes, opened = open_overflow_menu(nodes) + if not opened: + record("text_menu_labels_ellipsis", False, + "setup_failed: could not open the Home overflow menu", + depth=1, jump_kind="value", + expect="menu items Edit description/Open with/Save as") + return + and_enter("overflow menu") + labels = all_labels(nodes) + # These items use a real ellipsis ("Open with…", "Save as…"); match the stable + # stem so a recreation using "..." also passes, but require the specific words. + has_edit = "edit description" in labels + has_open = any(x.startswith("open with") for x in labels) + has_saveas = any(x.startswith("save as") for x in labels) + ok = has_edit and has_open and has_saveas + missing = [nm for nm, hit in + (("Edit description", has_edit), ("Open with…", has_open), + ("Save as…", has_saveas)) if not hit] + dismiss_menu_or_dialog() + record("text_menu_labels_ellipsis", ok, + "" if ok else f"behavior_wrong: overflow menu missing item(s): {missing}", + depth=1, jump_kind="value", + expect="menu shows 'Edit description', 'Open with…', 'Save as…'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Settings section / chip labels (content produced by reaching Settings) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_settings_section_labels",)) +def test_settings_section_labels(): + nodes = open_home() + # These headers do NOT exist on Home — reaching Settings produces them. + absent = not has_label(nodes, "Recording format:") + st = find_node(nodes, content_desc="Settings") + ok_settings, nodes = (and_reach_child(st, "Settings") if st else (False, nodes)) + if not ok_settings: + record("text_settings_section_labels", False, + "setup_failed: could not reach Settings", + depth=1, jump_kind="value", + expect="section headers Recording format:/Sample rate:/Bitrate:/" + "Channel count:") + return + wanted = ["Recording format:", "Sample rate:", "Bitrate:", "Channel count:"] + present = [w for w in wanted if find_node(nodes, text=w)] + # Bitrate/Channel-count headers may sit below the fold — scroll to confirm. + for w in wanted: + if w not in present: + n = scroll_into_view(w, max_swipes=3) + if n: + present.append(w) + missing = [w for w in wanted if w not in present] + ok = absent and not missing + record("text_settings_section_labels", ok, + "" if ok else f"behavior_wrong: Settings missing section header(s): {missing}", + depth=1, jump_kind="value", + expect="Settings shows section headers Recording format:/Sample rate:/" + "Bitrate:/Channel count:") + + +@and_test(expects=("text_settings_chip_labels",)) +def test_settings_chip_labels(): + nodes = open_home() + absent = not has_label(nodes, "M4a") + st = find_node(nodes, content_desc="Settings") + ok_settings, nodes = (and_reach_child(st, "Settings") if st else (False, nodes)) + if not ok_settings: + record("text_settings_chip_labels", False, + "setup_failed: could not reach Settings", + depth=1, jump_kind="value", + expect="format chips M4a/Wav/3gp") + return + # The recording-format chip group: M4a / Wav / 3gp (observed exactly). + wanted = ["M4a", "Wav", "3gp"] + present = [w for w in wanted if find_node(nodes, text=w)] + missing = [w for w in wanted if w not in present] + ok = absent and not missing + record("text_settings_chip_labels", ok, + "" if ok else f"behavior_wrong: Settings missing format chip(s): {missing}", + depth=1, jump_kind="value", + expect="Settings recording-format chips read M4a, Wav, 3gp") + + +# ══════════════════════════════════════════════════════════════════════════════ +# Char-counter suffix (fixed "/500" label produced by opening the desc dialog) +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_desc_counter_suffix",)) +def test_desc_counter_suffix(): + nodes = open_home() + absent = "/500" not in all_text(nodes) + nodes, opened = open_overflow_menu(nodes) + if not opened: + record("text_desc_counter_suffix", False, + "setup_failed: could not open the Home overflow menu", + depth=1, jump_kind="value", expect="counter contains '/500'") + return + ed = find_node(nodes, content_desc="Edit description") or find_node(nodes, text="Edit description") + if not ed: + record("text_desc_counter_suffix", False, + "feature_missing: no 'Edit description' item in the overflow menu", + depth=1, jump_kind="value", expect="counter contains '/500'") + return + tap_node(ed) + and_enter("edit description dialog") + nodes = ui() + present = "/500" in all_text(nodes) + ok = absent and present + c = find_node_ci(nodes, "Cancel") + if c: + tap_node(c) + record("text_desc_counter_suffix", ok, + "" if ok else "behavior_wrong: description dialog shows no '/500' " + "character-counter suffix", + depth=1, jump_kind="value", + expect="description dialog char counter contains '/500'") + + +# ══════════════════════════════════════════════════════════════════════════════ +# VLM (exactly 2) — the ONE opaque core: canvas-drawn waveform time-axis labels +# ══════════════════════════════════════════════════════════════════════════════ + +@and_test(expects=("text_waveform_axis_labels_vlm", "text_waveform_axis_row_vlm")) +def test_waveform_axis_labels(): + nodes = open_home() + rec_btn = find_node(nodes, text="Record") or find_node(nodes, content_desc="Record") + if not rec_btn: + record("text_waveform_axis_labels_vlm", False, + "setup_failed: no Record button to start the waveform", + depth=0, jump_kind="value", tag="content") + record("text_waveform_axis_row_vlm", False, + "setup_failed: no Record button to start the waveform", + depth=0, jump_kind="value", tag="position") + return + tap_node(rec_btn) + time.sleep(5) # let the canvas accrue several mm:ss time-axis marks + # (1) opaque CONTENT: the mm:ss labels exist at all — they never reach the dump. + vlm_assert( + "text_waveform_axis_labels", + "Along the horizontal waveform strip in the middle of the screen, are there " + "small numeric time labels in mm:ss format such as '00:02', '00:04', '00:06'?", + RESULTS_DIR, jump_kind="value", tag="content") + # (2) POSITION: those labels form a horizontal axis across the CENTRE region, + # not in the top title bar or bottom button bar. + vlm_assert( + "text_waveform_axis_row", + "Are numeric mm:ss time labels (like '00:02', '00:04') arranged in a " + "horizontal row across the CENTER waveform region of the screen, rather " + "than at the very top title area or the bottom button bar?", + RESULTS_DIR, jump_kind="value", tag="position") + # Clean up: Stop, dismiss any post-record dialog via Cancel (never Delete). + stop = find_node(ui(), content_desc="Stop") + if stop: + tap_node(stop) + time.sleep(1) + dismiss_menu_or_dialog() + + +TESTS = [ + test_records_title, + test_settings_title, + test_information_title, + test_trash_title, + test_trash_empty_message, + test_rename_dialog_title, + test_recording_status, + test_sort_subtitle_default, + test_sort_subtitle_byname, + test_info_labels, + test_info_format_value, + test_info_channel_mono, + test_info_file_ext, + test_menu_labels_core, + test_menu_labels_ellipsis, + test_settings_section_labels, + test_settings_chip_labels, + test_desc_counter_suffix, + test_waveform_axis_labels, +] + + +if __name__ == "__main__": + run_suite(TESTS, "text") diff --git a/android/dimowner-audiorecorder/tests/test_manifest.json b/android/dimowner-audiorecorder/tests/test_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..4cfc60e8d7cba702b89d2dec26df12c0de58b6d0 --- /dev/null +++ b/android/dimowner-audiorecorder/tests/test_manifest.json @@ -0,0 +1,737 @@ +{ + "manifest_version": 1, + "kit_api_version": 1, + "task_id": "AudioRecorder", + "baseline_model": "claude-opus-4-8", + "baseline_package": "", + "total": 116, + "manifest_sha": "59dcb338cf74", + "tests": [ + { + "name": "computation::computation_char_counter_two_lengths", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_char_counter_updates", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_name_format_epoch_all_digits", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_name_format_fixed_and_dated", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_playback_position_advances", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_playback_stop_resets", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_record_size_grows", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_record_timer_advances", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_record_timer_starts_at_zero", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_recording_progress_line_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_recording_timeaxis_vlm", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_total_duration_parseable", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "computation::computation_total_records_count_valid", + "module": "computation", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_bookmark_filter", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_bookmark_icon_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_bookmark_persists", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_context_edit_description", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_context_information", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_context_menu_items", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_context_rename", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_create_increments_count", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_create_persists", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_description_persists", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_multi_record_integrity", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_playback_started_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_recording_cursor_vlm", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_rename_cross_surface", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_rename_home", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_rename_persists", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_row_starts_playback", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "interaction::interaction_sequence_record_info_back", + "module": "interaction", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_back_info_home", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_back_records_home", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_back_records_home_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_back_settings_home", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_backstack_records_info_unwind", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_backstack_unwind_2hop", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_chain_records_info", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_chain_records_info_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_chain_settings_trash", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_chain_settings_trash_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_import_external_picker", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_import_external_picker_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_info_reachable_two_paths", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_overflow_opens", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_reach_info_home", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_reach_records", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_reach_records_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_reach_settings", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_reach_settings_vlm", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "navigation::navigation_settings_records_sibling", + "module": "navigation", + "baseline_status": "passed" + }, + { + "name": "states::states_bitrate_chip", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_bitrate_chip_96_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_channel_chip", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_theme", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_theme_off_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dark_theme_on_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dialog_dont_ask_checkbox", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dialog_write_desc_checkbox", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dynamic_theme", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_dynamic_theme_on_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_format_chip", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_format_chip_wav_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_keep_screen_off_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_keep_screen_on", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_keep_screen_persists", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_play_glyph_vlm", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_play_stop", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_record_pause", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_record_resume", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_sample_rate_chip", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_show_rename_dialog", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "states::states_sort_mode", + "module": "states", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_bottom_bar", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_bottom_bar_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_center_panel", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_center_panel_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_launch", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_gate_top_bar", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_menu_layer_added", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_overflow_menu_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_record_starts_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_record_starts_shape_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_recording_labels_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_records_list_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_records_list_shape_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_rename_dialog_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_rename_dialog_shape_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_row_context_menu_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_chips", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_chips_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_list_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_list_shape_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_settings_scroll_shape", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_stop_opens_dialog", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "structure::structure_stop_opens_dialog_vlm", + "module": "structure", + "baseline_status": "passed" + }, + { + "name": "text::text_desc_counter_suffix", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_info_channel_mono", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_info_file_ext", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_info_format_value", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_info_labels", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_information_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_menu_labels_core", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_menu_labels_ellipsis", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_recording_status", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_records_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_rename_dialog_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_chip_labels", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_section_labels", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_settings_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_sort_subtitle_byname", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_sort_subtitle_default", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_trash_empty_message", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_trash_title", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_waveform_axis_labels_vlm", + "module": "text", + "baseline_status": "passed" + }, + { + "name": "text::text_waveform_axis_row_vlm", + "module": "text", + "baseline_status": "passed" + } + ], + "ignored": [], + "vlm_assertions": [ + { + "name": "computation::computation_recording_timeaxis_vlm", + "module": "computation", + "tag": "position" + }, + { + "name": "computation::computation_recording_progress_line_vlm", + "module": "computation", + "tag": "color" + }, + { + "name": "interaction::interaction_bookmark_icon_vlm", + "module": "interaction", + "tag": "shape" + }, + { + "name": "interaction::interaction_recording_cursor_vlm", + "module": "interaction", + "tag": "color" + }, + { + "name": "interaction::interaction_playback_started_vlm", + "module": "interaction", + "tag": "shape" + }, + { + "name": "navigation::navigation_reach_records_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::navigation_reach_settings_vlm", + "module": "navigation", + "tag": "layout" + }, + { + "name": "navigation::navigation_chain_records_info_vlm", + "module": "navigation", + "tag": "content" + }, + { + "name": "navigation::navigation_chain_settings_trash_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::navigation_back_records_home_vlm", + "module": "navigation", + "tag": "position" + }, + { + "name": "navigation::navigation_import_external_picker_vlm", + "module": "navigation", + "tag": "color" + }, + { + "name": "states::states_dark_theme_on_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_dark_theme_off_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_dynamic_theme_on_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_keep_screen_off_vlm", + "module": "states", + "tag": "color" + }, + { + "name": "states::states_format_chip_wav_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_bitrate_chip_96_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "states::states_play_glyph_vlm", + "module": "states", + "tag": "shape" + }, + { + "name": "structure::structure_gate_bottom_bar_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_gate_center_panel_vlm", + "module": "structure", + "tag": "shape" + }, + { + "name": "structure::structure_record_starts_shape_vlm", + "module": "structure", + "tag": "shape" + }, + { + "name": "structure::structure_stop_opens_dialog_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_rename_dialog_shape_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_records_list_shape_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_settings_list_shape_vlm", + "module": "structure", + "tag": "position" + }, + { + "name": "structure::structure_settings_chips_vlm", + "module": "structure", + "tag": "shape" + }, + { + "name": "text::text_waveform_axis_labels_vlm", + "module": "text", + "tag": "content" + }, + { + "name": "text::text_waveform_axis_row_vlm", + "module": "text", + "tag": "position" + } + ], + "vlm_total": 28, + "n_vlm_unverified": 0, + "vlm_log_found": true +} \ No newline at end of file diff --git a/android/dimowner-audiorecorder/vlm_assertions.json b/android/dimowner-audiorecorder/vlm_assertions.json new file mode 100644 index 0000000000000000000000000000000000000000..3ab3c2298eb553af0483713b43acc097d96100b7 --- /dev/null +++ b/android/dimowner-audiorecorder/vlm_assertions.json @@ -0,0 +1,596 @@ +{ + "schema_version": 2, + "instance_id": "android/dimowner-audiorecorder", + "grading": { + "mode": "inline", + "model": null, + "scored_separately": true + }, + "totals": { + "assertions": 29, + "with_verdict": 28, + "calibrated": 0, + "usable": null, + "scored_records": 28, + "unbacked_records": 0 + }, + "assertions": [ + { + "id": "text_waveform_axis_labels_vlm", + "screenshot": "text_waveform_axis_labels_vlm.png", + "assertion": "Along the horizontal waveform strip in the middle of the screen, are there small numeric time labels in mm:ss format such as '00:02', '00:04', '00:06'?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "text_waveform_axis_labels", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "text_waveform_axis_row_vlm", + "screenshot": "text_waveform_axis_row_vlm.png", + "assertion": "Are numeric mm:ss time labels (like '00:02', '00:04') arranged in a horizontal row across the CENTER waveform region of the screen, rather than at the very top title area or the bottom button bar?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "text_waveform_axis_row", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_bookmark_icon_vlm", + "screenshot": "interaction_bookmark_icon_vlm.png", + "assertion": "On the first record row, is the bookmark icon (to the right of the record name, left of the 3-dot menu) drawn as a SOLID/FILLED bookmark shape rather than a hollow outline?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "interaction_bookmark_icon", + "rigor": { + "jump_kind": "value", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_recording_waveform_vlm", + "screenshot": "interaction_recording_waveform_vlm.png", + "assertion": "Is an audio waveform (a horizontal series of vertical amplitude bars/lines) being drawn across the middle of the screen while recording is in progress?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "interaction_recording_waveform", + "rigor": null, + "verdict": null, + "calibration": null + }, + { + "id": "interaction_playback_started_vlm", + "screenshot": "interaction_playback_started_vlm.png", + "assertion": "Is the central round play/pause button now showing a PAUSE icon (two vertical bars) rather than a triangular play arrow, indicating playback is in progress?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "interaction_playback_started", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "interaction_recording_cursor_vlm", + "screenshot": "interaction_recording_cursor_vlm.png", + "assertion": "In the waveform area in the upper-middle of the screen, is there a bright YELLOW vertical line drawn (the recording position cursor), distinct from the darker background and the pale time-axis gridlines?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "interaction_recording_cursor", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_gate_bottom_bar_vlm", + "screenshot": "structure_gate_bottom_bar_vlm.png", + "assertion": "At the very bottom of the screen, is there a control bar with a large light-blue circular 'Record' button in the center, a gear/settings icon at the far left, and a list icon at the far right?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_gate_bottom_bar", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_gate_center_panel_vlm", + "screenshot": "structure_gate_center_panel_vlm.png", + "assertion": "In the middle area of the screen, above the large blue 00:00 timer digits, is an audio waveform visualization drawn (either a small equalizer-style glyph of vertical bars, or a wider waveform with a horizontal time axis)?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "structure_gate_center_panel", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_record_starts_shape_vlm", + "screenshot": "structure_record_starts_shape_vlm.png", + "assertion": "Is a live recording waveform being drawn in the upper half of the screen, showing a horizontal time axis with numeric time labels (like 00:02, 00:04, 00:06) and a bright vertical playhead line?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "structure_record_starts_shape", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_stop_opens_dialog_vlm", + "screenshot": "structure_stop_opens_dialog_vlm.png", + "assertion": "Is a rounded rectangular dialog card overlaid on top of the screen, horizontally centered, containing a title and two text input boxes stacked vertically, with the dimmed app screen visible behind it?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_stop_opens_dialog", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_rename_dialog_shape_vlm", + "screenshot": "structure_rename_dialog_shape_vlm.png", + "assertion": "Is a single rounded dialog card centered on the screen showing an 'Update name' title and exactly one text field prefilled with a record name, above 'Cancel' and 'Save' buttons?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_rename_dialog_shape", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_records_list_shape_vlm", + "screenshot": "structure_records_list_shape_vlm.png", + "assertion": "Is this a records list screen where recording entries are laid out as a vertical list of rows beneath a centered 'Today' date header near the top, each row starting with a record name at the left?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_records_list_shape", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_settings_list_shape_vlm", + "screenshot": "structure_settings_list_shape_vlm.png", + "assertion": "Is this a settings screen with multiple option rows stacked vertically, where the top rows each have a toggle switch aligned to the far right of the row?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "structure_settings_list_shape", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "structure_settings_chips_vlm", + "screenshot": "structure_settings_chips_vlm.png", + "assertion": "Under a 'Recording format:' label, are the format options ('M4a', 'Wav', '3gp') rendered as separate rounded pill-shaped chips laid out in a single horizontal row?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "structure_settings_chips", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "navigation_reach_records_vlm", + "screenshot": "navigation_reach_records_vlm.png", + "assertion": "Does the top of this screen show two small horizontal-line sort/filter icons and a bookmark (ribbon) icon in a row at the top-right?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "navigation_reach_records", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "navigation_reach_settings_vlm", + "screenshot": "navigation_reach_settings_vlm.png", + "assertion": "Is this a settings screen showing a vertical list of labelled rows with pill-shaped ON/OFF toggle switches on the right side of some rows?", + "form": "question", + "expected": true, + "aspect": "layout", + "modality": null, + "links_to": "navigation_reach_settings", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "navigation_chain_records_info_vlm", + "screenshot": "navigation_chain_records_info_vlm.png", + "assertion": "Does this detail screen show label/value pairs such as 'Format:' and 'Bitrate:' stacked vertically beneath a header?", + "form": "question", + "expected": true, + "aspect": "content", + "modality": null, + "links_to": "navigation_chain_records_info", + "rigor": { + "jump_kind": "none", + "depth": 3 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "navigation_chain_settings_trash_vlm", + "screenshot": "navigation_chain_settings_trash_vlm.png", + "assertion": "Does this screen show a large trash-can icon centered in the middle with a short message below it and no list of items?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "navigation_chain_settings_trash", + "rigor": { + "jump_kind": "none", + "depth": 2 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "navigation_back_records_home_vlm", + "screenshot": "navigation_back_records_home_vlm.png", + "assertion": "Does this screen show a large round 'Record' button near the bottom center with a gear (settings) icon at the bottom-left?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "navigation_back_records_home", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "navigation_import_external_picker_vlm", + "screenshot": "navigation_import_external_picker_vlm.png", + "assertion": "Is this a system file browser (light/white background) with a search magnifier icon at the top-right and a hamburger menu at the top-left, clearly different chrome from a dark audio-recorder app?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "navigation_import_external_picker", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_recording_timeaxis_vlm", + "screenshot": "computation_recording_timeaxis_vlm.png", + "assertion": "While recording, is a horizontal time axis with numeric time labels (such as 00:00, 00:02, 00:04) drawn across the MIDDLE of the screen, left to right, above the large 00:0X timer?", + "form": "question", + "expected": true, + "aspect": "position", + "modality": null, + "links_to": "computation_recording_timeaxis", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "computation_recording_progress_line_vlm", + "screenshot": "computation_recording_progress_line_vlm.png", + "assertion": "In the waveform area in the middle of the screen, is there a single bright coloured (yellow/orange) VERTICAL line marking the current recording position, standing out from the fainter grid marks?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "computation_recording_progress_line", + "rigor": { + "jump_kind": "value", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_dark_theme_on_vlm", + "screenshot": "states_dark_theme_on_vlm.png", + "assertion": "Is the whole screen background a very dark, near-black colour (dark theme), with light-coloured text on top of it?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_dark_theme_on", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_dark_theme_off_vlm", + "screenshot": "states_dark_theme_off_vlm.png", + "assertion": "Is the whole screen background now a light, near-white colour (light theme), rather than dark?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_dark_theme_off", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_dynamic_theme_on_vlm", + "screenshot": "states_dynamic_theme_on_vlm.png", + "assertion": "Look at the 'Dynamic theme colors' row. Is its toggle switch in the ON state — a filled blue/coloured track with the round thumb positioned on the RIGHT side?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_dynamic_theme_on", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_keep_screen_off_vlm", + "screenshot": "states_keep_screen_off_vlm.png", + "assertion": "Look at the 'Keep screen ON while recording' row. Is its toggle switch in the OFF state — a grey/unfilled track with the round thumb positioned on the LEFT side?", + "form": "question", + "expected": true, + "aspect": "color", + "modality": null, + "links_to": "states_keep_screen_off", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_format_chip_wav_vlm", + "screenshot": "states_format_chip_wav_vlm.png", + "assertion": "In the 'Recording format:' chip row, does the 'Wav' chip have a small round CHECKMARK (tick) icon to the LEFT of the word 'Wav', marking it as the selected chip, while the '3gp' chip has no such checkmark?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_format_chip_wav", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_bitrate_chip_96_vlm", + "screenshot": "states_bitrate_chip_96_vlm.png", + "assertion": "In the 'Bitrate:' chip row, does the '96 kbps' chip have a small round CHECKMARK (tick) icon to the LEFT of its label, marking it as the selected bitrate, while the '128 kbps' chip has no checkmark?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_bitrate_chip_96", + "rigor": { + "jump_kind": "none", + "depth": 1 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + }, + { + "id": "states_play_glyph_vlm", + "screenshot": "states_play_glyph_vlm.png", + "assertion": "In the middle of the screen, just below the waveform and above the large time display, there is a small playback-control icon. Is that icon a PAUSE symbol (two short vertical bars side by side), rather than a triangular play (▶) arrow?", + "form": "question", + "expected": true, + "aspect": "shape", + "modality": null, + "links_to": "states_play_glyph", + "rigor": { + "jump_kind": "none", + "depth": 0 + }, + "verdict": { + "answer": true, + "passed": true, + "raw": null + }, + "calibration": null + } + ], + "merged_from_files": 1, + "source_shapes": { + "list": 1 + } +} \ No newline at end of file diff --git a/android/dozingcat-vector-pinball/COPYING.txt b/android/dozingcat-vector-pinball/COPYING.txt new file mode 100644 index 0000000000000000000000000000000000000000..94a9ed024d3859793618152ea559a168bbcbb5e2 --- /dev/null +++ b/android/dozingcat-vector-pinball/COPYING.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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 for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know 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 License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of 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 of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification 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 of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. 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 work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a 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 visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation 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 to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients 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 to +produce it from the Program, in the form of source code under the +terms 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 independent +works, 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 not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-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 excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the 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 install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional 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 you +add to a covered work, you may (if authorized by the copyright holders of +that 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 "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form 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 expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered 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 automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent 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 anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain 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 limiting +any implied license or other defenses to infringement that may +otherwise 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 or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License 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 have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License 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 the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES 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 OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy 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 greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + 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 appropriate +parts of the General Public License. Of course, your program's commands +might 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 +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/android/dozingcat-vector-pinball/instance.json b/android/dozingcat-vector-pinball/instance.json new file mode 100644 index 0000000000000000000000000000000000000000..c589de5ed4edf2638e7902b5d871e0ae48425599 --- /dev/null +++ b/android/dozingcat-vector-pinball/instance.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "instance_id": "android/dozingcat-vector-pinball", + "platform": "android", + "repo": "https://github.com/dozingcat/Vector-Pinball", + "commit": "977529b52494ad800c5283173d231f8f58d24a9a", + "patches": [], + "package": "com.dozingcatsoftware.bouncy", + "license": null +} diff --git a/android/dozingcat-vector-pinball/reference/launch.sh b/android/dozingcat-vector-pinball/reference/launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8 --- /dev/null +++ b/android/dozingcat-vector-pinball/reference/launch.sh @@ -0,0 +1,9 @@ +#!/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 1