diff --git a/benchmark/IOAI/IOAI-2024/README.md b/benchmark/IOAI/IOAI-2024/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f452b3ab6e1a2da9c733a68ec841241c6bd6686b --- /dev/null +++ b/benchmark/IOAI/IOAI-2024/README.md @@ -0,0 +1,27 @@ +# International Olympiad in Artificial Intelligence + +## IOAI 2024 – Burgas, Bulgaria + +The **1st International Olympiad in Artificial Intelligence (IOAI 2024)** was held in **Burgas, Bulgaria**, from **August 9–15, 2024**. +Nearly **200 students** in **41 teams** from **32 countries and territories across 6 continents** participated in this inaugural global AI Olympiad. + +- 🌍 [Official Website – IOAI 2024](https://ioai-official.org/2024-bulgaria/) +- 🏆 [Official Results](https://ioai-official.org/2024-bulgaria/results/) + +--- + +## Competition Rounds + +### 🔬 Scientific Round +- **Take-home stage**: One month of tasks in **Machine Learning, NLP, and Computer Vision**. +- **On-site stage**: 8-hour competition in Burgas on similar topics. + +### 🎨 Practical (Team Challenge) Round +- Teams had **4 hours onsite** to use **AI image/video generation tools**. +- Task: Design a **music album cover and video** for Maria Ilieva’s track *"Love"*. + +## License + +This work is released under the **Creative Commons Attribution 4.0 International (CC-BY-4.0)** License. +You may share and adapt this content as long as proper credit is given and changes are clearly indicated. + diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/answer_conditioned_v11_trace_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/answer_conditioned_v11_trace_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..8311722c5716c037c7ba526c97605a62fd36a753 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/answer_conditioned_v11_trace_audit.json @@ -0,0 +1,48 @@ +{ + "schema_version": "answer_conditioned_v11_trace_audit_v1", + "review_scope": { + "data": "data/rl/ioling_qwen3_4b_manual_v11_clean_prompt/val.jsonl", + "model": "Qwen/Qwen3-4B-Instruct-2507", + "sample_index": 0, + "conditions": [ + "answer_target_only", + "answer_target_plus_official_solution_rules" + ], + "records_per_condition": 24, + "total_traces_read": 48 + }, + "decision_rule": "Accept only if every supporting claim is consistent with the paired examples and official solution rules, the target is derived rather than cited, and the final answer is exact.", + "summary": { + "answer_target_only_accepted": 0, + "answer_target_only_rejected": 24, + "official_rules_accepted": 0, + "official_rules_rejected": 24, + "important_result": "Final-answer exactness was above 92% in both conditions but had zero precision for an acceptable rationale in this first-sample manual audit." + }, + "records": [ + {"record_id":"iol-2015-individual-p1-sub-b-atomic-b.1","answer_target_only":"reject: lists equations without deriving 42 and assigns wrong values","official_rules":"reject: misreads equation (1) as a base-20 identity and never derives 42 = 2*20+2"}, + {"record_id":"iol-2015-individual-p1-sub-b-atomic-b.2","answer_target_only":"reject: lists unrelated equations and does not derive 494","official_rules":"reject: assigns 20 to mahtlactli and misstates equations (1), (3), and (14)"}, + {"record_id":"iol-2015-individual-p1-sub-c-atomic-c.1","answer_target_only":"reject: repeats Arammba equations without solving their values","official_rules":"reject: includes false arithmetic and wrong values for asar, nimbo, and tambaroy"}, + {"record_id":"iol-2015-individual-p1-sub-c-atomic-c.2","answer_target_only":"reject: does not derive the base-6 expansion of 569","official_rules":"reject: assigns 6 to asar and yànparo and gives inconsistent base-6 arithmetic"}, + {"record_id":"iol-2016-individual-p3-sub-a-atomic-a.1","answer_target_only":"reject: swaps verb and noun meanings and concludes a different sentence than the target","official_rules":"reject: cites another target as evidence and assigns person, case, and tense roles incorrectly"}, + {"record_id":"iol-2016-individual-p3-sub-a-atomic-a.2","answer_target_only":"reject: treats noun stems as verbs and maps several words to the wrong examples","official_rules":"reject: calls tirt a repair verb and invents an indirect object in sentence 2"}, + {"record_id":"iol-2016-individual-p3-sub-a-atomic-a.3","answer_target_only":"reject: explicitly finds contradictions, then invents a semantic shift to copy the answer","official_rules":"reject: reverses the S-O-V analysis; hanu is donkey, tirtiig is owners as object, and elirsu is the verb"}, + {"record_id":"iol-2016-individual-p3-sub-a-atomic-a.4","answer_target_only":"reject: assigns repair/found meanings to target morphemes and never composes the translation","official_rules":"reject: calls the subject tirti a verb and the verb deccirsa an object marker"}, + {"record_id":"iol-2016-individual-p3-sub-a-atomic-a.5","answer_target_only":"reject: says the construction denotes giving or striking rather than buying","official_rules":"reject: treats ay as a tense marker, darbadki as a verb, and bijaandi as an object"}, + {"record_id":"iol-2016-individual-p3-sub-b-atomic-b.1","answer_target_only":"reject: omits the required final box and never maps the requested sentence","official_rules":"reject: later bullets assign the object and recipient roles incorrectly and cite unrelated targets"}, + {"record_id":"iol-2016-individual-p3-sub-b-atomic-b.2","answer_target_only":"reject: assigns neighbours, camels, and verb meanings to the wrong forms","official_rules":"reject: analyzes case examples but does not derive jahal + argi + walgi + jaandeccirsu"}, + {"record_id":"iol-2016-individual-p3-sub-b-atomic-b.3","answer_target_only":"reject: invents tense and transitivity facts and does not derive the requested form","official_rules":"reject: cites the target itself as an example and invents a dative analysis for bimaagru"}, + {"record_id":"iol-2016-individual-p3-sub-b-atomic-b.4","answer_target_only":"reject: unrelated examples do not establish the requested owners/thieves sentence","official_rules":"reject: calls plural owners singular and calls the direct object an indirect object"}, + {"record_id":"iol-2016-individual-p3-sub-b-atomic-b.5","answer_target_only":"reject: assigns give/beneficiary meanings instead of deriving found-for","official_rules":"reject: swaps indirect and direct objects and calls eltirsa a future give form"}, + {"record_id":"iol-2021-individual-p3-sub-a-atomic-a.1","answer_target_only":"reject: assigns noun, verb, and quantity meanings inconsistently","official_rules":"reject: calls vivila how-many; the quantity is navila and biyamata is the future verb"}, + {"record_id":"iol-2021-individual-p3-sub-a-atomic-a.2","answer_target_only":"reject: analyzes the preceding question rather than the requested sentence","official_rules":"reject: again analyzes item 14 rather than deriving item 15"}, + {"record_id":"iol-2021-individual-p3-sub-a-atomic-a.3","answer_target_only":"reject: invents see meanings and two translations not supported by the target","official_rules":"reject: includes unsupported aspect ambiguity and wrong morpheme roles despite the correct final translation"}, + {"record_id":"iol-2021-individual-p3-sub-a-atomic-a.4","answer_target_only":"reject: invents reciprocal and subject-object evidence from unrelated examples","official_rules":"reject: explains the ambiguity using false reciprocal and example mappings"}, + {"record_id":"iol-2021-individual-p3-sub-a-atomic-a.5","answer_target_only":"reject: does not identify the actual verb, quantity, and noun-class components","official_rules":"reject: calls ketala a past-tense verb; it is the one-canoe quantity phrase"}, + {"record_id":"iol-2021-individual-p3-sub-b-atomic-b.1","answer_target_only":"reject: assigns see, canoe, and subject meanings to the wrong words","official_rules":"reject: says waga means saw and minasiwena means one canoe"}, + {"record_id":"iol-2021-individual-p3-sub-b-atomic-b.2","answer_target_only":"reject: analyzes sentence 19 instead of composing sentence 20","official_rules":"reject: focuses on the preceding canoe question and assigns target morphemes incorrectly"}, + {"record_id":"iol-2021-individual-p3-sub-b-atomic-b.3","answer_target_only":"reject: includes incorrect noun and number mappings despite copying the target","official_rules":"reject: claims bunukwa comes from the fish example and gives unsupported word-order claims"}, + {"record_id":"iol-2021-individual-p3-sub-b-atomic-b.4","answer_target_only":"reject: maps catch, fish, woman, and adjective forms incorrectly","official_rules":"reject: calls vivila a future verb and misidentifies the demonstrative and adjective forms"}, + {"record_id":"iol-2021-individual-p3-sub-b-atomic-b.5","answer_target_only":"reject: assigns dog, old-man, and numeral meanings to the wrong forms","official_rules":"reject: calls tomwaya a wild dog and ka'ukwa a quantity rather than the dog noun"} + ] +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/clean_bootstrap_v1_trace_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/clean_bootstrap_v1_trace_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..ca316ecf3e37740d33caae95eb758bf53092ccdb --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/clean_bootstrap_v1_trace_audit.json @@ -0,0 +1,23 @@ +{ + "schema_version": "clean_bootstrap_v1_trace_audit", + "report": "reports/sft_clean_bootstrap_v1_both_pass8.json", + "review_scope": "All exact samples plus the highest-similarity validation outputs", + "summary": { + "exact_train_samples": 4, + "exact_validation_samples": 0, + "accepted_exact_rationales": 0, + "rejected_exact_rationales": 4, + "validation_near_miss_conclusion": "The closest outputs were semantically wrong, not scorer false negatives." + }, + "exact_samples": [ + {"record_id":"iol-2016-individual-p5-sub-a-atomic-a.1","sample_index":2,"decision":"reject","reason":"Long speculative analysis repeatedly assigns incompatible meanings to the interrogative and locative suffixes before reaching the exact answer."}, + {"record_id":"iol-2016-individual-p5-sub-a-atomic-a.1","sample_index":6,"decision":"reject","reason":"The trace invents and revises several suffix analyses; the exact final translation is an unsupported late guess."}, + {"record_id":"iol-2021-individual-p1-sub-a-atomic-a.2","sample_index":0,"decision":"reject","reason":"The trace explicitly guesses 39 from the statement that one target duplicates an example and contains many false arithmetic hypotheses."}, + {"record_id":"iol-2024-individual-p1-sub-a-atomic-a.2","sample_index":4,"decision":"reject","reason":"The trace confuses object endings with tense and repeatedly guesses verb roots before copying the correct compositional reading."} + ], + "validation_near_misses": [ + {"record_id":"iol-2021-individual-p3-sub-a-atomic-a.1","samples":8,"candidate_pattern":"How many women will look after this/that man?","reason":"All samples omit old and reverse the required subject/object relation; this is not an equivalent paraphrase."}, + {"record_id":"iol-2016-individual-p3-sub-a-atomic-a.5","candidate":"I will give the dogs the chicken","reason":"The requested sentence means I will buy the chicken; the candidate has the wrong verb and adds a recipient."}, + {"record_id":"iol-2021-individual-p3-sub-a-atomic-a.4","candidate":"How many women did the chiefs see?","reason":"The candidate changes tense and all central participants and omits the official ambiguity."} + ] +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/composition_answer_reconstruction_v1_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/composition_answer_reconstruction_v1_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..c4dd2ac3b66f56fabfc44625808266b9dd174bb1 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/composition_answer_reconstruction_v1_audit.json @@ -0,0 +1,154 @@ +{ + "schema_version": "ioling_composition_answer_reconstruction_audit_v1", + "created_at_utc": "2026-07-12", + "report": "reports/composition_answer_reconstruction_v1_balanced_pass2.json", + "review_scope": "All 40 answer-exposed reconstruction outputs were read against the checked card, including the two outputs that did not score exact.", + "acceptance_rule": "Accept only a coherent derivation whose substantive claims all follow from the manually checked facts. Supplying the final answer during generation does not validate the reasoning.", + "outputs_reviewed": 40, + "scorer_exact_outputs": 38, + "accepted_traces": 5, + "accepted_records": 5, + "selected_traces": 5, + "decisions": { + "iol-2012-individual-p5-sub-d-atomic-d.1": { + "accepted": [], + "rejected": { + "0": "It derives only two of three alternatives and invents transformations.", + "1": "It omits one alternative and gives an incoherent account of the phrase-form rules." + } + }, + "iol-2012-individual-p5-sub-d-atomic-d.2": { + "accepted": [], + "rejected": { + "0": "It copies all alternatives after an invented chain-shift derivation.", + "1": "The metaphonic and phonotactic explanation is invented and incoherent." + } + }, + "iol-2016-individual-p5-sub-a-atomic-a.1": { + "accepted": [], + "rejected": { + "0": "It omits the locative suffix from the stated segmentation.", + "1": "It misidentifies ut as 'my' and invents examples." + } + }, + "iol-2012-individual-p1-sub-b-atomic-b.2": { + "accepted": [], + "rejected": { + "0": "It assigns the checked lexical meanings incorrectly and invents unrelated rules.", + "1": "It invents case functions and never applies the checked object-subject-verb parse." + } + }, + "iol-2012-individual-p1-sub-b-atomic-b.3": { + "accepted": [], + "rejected": { + "0": "It reverses the checked object and subject roles.", + "1": "It invents internal morpheme meanings and does not correctly apply object-subject-verb order." + } + }, + "iol-2011-individual-p1-sub-b-atomic-b.2": { + "accepted": [], + "rejected": { + "0": "It adds several invented sound changes after the correct component list.", + "1": "It says the lengthened vowel re-shortens, contradicting its own boxed form." + } + }, + "iol-2019-individual-p5-sub-a-atomic-a.2": { + "accepted": [], + "rejected": { + "0": "It invents person, gender, and present-tense morphology and omits the yam and today from the derivation.", + "1": "It incorrectly glosses le as market and adds unsupported syntax." + } + }, + "iol-2019-individual-p5-sub-a-atomic-a.4": { + "accepted": [], + "rejected": { + "0": "The lexical parse is present but it misdescribes the future marker and adds invented tense rules.", + "1": "It does not map the checked words and relies on invented pronominal claims." + } + }, + "iol-2016-individual-p5-sub-b-atomic-b.2": { + "accepted": [1], + "selected": 1, + "rejected": { + "0": "It says the vowel u in -ma is deleted; the deleted suffix vowel is a." + } + }, + "iol-2008-individual-p5-sub-a-atomic-a.6": { + "accepted": [], + "rejected": { + "0": "The core mapping is right, but it adds unsupported claims about prefixes and subject omission.", + "1": "The explanation is unrelated to the checked sentence." + } + }, + "iol-2021-individual-p1-sub-b-atomic-b.3": { + "accepted": [1], + "selected": 1, + "rejected": { + "0": "It introduces a false subtraction rule before giving the correct sum." + } + }, + "iol-2023-individual-p5-sub-b-atomic-b.2": { + "accepted": [1], + "selected": 1, + "rejected": { + "0": "It calls 80 a base unit for 100 and gives the wrong decomposition before copying the target." + } + }, + "iol-2023-individual-p5-sub-b-atomic-b.3": { + "accepted": [0], + "selected": 0, + "rejected": { + "1": "It gives incorrect component forms for the multiplier and units." + } + }, + "iol-2022-individual-p1-sub-b-atomic-b.2": { + "accepted": [], + "rejected": { + "0": "It assigns first-person and second-person prefixes to the wrong roles and gives the wrong vowel condition.", + "1": "It repeatedly assigns the indirect object incorrectly and contradicts itself." + } + }, + "iol-2022-individual-p1-sub-c-atomic-c.3": { + "accepted": [], + "rejected": { + "0": "It states that the vowel is a while boxing a form with schwa.", + "1": "It initially assigns the subject prefix incorrectly and again states a while boxing schwa." + } + }, + "iol-2024-individual-p1-sub-a-atomic-a.4": { + "accepted": [], + "rejected": { + "0": "It calls the second-person-plural object third-person and misstates -la.", + "1": "It ends by identifying the plural object as me and invents a sound description." + } + }, + "iol-2017-individual-p2-sub-c-atomic-c.3": { + "accepted": [], + "rejected": { + "0": "It assigns the possessor prefixes and body-part status incorrectly and adds unrelated claims.", + "1": "It derives he-ya and then boxes e-ya, contradicting the checked prefix rule." + } + }, + "iol-2017-individual-p3-sub-b-atomic-b.1": { + "accepted": [0], + "selected": 0, + "rejected": { + "1": "It invents an object marker and gives a contradictory tone account." + } + }, + "iol-2018-individual-p2-sub-a-atomic-a.1": { + "accepted": [], + "rejected": { + "0": "It adds false agreement and past-tense claims after the correct lexical mapping.", + "1": "It calls the intransitive construction transitive and alternates incorrectly between tu and ku." + } + }, + "iol-2018-individual-p3-sub-b-atomic-b.1": { + "accepted": [], + "rejected": { + "0": "It attaches the wrong native contrast to mbaho/peaho and misspells a checked example.", + "1": "It invents examples and does not support the full stated contrast cleanly." + } + } + } +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/composition_answer_reconstruction_v2_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/composition_answer_reconstruction_v2_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..5b66a912c707e753be25d6ad8552647d55d716d6 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/composition_answer_reconstruction_v2_audit.json @@ -0,0 +1,115 @@ +{ + "schema_version": "ioling_composition_answer_reconstruction_audit_v2", + "created_at_utc": "2026-07-12", + "report": "reports/composition_answer_reconstruction_v2_balanced_pass2.json", + "review_scope": "All 30 outputs from the fact-only reconstruction repair pass were read against the checked cards.", + "acceptance_rule": "Accept only when every substantive sentence directly applies or combines a checked fact. Correct boxes with invented or contradictory derivations are rejected.", + "outputs_reviewed": 30, + "scorer_exact_outputs": 25, + "accepted_traces": 7, + "accepted_records": 5, + "selected_traces": 5, + "decisions": { + "iol-2012-individual-p5-sub-d-atomic-d.1": { + "accepted": [], + "rejected": { + "0": "It derives only one of three alternatives and assigns an arbitrary omitted vowel.", + "1": "It derives only one alternative and invents vowel motion and syllabification." + } + }, + "iol-2012-individual-p5-sub-d-atomic-d.2": { + "accepted": [], + "rejected": { + "0": "It gives only one of six alternatives and the derivation is incoherent.", + "1": "It gives only one alternative after an entirely invented account." + } + }, + "iol-2016-individual-p5-sub-a-atomic-a.1": { + "accepted": [1], + "selected": 1, + "rejected": { + "0": "It incorrectly says -t means in." + } + }, + "iol-2012-individual-p1-sub-b-atomic-b.2": { + "accepted": [], + "rejected": { + "0": "It invents examples and does not apply the three checked phrase meanings.", + "1": "It invents morphology and never gives the checked object-subject-verb derivation." + } + }, + "iol-2012-individual-p1-sub-b-atomic-b.3": { + "accepted": [0, 1], + "selected": 0, + "rejected": {} + }, + "iol-2011-individual-p1-sub-b-atomic-b.2": { + "accepted": [], + "rejected": { + "0": "It substitutes unrelated forms instead of composing the checked morphemes.", + "1": "It relies on invented examples and sound descriptions." + } + }, + "iol-2019-individual-p5-sub-a-atomic-a.2": { + "accepted": [], + "rejected": { + "0": "It misglosses the final material and changes future seeing into something seen.", + "1": "It misglosses le and adds unrelated, partly non-English text." + } + }, + "iol-2019-individual-p5-sub-a-atomic-a.4": { + "accepted": [0, 1], + "selected": 0, + "rejected": {} + }, + "iol-2008-individual-p5-sub-a-atomic-a.6": { + "accepted": [0], + "selected": 0, + "rejected": { + "1": "It invents third-person forms and incorrectly says the subject receives the cure." + } + }, + "iol-2022-individual-p1-sub-b-atomic-b.2": { + "accepted": [], + "rejected": { + "0": "It gives the correct roles initially, then gives the wrong reason for a and invents a suffix role.", + "1": "It assigns every participant prefix incorrectly." + } + }, + "iol-2022-individual-p1-sub-c-atomic-c.3": { + "accepted": [], + "rejected": { + "0": "It assigns the subject prefix incorrectly and confuses the linking schwa with the agreement vowel.", + "1": "It treats the verb stem as the indirect-object marker and falsely says the direct object is not plural." + } + }, + "iol-2024-individual-p1-sub-a-atomic-a.4": { + "accepted": [], + "rejected": { + "0": "It begins with an inaccurate segmentation and ends with unrelated invented prose.", + "1": "The main person and tense mapping is right, but it omits the plural marker and adds an unsupported harmony claim." + } + }, + "iol-2017-individual-p2-sub-c-atomic-c.3": { + "accepted": [1], + "selected": 1, + "rejected": { + "0": "It incorrectly says the possessor follows the possessed noun." + } + }, + "iol-2018-individual-p2-sub-a-atomic-a.1": { + "accepted": [], + "rejected": { + "0": "It introduces a false past-tense account and misplaces agreement.", + "1": "It incorrectly places k- on the lexical predicate and adds an unsupported object contrast." + } + }, + "iol-2018-individual-p3-sub-b-atomic-b.1": { + "accepted": [], + "rejected": { + "0": "It gives only part of the required contrast and invents native examples.", + "1": "It invents transformed forms that do not match the checked pairs." + } + } + } +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/composition_guided_train_v1_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/composition_guided_train_v1_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..8336b6be4dfb662d842ab30e409fa67e59069c41 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/composition_guided_train_v1_audit.json @@ -0,0 +1,150 @@ +{ + "schema_version": "ioling_composition_guided_train_audit_v1", + "created_at_utc": "2026-07-12", + "report": "reports/composition_guided_train_v1_balanced_pass8.json", + "review_scope": "Every one of the 44 scorer-exact traces was read against the manually checked card and canonical answer.", + "acceptance_rule": "Accept only when the prose gives a coherent derivation supported by the checked facts, has no material contradiction or invented rule, and assigns every answer component correctly. Exact final answer matching alone is insufficient.", + "exact_traces_reviewed": 44, + "accepted_traces": 18, + "accepted_records": 12, + "selected_traces": 12, + "decisions": { + "iol-2016-individual-p5-sub-a-atomic-a.1": { + "accepted": [], + "rejected": { + "1": "The elision account is internally inconsistent and omits/misplaces -na.", + "3": "It gives the wrong intermediate form utna-txi instead of the checked suffix sequence.", + "6": "It misidentifies the morphemes and gives an incoherent segmentation." + } + }, + "iol-2016-individual-p5-sub-a-atomic-a.2": { + "accepted": [3], + "selected": 3, + "rejected": { + "2": "It invents unattested intermediate forms and vowel harmony.", + "4": "The syllable-level account is inaccurate and does not cleanly apply the two checked deletions." + } + }, + "iol-2012-individual-p1-sub-b-atomic-b.1": { + "accepted": [7], + "selected": 7, + "rejected": {} + }, + "iol-2012-individual-p1-sub-b-atomic-b.2": { + "accepted": [], + "rejected": { + "1": "It falsely describes the subject phrase as indicating possession." + } + }, + "iol-2012-individual-p1-sub-b-atomic-b.3": { + "accepted": [], + "rejected": { + "5": "The explanation invents a dual default and does not actually parse the checked phrases." + } + }, + "iol-2011-individual-p1-sub-b-atomic-b.3": { + "accepted": [1], + "selected": 1, + "rejected": { + "5": "The core concatenation is present, but the rest is incoherent and unsupported.", + "7": "It invents prefixes, possessive marking, and unrelated morphology." + } + }, + "iol-2011-individual-p1-sub-b-atomic-b.4": { + "accepted": [7], + "selected": 7, + "rejected": {} + }, + "iol-2019-individual-p5-sub-a-atomic-a.2": { + "accepted": [], + "rejected": { + "6": "It introduces false claims about object licensing and says 'we saw ... tonight' before changing to the supplied answer." + } + }, + "iol-2019-individual-p5-sub-a-atomic-a.4": { + "accepted": [], + "rejected": { + "0": "Most of the explanation is invented phonetic and temporal material.", + "1": "It incorrectly says the future event has already occurred and conflates the future marker with 'come'.", + "2": "It invents negation and unrelated temporal claims.", + "3": "The lexical parse is mostly right, but it ends with an unsupported compound-object claim rather than a complete derivation." + } + }, + "iol-2008-individual-p5-sub-a-atomic-a.2": { + "accepted": [2, 6], + "selected": 2, + "rejected": { + "0": "It invents movement, causation, and suffix functions not supported by the checked facts." + } + }, + "iol-2008-individual-p5-sub-a-atomic-a.4": { + "accepted": [2], + "selected": 2, + "rejected": { + "5": "It adds invented absolutive and suffix claims after the correct lexical mapping." + } + }, + "iol-2008-individual-p5-sub-a-atomic-a.6": { + "accepted": [], + "rejected": { + "0": "It first glosses the indefinite object as 'the hunter', contradicting the target definiteness.", + "2": "The person, tense, genitive, and voice analysis is largely invented and contradictory." + } + }, + "iol-2021-individual-p1-sub-b-atomic-b.4": { + "accepted": [1], + "selected": 1, + "rejected": {} + }, + "iol-2022-individual-p1-sub-b-atomic-b.2": { + "accepted": [], + "rejected": { + "2": "It assigns me to the indirect-object role and gives the wrong vowel condition.", + "4": "It initially assigns the second-person prefix to the wrong role and adds unsupported tense.", + "5": "It assigns s- to a third-person indirect object, contrary to the checked mapping.", + "7": "It invents directional and voice meanings and misdescribes participant roles." + } + }, + "iol-2024-individual-p1-sub-a-atomic-a.1": { + "accepted": [2], + "selected": 2, + "rejected": {} + }, + "iol-2024-individual-p1-sub-a-atomic-a.4": { + "accepted": [], + "rejected": { + "6": "The derivation reverses tense, subject, and object markers and is incoherent despite the correct box." + } + }, + "iol-2017-individual-p2-sub-c-atomic-c.3": { + "accepted": [], + "rejected": { + "3": "The derivation is initially correct but then asserts the wrong extra form 'fe ya he-maama'." + } + }, + "iol-2017-individual-p2-sub-c-atomic-c.4": { + "accepted": [1, 3], + "selected": 3, + "rejected": { + "2": "It attributes body-part marking to first-person possession and omits the reason for h-." + } + }, + "iol-2017-individual-p3-sub-a-atomic-a.1": { + "accepted": [3], + "selected": 3, + "rejected": {} + }, + "iol-2017-individual-p3-sub-a-atomic-a.3": { + "accepted": [0, 1, 2, 5, 6], + "selected": 1, + "rejected": {} + }, + "iol-2018-individual-p2-sub-a-atomic-a.2": { + "accepted": [4], + "selected": 4, + "rejected": { + "7": "It reverses the participants and tense/person rules before copying the correct answer." + } + } + } +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/composition_manual_completion_traces_v1.json b/benchmark/IOL/ioling_hf/data/manual_overrides/composition_manual_completion_traces_v1.json new file mode 100644 index 0000000000000000000000000000000000000000..4b5084ef9491fc086c15fb5115ede831205181ec --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/composition_manual_completion_traces_v1.json @@ -0,0 +1,17 @@ +{ + "schema_version": "ioling_composition_manual_completion_traces_v1", + "created_at_utc": "2026-07-12", + "review_method": "Each trace was written directly from the manually checked composition card and checked against the raw problem target and canonical answer.", + "records": { + "iol-2012-individual-p5-sub-d-atomic-d.1": "The phrase form fäeag can be reversed in three compatible ways. Transposing final -ga gives fäega; restoring a deleted final vowel gives either fäeaga or fäeagu. These are all forms allowed by the observed phrase-form rules.\n\n\\boxed{d.1: fäega (or fäeaga, fäeagu)}", + "iol-2012-individual-p5-sub-d-atomic-d.2": "The phrase form a‘öf can result from the final-vowel deletion, vowel-mutation, or transposition patterns. Reversing every compatible pattern gives a‘ofi, a‘öfi, a‘öfö, a‘öfu, a‘öfü, and a‘ofü.\n\n\\boxed{d.2: a‘ofi (or a‘öfi, a‘öfö, a‘öfu, a‘öfü, a‘ofü)}", + "iol-2012-individual-p1-sub-b-atomic-b.2": "Dyirbal places the object before the subject and verb. Here bala diban bilmbalmuNa is the stone that is always being pushed, baNgun biñéiriñéu is the lizard, and guniñu is searching for. Thus the lizard is searching for that stone.\n\n\\boxed{b.2: The lizard is searching for the stone that is always being pushed.}", + "iol-2011-individual-p1-sub-b-atomic-b.2": "Combine ke- for we1+2, kaw for down, -en for by hand, and transitive -æq for we1+2. The first two vowels are short, so the a in kaw lengthens to ā. The resulting form is kekāwenæq.\n\n\\boxed{b.2: kekāwenæq}", + "iol-2019-individual-p5-sub-a-atomic-a.2": "me is I; nú géː marks future today; yɛn ... lé is see; kèŋkfǔ is yam; and ɛ̀bɛ̀n is today. With first-person n-, géː and yɛn surface as ŋgéː and nyɛ́n. The sentence therefore says that today I will see the yam.\n\n\\boxed{a.2: Today, I will see the yam.}", + "iol-2022-individual-p1-sub-b-atomic-b.2": "In səŝʷtʷan, s- marks me as the direct object and ŝʷ- marks you(pl) as the subject. The third-person-singular indirect object is unmarked, and tʷ is the give stem. Therefore you(pl) give me to him.\n\n\\boxed{b.2: you(pl) give me to him}", + "iol-2022-individual-p1-sub-c-atomic-c.3": "The direct object us takes šʼ-, the third-person-singular indirect object is unmarked, and the subject you(sg) takes w-. Schwa separates the adjacent prefixes, while the plural direct object selects a in the ending -an. With the stem tʷ, this gives šʼəwtʷan.\n\n\\boxed{c.3: šʼəwtʷan}", + "iol-2024-individual-p1-sub-a-atomic-a.4": "The initial t- marks I and je- marks future. The harmonized root means wait, -la marks plural participation, and -tək marks a second-person-plural object. Thus təjohallaŋtək means I will wait for you(pl).\n\n\\boxed{a.4: I will wait for you(pl)}", + "iol-2018-individual-p2-sub-a-atomic-a.1": "nɤ is you(sg) and ʒip is sleep. The agreement form ku consists of present k- plus the second-person-singular suffix -u, and final ne marks the question. Thus the sentence asks whether you(sg) sleep.\n\n\\boxed{a.1: Do you(sg) sleep?}", + "iol-2018-individual-p3-sub-b-atomic-b.1": "The second-person-singular forms show a special rule in Portuguese loans: á becomes eá, as in leápina and leátana. Native Terêna instead has á→é and â→eâ, as shown by ngásaxo/késaxo and mbâho/peâho.\n\n\\boxed{b.1: Portuguese á→eá versus native á→é and â→eâ}" + } +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/composition_opd_v1_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/composition_opd_v1_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..0d4c40cd20ddba5d4cf3b2e2ad0d08095aa69cac --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/composition_opd_v1_audit.json @@ -0,0 +1,69 @@ +{ + "schema_version": "ioling_composition_opd_v1_manual_audit", + "reviewed_at_utc": "2026-07-12", + "starting_checkpoint": "checkpoints/qwen3-4b-ioling-microsteps-balanced-v2-e5", + "cards": { + "path": "data/manual_overrides/train_composition_cards_v1.json", + "eligible_no_answer_records": 77, + "excluded_answer_exposed_records": 46, + "selected_records": 32, + "selected_sources": 14, + "selected_cards_manually_read": 32, + "manual_revisions": 2, + "complete_answer_units_exposed": 0 + }, + "raw_on_policy_rollouts": { + "report": "reports/composition_opd_v1_raw_train_pass8.json", + "wandb": "https://wandb.ai/alexgurung/ioling-research/runs/apvnaxl1", + "records": 32, + "samples": 256, + "temperature": 1.0, + "max_tokens": 4096, + "exact_samples": 2, + "records_with_any_exact": 2, + "exact_rationales_manually_reviewed": 2, + "exact_rationales_accepted": 0, + "finding": "The Jaqaru exact trace invented reflexive, class, and tense claims; the Hakhun exact trace invented pronoun and agreement rules. Neither is training-quality reasoning." + }, + "training": { + "framework": "full-vocabulary forward KL on raw student prefixes with a frozen same-model privileged teacher", + "wandb": "https://wandb.ai/alexgurung/ioling-research/runs/tydc2lj4", + "output_adapter": "checkpoints/qwen3-4b-ioling-microsteps-balanced-v2-e5-opd-composition-v1", + "records": 32, + "source_problems": 14, + "reasoning_tokens": 3425, + "max_reasoning_tokens_per_record": 128, + "optimizer_updates": 4, + "learning_rate": 0.0000005, + "gradient_accumulation_steps": 8, + "mean_forward_kl": 0.25354478042572737, + "final_answer_tokens_masked": true + }, + "held_out_raw": { + "report": "reports/composition_opd_v1_v14_val_pass8.json", + "wandb": "https://wandb.ai/alexgurung/ioling-research/runs/v67kqtd0", + "records": 24, + "samples": 192, + "exact_samples": 0, + "records_with_any_exact": 0, + "format_rate": 0.9895833333333334, + "truncation_rate": 0.005208333333333333, + "visible_final_boxes_manually_reviewed": 190, + "scorer_false_negatives": 0 + }, + "held_out_microsteps": { + "report": "reports/microsteps/qwen3_4b_opd_composition_v1_validation_pass8.json", + "wandb": "https://wandb.ai/alexgurung/ioling-research/runs/vjhjaxq5", + "samples": 320, + "correct_samples": 47, + "pass_at_8_tasks": 13, + "pre_correct_samples": 47, + "pre_pass_at_8_tasks": 14, + "all_outputs_manually_reviewed": 320, + "scorer_false_negatives": 0, + "gained_tasks": [], + "lost_tasks": ["arammba-power-36"] + }, + "runtime_note": "Direct vLLM LoRA serving was stopped before generation after adapter-specialized graph compilation stalled for several minutes. The adapter was merged once; all authoritative evaluations use the merged weights.", + "decision": "Do not run a second pass. Verified target-specific cards create useful guided support, but dense KL over incorrect raw-prefix tokens neither improves raw held-out answers nor intermediate coverage. The next pilot should train only verified continuations or keyed composition decisions selected from the guided distribution." +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/composition_scaffold_v1_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/composition_scaffold_v1_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..7d6c8e119b71128880cb2fe62ba0fb371e7decb4 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/composition_scaffold_v1_audit.json @@ -0,0 +1,69 @@ +{ + "schema_version": "ioling_composition_scaffold_v1_manual_audit", + "reviewed_at_utc": "2026-07-12", + "data": { + "validation_records": 24, + "validation_sources": 3, + "composition_cards": "data/manual_overrides/validation_composition_cards_v1.json", + "cards_manually_reviewed": 24, + "official_solution_pages_manually_read": 6, + "full_answer_units_exposed_by_cards": 0 + }, + "generic_source_microsteps": { + "report": "reports/composition_scaffold_v1_balanced_val_pass8.json", + "wandb": "https://wandb.ai/alexgurung/ioling-research/runs/ngzf1spk", + "samples": 192, + "exact_samples": 0, + "records_with_any_exact": 0, + "all_final_boxes_manually_reviewed": 192, + "finding": "The model used supplied order and class rules but lacked target lexical mappings and target-specific decomposition." + }, + "target_specific_cards": { + "report": "reports/composition_cards_v1_balanced_val_pass8.json", + "generation_wandb": "https://wandb.ai/alexgurung/ioling-research/runs/qgeuaz9b", + "final_rescore_wandb": "https://wandb.ai/alexgurung/ioling-research/runs/cwb3peds", + "samples": 192, + "format_valid": 192, + "truncated": 0, + "final_exact_samples": 23, + "records_with_any_exact": 9, + "all_final_boxes_manually_reviewed": 192, + "exact_traces_manually_reviewed": 23, + "reasoning_accepted": 13, + "reasoning_rejected": 10 + }, + "scorer_review": { + "override_ledger": "data/manual_overrides/scoring_overrides_v1.json", + "false_positives_found": 4, + "false_positive_cause": "Four Nahuatl answers retained uppercase metanotation M in -oM-. Case folding incorrectly treated it as realized lowercase m.", + "false_negatives_found": 6, + "false_negative_classes": [ + "Three Arammba answers preserved the official token sequence with reviewed hyphen separators.", + "One Kunuz English answer used the equivalent dative paraphrase 'gave the camel to us'.", + "Two Kilivila answers inserted transparent morpheme-boundary hyphens whose removal gives the official form exactly." + ], + "rejected_near_miss_classes": [ + "Different number, tense, deixis, participant role, or lexical item.", + "Extra arithmetic operators or extra Arammba tàxwo.", + "Underlying segmentation that fails required surface morphophonology.", + "Reordered words or omitted required ambiguity reading." + ], + "final_scorer": "normalized_keyed_answer_v2_with_unit_case_overrides_v1" + }, + "accepted_reasoning": [ + {"record_id": "iol-2015-individual-p1-sub-c-atomic-c.1", "sample_indexes": [0, 1, 2, 3, 4, 7], "count": 6}, + {"record_id": "iol-2015-individual-p1-sub-c-atomic-c.2", "sample_indexes": [2, 3, 4, 5, 7], "count": 5}, + {"record_id": "iol-2016-individual-p3-sub-a-atomic-a.4", "sample_indexes": [0], "count": 1}, + {"record_id": "iol-2021-individual-p3-sub-a-atomic-a.3", "sample_indexes": [4], "count": 1} + ], + "rejected_exact_reasoning": [ + {"record_id": "iol-2015-individual-p1-sub-c-atomic-c.1", "sample_indexes": [6], "reason": "Claims fete means sixty rather than 36."}, + {"record_id": "iol-2016-individual-p3-sub-a-atomic-a.5", "sample_indexes": [7], "reason": "Calls the finite form an infinitive and gives a false -r+r derivation."}, + {"record_id": "iol-2021-individual-p3-sub-a-atomic-a.2", "sample_indexes": [0], "reason": "Contradicts the verified V-O-S order."}, + {"record_id": "iol-2021-individual-p3-sub-a-atomic-a.3", "sample_indexes": [2, 5, 6], "reason": "Adds invented voice, phonology, existential, or season claims."}, + {"record_id": "iol-2021-individual-p3-sub-a-atomic-a.5", "sample_indexes": [5], "reason": "States both subject-before-object and object-before-subject analyses."}, + {"record_id": "iol-2021-individual-p3-sub-b-atomic-b.3", "sample_indexes": [3, 7], "reason": "Final forms are valid reviewed segmentations, but the explanations add invented or unsupported grammatical claims."}, + {"record_id": "iol-2021-individual-p3-sub-b-atomic-b.4", "sample_indexes": [3], "reason": "Invents an oblique suffix analysis and unrelated unsupported prose."} + ], + "decision": "Proceed with a small selective composition-distillation pilot. Use source-balanced raw student prefixes and teacher-only target cards that contain no complete answer unit. Do not train on unchecked guided prose or treat final-answer correctness as rationale validity." +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/focused_reasoning_trace_audit_v1.json b/benchmark/IOL/ioling_hf/data/manual_overrides/focused_reasoning_trace_audit_v1.json new file mode 100644 index 0000000000000000000000000000000000000000..c542981880d486e0cc242a7b1d735aa35afef01b --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/focused_reasoning_trace_audit_v1.json @@ -0,0 +1,70 @@ +{ + "schema_version": "ioling_focused_reasoning_trace_audit_v1", + "reviewer": "Codex, manual trace-by-trace comparison with rendered official problem and solution pages", + "reviewed_at_utc": "2026-07-11", + "criteria": { + "faithful": "The final answer is exact and every stated mapping, segmentation, grammatical role, arithmetic operation, and example citation is supported by the official rules/problem.", + "reject": "Reject the entire trace if it contains any false intermediate claim, incorrect example gloss, role/tense/case error, unsupported derivation, or self-correction from a materially false path." + }, + "audits": [ + { + "run": "Qwen_Qwen3-4B-Instruct-2507__qwen3_4b_focus_v3_official_rules.json", + "method": "rule_decomposition", + "exact_samples_reviewed": 30, + "faithful_samples": 16, + "rejected_exact_samples": 14, + "records": [ + { + "record_id": "iol-2015-individual-p1-sub-b-atomic-b.1", + "exact_sample_indices": [0, 2, 3, 4, 5], + "faithful_sample_indices": [2, 4], + "rejected_sample_indices": [0, 3, 5], + "note": "Rejected traces misstate the linker trigger, describe 2*20 imprecisely, or cite a derived 41 form as if it were supplied." + }, + { + "record_id": "iol-2015-individual-p1-sub-c-atomic-c.1", + "exact_sample_indices": [0, 1, 2, 3, 4, 5, 6, 7], + "faithful_sample_indices": [0, 1, 2, 3, 4, 5, 6, 7], + "rejected_sample_indices": [], + "note": "All eight correctly apply 43=36+6+1 and descending Arammba place order." + }, + { + "record_id": "iol-2016-individual-p3-sub-a-atomic-a.1", + "exact_sample_indices": [4], + "faithful_sample_indices": [], + "rejected_sample_indices": [4], + "note": "The reviewed simple-present answer alias is semantically acceptable, but this trace is rejected as a rationale because it contains false suffix and example analyses." + }, + { + "record_id": "iol-2016-individual-p3-sub-a-atomic-a.5", + "exact_sample_indices": [2, 3, 6, 7], + "faithful_sample_indices": [7], + "rejected_sample_indices": [2, 3, 6], + "note": "Rejected traces call -di a subject suffix; the official parse is bi-jaːn-d-i, with d the post-n allomorph of present/future -r and -i the 1sg subject suffix." + }, + { + "record_id": "iol-2021-individual-p3-sub-a-atomic-a.3", + "exact_sample_indices": [0, 1, 2, 3, 4, 5, 6, 7], + "faithful_sample_indices": [0, 2, 5, 6, 7], + "rejected_sample_indices": [1, 3, 4], + "note": "Rejected traces misassign QVX slots, call singular gwadi plural, or incorrectly treat past le- as a demonstrative." + }, + { + "record_id": "iol-2021-individual-p3-sub-a-atomic-a.5", + "exact_sample_indices": [0, 1, 2, 6], + "faithful_sample_indices": [], + "rejected_sample_indices": [0, 1, 2, 6], + "note": "All four exact traces, including the reviewed passive-answer alias, contain a materially wrong example gloss or demonstrative analysis despite deriving the correct V-O-S answer." + } + ] + }, + { + "run": "Qwen_Qwen3-4B-Instruct-2507__qwen3_4b_focus_v4_trusted_parse.json", + "method": "answer_trusted_parse", + "exact_samples_reviewed": 48, + "faithful_samples": 48, + "rejected_exact_samples": 0, + "qualification": "These are faithful constrained-imitation traces, not evidence that the model independently inferred the parse: both the trusted target parse and final answer were in the prompt." + } + ] +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/microstep_curriculum_v1_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/microstep_curriculum_v1_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..fe67cbb164f7d0701cd94d6cbd0473ad15d37e37 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/microstep_curriculum_v1_audit.json @@ -0,0 +1,132 @@ +{ + "schema_version": "ioling_microstep_curriculum_v1_audit", + "reviewed_at_utc": "2026-07-12", + "data": { + "train_ledger": "data/manual_overrides/train_microsteps_v1.json", + "validation_ledger": "data/manual_overrides/validation_microsteps_v1.json", + "train_tasks": 100, + "train_sources": 15, + "validation_tasks": 40, + "validation_sources": 3, + "source_overlap": [], + "validation_solution_pages_manually_read": 6, + "validation_sources_manually_read": [ + "2015-individual-1", + "2016-individual-3", + "2021-individual-3" + ] + }, + "scorer": { + "version": "reviewed_mapping_and_order_v3", + "association": "Every response must contain the requested step_id in a parsed JSON object.", + "normalization": "NFKC, casefolding, whitespace normalization, and reviewed punctuation normalization.", + "reviewed_equivalences": [ + "A numeric mapping may be stated as a sentence only when it contains exactly the expected integer and no competing integer.", + "Symbolic word-order answers may vary spaces, commas, parentheses, and separator hyphens but not symbol order or symbol inventory.", + "A mapping statement may start with the canonical form or end in an explicit is/means/represents/becomes predicate.", + "General substring matching, fuzzy edit distance, and model-judge acceptance are disabled." + ], + "tests": "tests/test_microstep_eval.py and tests/test_microstep_rl.py" + }, + "manual_output_review": { + "base_microstep_samples_reviewed": 320, + "balanced_sft_microstep_samples_reviewed": 320, + "qwen3_30b_microstep_samples_reviewed": 320, + "unbalanced_sft_visible_raw_finals_reviewed": 170, + "balanced_sft_visible_raw_finals_reviewed": 189, + "post_rl_visible_raw_finals_reviewed": 185, + "raw_final_scorer_false_negatives": 0, + "notes": [ + "The initial exact-value scorer missed valid sentence-wrapped numeric and lexical mappings and compact symbolic word orders; all reviewed equivalences were encoded narrowly and regression-tested.", + "Near Kilivila finals changed participants, tense, number, deixis, or modifiers and were not accepted as paraphrases.", + "Nahuatl and Arammba finals used wrong components or decompositions; Kunuz Nubian finals changed roots, cases, agreement, or roles." + ] + }, + "baselines": { + "qwen3_4b_base": { + "report": "reports/microsteps/qwen3_4b_base_validation_v1.json", + "wandb": "https://wandb.ai/alexgurung/ioling-research/runs/xj5k5u1v", + "correct_samples": 57, + "samples": 320, + "pass_at_8_tasks": 9, + "tasks": 40 + }, + "selected_v6_sft": { + "report": "reports/microsteps/qwen3_4b_selected_v6_e2_validation_v1.json", + "wandb": "https://wandb.ai/alexgurung/ioling-research/runs/hlz9lqpp", + "correct_samples": 58, + "samples": 320, + "pass_at_8_tasks": 9, + "tasks": 40 + }, + "qwen3_30b_raw": { + "report": "reports/microsteps/qwen3_30b_validation_v1.json", + "wandb": "https://wandb.ai/alexgurung/ioling-research/runs/ml22jowg", + "correct_samples": 38, + "samples": 320, + "pass_at_8_tasks": 6, + "tasks": 40 + } + }, + "unbalanced_sft": { + "wandb": "https://wandb.ai/alexgurung/ioling-research/runs/olnum9nm", + "rows": 223, + "epochs": 2, + "learning_rate": 0.000005, + "train_microstep_greedy": "8/100", + "validation_microstep_samples": "56/320", + "validation_microstep_pass_at_8": "9/40", + "raw_validation_exact": "0/192", + "raw_validation_format_rate": 0.8854166666666666, + "raw_validation_truncation_rate": 0.11458333333333333, + "decision": "Underfit because 1,677 microstep completion tokens were dominated by 7,028 raw-trace completion tokens. Do not interpret as a transfer test." + }, + "balanced_sft": { + "wandb": "https://wandb.ai/alexgurung/ioling-research/runs/a9j4dxpx", + "data": "data/sft/ioling_microsteps_and_selected_v2_balanced/train.jsonl", + "rows": 523, + "microstep_repetitions": 4, + "epochs": 5, + "learning_rate": 0.000005, + "train_microstep_greedy": "28/100", + "train_microstep_samples": "157/800", + "train_microstep_pass_at_8": "47/100", + "validation_microstep_report": "reports/microsteps/qwen3_4b_microsteps_balanced_v2_e5_validation_v1.json", + "validation_microstep_wandb": "https://wandb.ai/alexgurung/ioling-research/runs/4wjhfqf1", + "validation_microstep_samples": "47/320", + "validation_microstep_pass_at_8": "14/40", + "raw_validation_report": "reports/microsteps_balanced_v2_e5_v14_val_pass8.json", + "raw_validation_wandb": "https://wandb.ai/alexgurung/ioling-research/runs/a2cofea9", + "raw_validation_exact": "0/192", + "raw_validation_format_rate": 0.984375, + "raw_validation_truncation_rate": 0.010416666666666666 + }, + "microstep_rl": { + "framework": "OpenRLHF colocated one-GPU group-normalized PPO", + "wandb": "https://wandb.ai/alexgurung/ioling-rl/runs/n0bpuycd", + "episodes": 1, + "rollout_batch_size": 32, + "train_batch_size": 32, + "samples_per_prompt": 8, + "temperature": 1.0, + "max_new_tokens": 256, + "learning_rate": 0.0000005, + "vllm_gpu_memory_utilization": 0.5, + "final_rollout_reward": 0.21875, + "reward_fetch_failed": 0.0, + "final_rollout_format_rate": 0.99609375, + "internal_eval_pass_at_1": 0.175, + "internal_eval_pass_at_2": 0.25, + "matched_post_validation_microstep_report": "reports/microsteps/qwen3_4b_microsteps_balanced_v2_e5_grpo_v1_validation_pass8.json", + "matched_post_validation_microstep_wandb": "https://wandb.ai/alexgurung/ioling-research/runs/k772ijsk", + "matched_post_validation_microstep_samples": "48/320", + "matched_post_validation_microstep_pass_at_8": "14/40", + "matched_post_raw_report": "reports/microsteps_balanced_v2_e5_grpo_v1_v14_val_pass8.json", + "matched_post_raw_wandb": "https://wandb.ai/alexgurung/ioling-research/runs/ufmzgo2h", + "matched_post_raw_exact": "0/192", + "matched_post_raw_format_rate": 0.9635416666666666, + "matched_post_raw_truncation_rate": 0.020833333333333332, + "decision": "Do not run a second episode. Exact microstep reward fixes zero-reward optimization, but the matched held-out support and raw final accuracy did not improve." + }, + "overall_decision": "Keep the manually verified microstep data and scorer. The balanced SFT checkpoint improves held-out pass@8 task coverage and termination, but neither one SFT correction nor one exact-reward RL episode yields a correct raw final answer. The next data work must add source diversity and target-composition supervision; do not scale this RL recipe unchanged." +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/qwen3_30b_opd_teacher_audit_v1.json b/benchmark/IOL/ioling_hf/data/manual_overrides/qwen3_30b_opd_teacher_audit_v1.json new file mode 100644 index 0000000000000000000000000000000000000000..dccd5f279b8e07159c1e19dbf4168f283d92dee4 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/qwen3_30b_opd_teacher_audit_v1.json @@ -0,0 +1,110 @@ +{ + "schema_version": "ioling_qwen3_30b_opd_teacher_audit_v1", + "reviewed_at_utc": "2026-07-12", + "teacher": "Qwen/Qwen3-30B-A3B-Instruct-2507-FP8", + "compatibility_report": "reports/opd_qwen3_30b_teacher_prefix_compatibility_v1.json", + "compatibility_wandb_run": "https://wandb.ai/alexgurung/ioling-research/runs/en9lmb1x", + "compatibility_summary": { + "records": 12, + "source_problems": 12, + "tokens": 1536, + "mean_top_16_overlap": 0.626953125, + "low_compatibility_fraction": 0.7161458333333334, + "student_teacher_top_one_agreement": 0.779296875, + "sampled_token_teacher_top_one_rate": 0.76953125, + "sampled_token_teacher_top_five_rate": 0.9427083333333334, + "sampled_token_teacher_top_16_rate": 0.9830729166666666 + }, + "privileged_trace_report": "reports/answer_given_rationale/Qwen_Qwen3-30B-A3B-Instruct-2507-FP8__qwen3-30b-v14-privileged-trace-gate-n2.json", + "privileged_trace_wandb_run": "https://wandb.ai/alexgurung/ioling-research/runs/izq40g40", + "trace_review_rule": "Accept only when every bullet is true, grounded in a displayed example or checked rule, and sufficient for the final answer. Exact final-answer copying is not evidence of a valid rationale.", + "trace_reviews": [ + { + "record_id": "iol-2017-individual-p3-sub-a-atomic-a.3", + "sample_index": 0, + "decision": "reject", + "reason": "The fifth bullet falsely says kínà is not used with another verb; example 5 explicitly coordinates singing and dancing." + }, + { + "record_id": "iol-2017-individual-p3-sub-a-atomic-a.3", + "sample_index": 1, + "decision": "accept", + "reason": "The trace correctly identifies first-person ŋg-, the dance root kínà from example 5, and the low declarative final tone. These facts are sufficient for the short translation." + }, + { + "record_id": "iol-2018-individual-p2-sub-b-atomic-b.3", + "sample_index": 0, + "decision": "reject", + "reason": "Several citations are false: examples 2 and 8 are past rather than present r-, and their -u does not demonstrate a second-person object outranking a third-person subject." + }, + { + "record_id": "iol-2018-individual-p2-sub-b-atomic-b.3", + "sample_index": 1, + "decision": "reject", + "reason": "The trace cites examples 5, 7, 8, and 10 for person-role configurations they do not contain and describes post-predicate agreement as a verb prefix." + }, + { + "record_id": "iol-2018-individual-p3-sub-a-atomic-a.7", + "sample_index": 0, + "decision": "reject", + "reason": "It calls nd voiceless and says nd is preserved, while the checked rule and its own final form require reversing first-person nd to second-person t." + }, + { + "record_id": "iol-2018-individual-p3-sub-a-atomic-a.7", + "sample_index": 1, + "decision": "reject", + "reason": "It repeatedly claims consonant preservation even though ndôko to teôko changes nd to t, and it misdescribes ô as an initial vowel." + } + ], + "summary": { + "privileged_traces_reviewed": 6, + "privileged_traces_accepted": 1, + "privileged_traces_rejected": 5, + "free_form_sft_gate": "closed", + "sparse_cross_model_opd_gate": "tested_without_held_out_gain", + "teacher_target_records": 61, + "teacher_target_tokens": 7808, + "validation_samples": 192, + "validation_exact_samples": 0, + "validation_visible_finals_reviewed": 174, + "validation_scorer_false_negatives": 0 + }, + "sparse_target_collection": { + "data": "data/opd/qwen3_30b_teacher_targets_v1.jsonl", + "report": "reports/opd_qwen3_30b_teacher_targets_v1.json", + "wandb_run": "https://wandb.ai/alexgurung/ioling-research/runs/30t30cqb", + "records": 61, + "source_problems": 12, + "tokens": 7808, + "teacher_top_k": 20, + "mean_teacher_top_k_probability_mass": 0.9984599844408782, + "objective_partition": "The top-20 teacher tokens are represented separately and all remaining probability mass is retained as one residual bucket." + }, + "cross_model_training": { + "starting_adapter": "checkpoints/qwen3-4b-ioling-selected-v6-e2", + "output_adapter": "checkpoints/qwen3-4b-ioling-selected-v6-e2-opd-qwen3-30b-v1", + "wandb_run": "https://wandb.ai/alexgurung/ioling-research/runs/emhr0aox", + "learning_rate": 0.0000005, + "epochs": 1, + "optimizer_updates": 16, + "gradient_accumulation_steps": 4, + "mean_coarse_forward_kl": 0.7166733221441018 + }, + "validation_review": { + "report": "reports/opd_qwen3_30b_sparse_v1_v14_val_pass8.json", + "wandb_run": "https://wandb.ai/alexgurung/ioling-research/runs/xdo5u39m", + "samples": 192, + "exact_samples": 0, + "format_rate": 0.90625, + "truncation_rate": 0.09895833333333333, + "visible_finals_reviewed": 174, + "scorer_false_negatives": 0, + "scope": "Every strict final box was grouped by record with its verified canonical answer and aliases. Every distinct box was read; repeated boxes were counted and all 174 visible samples were covered.", + "findings": [ + "Nahuatl and Arammba answers used the wrong numeral components or values.", + "Kunuz Nubian answers changed lexical roots, semantic roles, number, or inflection.", + "Kilivila English answers changed predicates, participants, quantity, tense, or direction of care; generated Kilivila forms used unrelated lexemes and morphology." + ] + }, + "decision": "The 30B teacher is materially different from the 4B student and produced one valid short rationale, but five of six free-form traces contain false claims. Sparse top-20 targets retained 99.846% of teacher probability mass and supplied a dense coarse forward-KL update over 7,808 raw-prefix tokens. The matched held-out evaluation nevertheless remained 0/192 exact, and manual review of all 174 visible final boxes found no scorer false negative. Do not use generated teacher prose and do not run a second cross-model OPD pass. Dense privileged distillation bypasses zero reward technically, but this evidence does not show useful transfer on IOLing." +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/qwen3_4b_thinking_v1_trace_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/qwen3_4b_thinking_v1_trace_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..b3dbbda3a5a44c6162ddc7793122c3d2e2ff921e --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/qwen3_4b_thinking_v1_trace_audit.json @@ -0,0 +1,51 @@ +{ + "schema_version": "qwen3_4b_thinking_v1_trace_audit", + "reports": [ + "reports/qwen3_4b_thinking_2507_v12_val_pass8_4k.json", + "reports/qwen3_4b_thinking_2507_v12_focused_pass8_8k.json" + ], + "summary": { + "validation_4k_records": 24, + "validation_4k_samples": 192, + "validation_4k_exact_samples": 0, + "validation_4k_truncated_samples": 192, + "focused_8k_records": 4, + "focused_8k_samples": 32, + "focused_8k_exact_samples": 0, + "focused_8k_truncated_samples": 31, + "focused_8k_visible_finals": 1, + "accepted_rationales": 0 + }, + "manual_review": [ + { + "scope": "All 192 four-thousand-token candidates, reviewed by record and candidate tail", + "decision": "reject", + "reason": "Every candidate hit the cap while repeatedly changing lexical and arithmetic assignments. The traces were making substantive attempts, but they did not converge toward a stable derivation." + }, + { + "record_id": "iol-2015-individual-p1-sub-b-atomic-b.1", + "scope": "All eight focused eight-thousand-token candidates", + "decision": "reject", + "reason": "Seven traces hit the cap while cycling through incompatible numeral values. The only completed trace copied a large number from equation 13 as the answer for 42 and was clearly wrong." + }, + { + "record_id": "iol-2016-individual-p3-sub-a-atomic-a.5", + "scope": "All eight focused eight-thousand-token candidates", + "decision": "reject", + "reason": "All traces hit the cap. They repeatedly reversed noun and verb assignments already constrained by the examples and the four verified earlier items." + }, + { + "record_id": "iol-2021-individual-p3-sub-a-atomic-a.1", + "scope": "All eight focused eight-thousand-token candidates", + "decision": "reject", + "reason": "All traces hit the cap and converged only on semantically wrong variants that omit old or reverse who looks after whom." + }, + { + "record_id": "iol-2021-individual-p3-sub-b-atomic-b.1", + "scope": "All eight focused eight-thousand-token candidates", + "decision": "reject", + "reason": "All traces hit the cap while swapping the roles of nouns, verbs, demonstratives, and agreement forms. None reached the verified Kilivila sentence." + } + ], + "conclusion": "Doubling the generation budget does not repair the Qwen3-4B Thinking model on this panel. The dominant failure is unstable rule induction and repetition, not merely a final answer truncated shortly before completion." +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/rl_positive_trace_audit_v1.json b/benchmark/IOL/ioling_hf/data/manual_overrides/rl_positive_trace_audit_v1.json new file mode 100644 index 0000000000000000000000000000000000000000..01d79962f566d1606e81cb233fea4547407c6c35 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/rl_positive_trace_audit_v1.json @@ -0,0 +1,91 @@ +{ + "schema_version": "ioling_rl_positive_trace_audit_v1", + "reviewed_at_utc": "2026-07-11", + "probe": "reports/rl_distill_v1_strict_ep2_pass8.json", + "review_method": "Every strict-correct train completion was compared with the manually checked facts in train_target_derivations_v1.json. Final-answer correctness was not treated as evidence that the explanation was correct.", + "summary": { + "exact_answer_samples": 13, + "reasoning_accepted": 2, + "reasoning_rejected": 11 + }, + "samples": [ + { + "record_id": "iol-2016-individual-p5-sub-a-atomic-a.1", + "sample_index": 7, + "decision": "reject", + "reason": "Invents a suffix -ntxi and calls utu 'house'; the checked segmentation is uta + -nha + -na + -txi." + }, + { + "record_id": "iol-2019-individual-p5-sub-a-atomic-a.2", + "sample_index": 0, + "decision": "reject", + "reason": "The answer is correct, but the explanation is unrelated to the Nooni forms and invents a day-clause rule and a form yu'e." + }, + { + "record_id": "iol-2019-individual-p5-sub-a-atomic-a.3", + "sample_index": 4, + "decision": "reject", + "reason": "Uses invented suffix descriptions and does not derive the checked components wvù, tɔ̀ nɔ̂ː, yɛn ... lé, bèsèn, and bvúmbòn." + }, + { + "record_id": "iol-2019-individual-p5-sub-a-atomic-a.4", + "sample_index": 1, + "decision": "accept", + "reason": "Correctly identifies bèsèn 'we', nú bóy future, tɔ́ 'come', fɔ̀wǎy 'market', and bvúzhı᷇ːde᷆n as Bvuzhiden." + }, + { + "record_id": "iol-2016-individual-p5-sub-b-atomic-b.4", + "sample_index": 4, + "decision": "reject", + "reason": "Misidentifies the suffix chain and states a surface form different from both the checked derivation and its own final answer." + }, + { + "record_id": "iol-2016-individual-p5-sub-b-atomic-b.6", + "sample_index": 6, + "decision": "reject", + "reason": "Contains the useful uta + -txi observation, but wraps it in invented wording ('Ahouse') and an unsupported construction claim." + }, + { + "record_id": "iol-2016-individual-p5-sub-b-atomic-b.6", + "sample_index": 7, + "decision": "reject", + "reason": "Incorrectly analyzes uta as 'our house' and claims a reflected final vowel." + }, + { + "record_id": "iol-2008-individual-p5-sub-a-atomic-a.1", + "sample_index": 1, + "decision": "reject", + "reason": "The translation is correct, but most suffix claims conflict with the checked segmentation Amaru-up, angatku-it, and taku-j-anga." + }, + { + "record_id": "iol-2008-individual-p5-sub-a-atomic-a.3", + "sample_index": 3, + "decision": "reject", + "reason": "Recognizes the reflexive reading, but invents suffixes and person meanings not supported by the checked analysis." + }, + { + "record_id": "iol-2008-individual-p5-sub-a-atomic-a.3", + "sample_index": 6, + "decision": "reject", + "reason": "Contradicts its final answer by glossing aarqijuq as 'cured him' before answering 'cured himself'." + }, + { + "record_id": "iol-2008-individual-p5-sub-a-atomic-a.4", + "sample_index": 1, + "decision": "reject", + "reason": "Invents -mik and -up morphology absent from the target; the checked verb segmentation is qukiq-t-ait." + }, + { + "record_id": "iol-2008-individual-p5-sub-a-atomic-a.5", + "sample_index": 3, + "decision": "reject", + "reason": "Calls qaij a bear/possessive form and gives an incoherent account of -tit." + }, + { + "record_id": "iol-2008-individual-p5-sub-a-atomic-a.5", + "sample_index": 4, + "decision": "accept", + "reason": "Correctly identifies qai/qaij 'come' and -utit as the second-person subject ending." + } + ] +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/rule_rich_v1_trace_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/rule_rich_v1_trace_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..8d2992c8a04efada77d2a9aecb4a4ac429b29374 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/rule_rich_v1_trace_audit.json @@ -0,0 +1,24 @@ +{ + "schema_version": "rule_rich_v1_trace_audit", + "validation_report": "reports/sft_rule_rich_v1_val_pass8.json", + "train_probe_report": "reports/sft_rule_rich_v1_train_one_per_source_pass8.json", + "summary": { + "validation_exact_samples": 0, + "validation_samples": 192, + "train_probe_exact_samples": 2, + "train_probe_sources": 11, + "accepted_exact_rationales": 0, + "rejected_exact_rationales": 2, + "rl_gate": "closed" + }, + "exact_samples": [ + {"record_id":"iol-2019-individual-p5-sub-a-atomic-a.1","sample_index":2,"decision":"reject","reason":"The rationale invents unrelated day and tense forms, never derives the target from the supplied examples, and then emits a memorized exact answer."}, + {"record_id":"iol-2022-individual-p1-sub-a-atomic-a.1","sample_index":6,"decision":"reject","reason":"The rationale gives incoherent participant-order claims and only states the second reading after repeating the known first translation."} + ], + "validation_near_miss_review": [ + {"record_id":"iol-2016-individual-p3-sub-a-atomic-a.5","candidate":"I will strike the chickens.","reason":"Wrong verb and number; official answer is I will buy the chicken."}, + {"record_id":"iol-2015-individual-p1-sub-b-atomic-b.1","candidate":"mäcuïl-pöhualli-öme","reason":"Wrong coefficient and missing required additive linker; this is not an alternate spelling of 42."}, + {"record_id":"iol-2021-individual-p3-sub-a-atomic-a.1","candidate":"How many women will look after this man?","reason":"Omits old and reverses the old man's role; not semantically equivalent."} + ], + "decision": "Do not start accuracy-only RL or rationale distillation from this checkpoint. Exact source-seen boxes are unsupported memorization and held-out reward is zero." +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/rule_rich_v2_abui_trace_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/rule_rich_v2_abui_trace_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..7656362fbf2ce3d097083fae0170bab4d35d63f6 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/rule_rich_v2_abui_trace_audit.json @@ -0,0 +1,54 @@ +{ + "schema_version": "rule_rich_v2_abui_trace_audit", + "validation_report": "reports/sft_rule_rich_v2_abui_val_pass8.json", + "train_probe_report": "reports/sft_rule_rich_v2_abui_train_one_per_source_pass8.json", + "summary": { + "validation_records": 24, + "validation_samples": 192, + "validation_exact_samples": 0, + "validation_visible_final_answers_reviewed": 153, + "train_probe_sources": 12, + "train_probe_samples": 96, + "train_probe_exact_samples": 1, + "accepted_exact_rationales": 0, + "rejected_exact_rationales": 1, + "rl_gate": "closed" + }, + "validation_review": { + "decision": "no_scorer_false_negatives_found", + "scope": "Every candidate's final line was reviewed by record; truncated candidates and the closest semantic candidates were inspected separately.", + "notable_errors": [ + { + "record_id": "iol-2015-individual-p1-sub-c-atomic-c.2", + "sample_index": 1, + "candidate": "fete nimbo ngámbi", + "reason": "This is the verified earlier answer for 43, copied into the 569 target. It is correctly rejected." + }, + { + "record_id": "iol-2016-individual-p3-sub-a-atomic-a.5", + "candidate_pattern": "I will strike/give the chicken(s)", + "reason": "All variants have the wrong verb, number, or added recipient. The official answer is 'I will buy the chicken.'" + }, + { + "record_id": "iol-2021-individual-p3-sub-a-atomic-a.1", + "candidate_pattern": "How many women will look after this/that man?", + "reason": "The candidates omit 'old' and reverse who looks after whom. They are not equivalent to the verified answer." + } + ] + }, + "source_seen_exact": { + "record_id": "iol-2022-individual-p1-sub-a-atomic-a.1", + "sample_index": 5, + "decision": "reject", + "reason": "The exact box follows a long invented account of vowels, voice, and person roles. It never derives the alternate role assignment from the examples and is not a valid reasoning trace." + }, + "new_abui_source_probe": { + "record_id": "iol-2017-individual-p2-sub-b-atomic-b.1", + "samples_reviewed": 8, + "exact_samples": 0, + "completed_wrong_answers": ["nose", "upper part of a tree", "side", "his own eye", "people", "..."], + "truncated_samples": 2, + "conclusion": "The model did not recover that a- marks a possessed body part and zero marks a second-person-singular possessor, even on this source-seen task." + }, + "decision": "The eight-task Abui expansion does not change held-out accuracy or produce a valid exact source-seen rationale. Do not begin accuracy-only RL from this checkpoint." +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/scoring_overrides_v1.json b/benchmark/IOL/ioling_hf/data/manual_overrides/scoring_overrides_v1.json new file mode 100644 index 0000000000000000000000000000000000000000..3a3e7c3cd38e625faaa3509fefd714d750d28b81 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/scoring_overrides_v1.json @@ -0,0 +1,50 @@ +{ + "schema_version": "ioling_scoring_overrides_v1", + "reviewed_at_utc": "2026-07-12", + "reason": "Manual generation review found that case folding made unresolved linguistic metanotation score as a concrete answer.", + "records": { + "iol-2015-individual-p1-sub-b-atomic-b.1": { + "units": { + "b.1": { + "case_sensitive": true, + "note": "The official rule uses uppercase M as an unresolved allomorph variable. The answer must realize lowercase m in -om-." + } + } + }, + "iol-2015-individual-p1-sub-c-atomic-c.1": { + "units": { + "c.1": { + "accepted_values": ["fete-nimbo-ngámbi"], + "note": "Reviewed formatting variant with hyphens replacing spaces between the same three Arammba words." + } + } + }, + "iol-2015-individual-p1-sub-c-atomic-c.2": { + "units": { + "c.2": { + "accepted_values": ["yànparo-tarumba yenówe-fete asàr-tàxwo tambaroy"], + "note": "Reviewed formatting variant with term-internal hyphens and the official word order." + } + } + }, + "iol-2016-individual-p3-sub-a-atomic-a.4": { + "units": { + "a.4": { + "accepted_values": ["The owners gave the camel to us."], + "note": "English dative paraphrase of the official 'gave us the camel'." + } + } + }, + "iol-2021-individual-p3-sub-b-atomic-b.3": { + "units": { + "b.3": { + "accepted_values": [ + "Gudivila gugwadi bi-kamkwam-si bunukwa minasina?", + "Gudivila gugwadi bi-kamkwamsi bunukwa minasina?" + ], + "note": "Reviewed morpheme-boundary formatting of bikamkwamsi; removing the hyphens gives the official surface form exactly." + } + } + } + } +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/sft_v3_positive_trace_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/sft_v3_positive_trace_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..cf4e2b7851e9f33f4af0455d6055c593c90461fe --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/sft_v3_positive_trace_audit.json @@ -0,0 +1,15 @@ +{ + "schema_version": "sft_v3_positive_trace_audit_v1", + "report": "reports/sft_distill_v3_expanded_clean_both_pass8.json", + "reviewed_exact_samples": 6, + "accepted_rationales": 1, + "rejected_rationales": 5, + "records": [ + {"record_id":"iol-2019-individual-p5-sub-a-atomic-a.1","decision":"reject","reason":"Invents an unsupported day/following-day pattern and does not use the checked copular analysis."}, + {"record_id":"iol-2019-individual-p5-sub-a-atomic-a.4","decision":"reject","reason":"Splits the checked future marker nú bóy and incorrectly assigns future meaning to bóy alone."}, + {"record_id":"iol-2016-individual-p5-sub-b-atomic-b.6","decision":"reject","reason":"Claims -txi questions an object; the checked fact only establishes an interrogative suffix."}, + {"record_id":"iol-2008-individual-p5-sub-a-atomic-a.2","decision":"accept","reason":"The three lexical/morphological claims match the checked target parse and directly compose the answer."}, + {"record_id":"iol-2008-individual-p5-sub-a-atomic-a.3","decision":"reject","reason":"Contains several invented morphological claims and unrelated prose despite an exact final answer."}, + {"record_id":"iol-2008-individual-p5-sub-a-atomic-a.5","decision":"reject","reason":"Calls -utit specifically second-person plural although the checked evidence only supports second person here."} + ] +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/structured_analysis_v1_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/structured_analysis_v1_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..6dd93fd58db8b66334bb01c613e6a21bc4924668 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/structured_analysis_v1_audit.json @@ -0,0 +1,102 @@ +{ + "schema_version": "ioling_structured_analysis_v1_manual_audit", + "created_at_utc": "2026-07-12", + "dataset": { + "path": "data/sft/ioling_structured_analysis_v1/train.jsonl", + "rows": 369, + "records": 123, + "source_problems": 15, + "task_counts": { + "structured_analysis": 123, + "solve_with_checked_analysis": 123, + "raw_solve": 123 + }, + "reference_review": { + "scope": "One complete structured target was read from every training source after generation. The underlying rule cards, target facts, and final answers had already been manually checked against the official problem and solution pages in the v14 audit.", + "sources_reviewed": [ + "2008-individual-5", + "2011-individual-1", + "2011-individual-4", + "2012-individual-1", + "2012-individual-5", + "2016-individual-5", + "2017-individual-2", + "2017-individual-3", + "2018-individual-2", + "2018-individual-3", + "2019-individual-5", + "2021-individual-1", + "2022-individual-1", + "2023-individual-5", + "2024-individual-1" + ], + "sources_accepted": 15, + "sources_rejected": 0 + } + }, + "training": { + "model": "Qwen/Qwen3-4B-Instruct-2507", + "adapter": "checkpoints/qwen3-4b-ioling-structured-analysis-v1-e2", + "epochs": 2, + "learning_rate": 0.000005, + "effective_batch_size": 8, + "max_length": 4096, + "lora_rank": 32, + "lora_alpha": 64, + "optimizer_updates": 94, + "train_loss": 1.908604508701791, + "wandb_run": "https://wandb.ai/alexgurung/ioling-research/runs/degxhckr" + }, + "two_stage_validation": { + "report": "reports/structured_analysis_v1_e2_v14_val_2x4.json", + "records": 24, + "analysis_samples": 48, + "solve_samples": 192, + "analysis_format_valid": 20, + "analysis_truncated": 27, + "final_format_valid": 178, + "final_truncated": 0, + "exact_final_samples": 0, + "records_with_any_exact": 0, + "manual_analysis_review": { + "reviewed": 48, + "accepted": 0, + "rejected": 48, + "scope": "Every generated analysis was read in full, including malformed and truncated analyses.", + "findings": [ + "Nahuatl and Arammba analyses invented numerical values and operations, then looped over inconsistent assignments.", + "Kunuz Nubian analyses swapped noun and verb meanings, word order, and participant roles.", + "Kilivila analyses assigned demonstratives, numerals, thematic roles, and tense inconsistently." + ] + }, + "manual_final_review": { + "visible_finals_reviewed": 178, + "scorer_false_negatives": 0, + "scope": "Every strict boxed final was grouped by record and compared with its verified canonical answer and accepted aliases. Every distinct box was read; all were semantically wrong." + } + }, + "raw_validation": { + "report": "reports/structured_analysis_v1_e2_v14_val_raw_pass8.json", + "records": 24, + "samples": 192, + "visible_finals_reviewed": 122, + "exact_samples": 0, + "format_rate": 0.6354166666666666, + "truncation_rate": 0.3229166666666667, + "scorer_false_negatives": 0, + "scope": "Every strict boxed final was grouped by record and compared with its verified canonical answer and accepted aliases. Every distinct box was read; all were semantically wrong." + }, + "summary": { + "training_sources_manually_sampled": 15, + "generated_analyses_reviewed": 48, + "generated_analyses_accepted": 0, + "two_stage_final_samples": 192, + "two_stage_exact_samples": 0, + "two_stage_visible_finals_reviewed": 178, + "raw_final_samples": 192, + "raw_exact_samples": 0, + "raw_visible_finals_reviewed": 122, + "scorer_false_negatives_found": 0 + }, + "decision": "The separate intermediate target makes the failure observable, but the model did not generate one valid held-out analysis in 48 attempts. Do not scale this representation or aggregate its outputs. The next distillation experiment must verify concrete intermediate claims against displayed evidence before those claims receive a positive teacher weight." +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/student_trace_selection_v1.json b/benchmark/IOL/ioling_hf/data/manual_overrides/student_trace_selection_v1.json new file mode 100644 index 0000000000000000000000000000000000000000..819003dacf495923ca324aa35d3277faf8573c57 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/student_trace_selection_v1.json @@ -0,0 +1,46 @@ +{ + "schema_version": "ioling_student_trace_selection_v1", + "reviewed_at_utc": "2026-07-11", + "reviewer": "Codex, manual comparison of every selected trace with train_target_derivations_v1 checked facts", + "candidate_run": "reports/sft_trace_candidates/checkpoints_qwen3-4b-ioling-manual-sft-v1-e10-merged__e10_all_train_trusted_n8.json", + "records": { + "iol-2012-individual-p5-sub-d-atomic-d.1": {"method": "manual", "sample_index": null, "review_note": "All sampled exact traces invented phrase-form details."}, + "iol-2012-individual-p5-sub-d-atomic-d.2": {"method": "manual", "sample_index": null, "review_note": "All sampled exact traces invented or misstated vowel rules."}, + "iol-2016-individual-p5-sub-a-atomic-a.1": {"method": "answer_trusted_facts", "sample_index": 0, "review_note": "Uses only the checked suffix meanings."}, + "iol-2016-individual-p5-sub-a-atomic-a.2": {"method": "answer_trusted_facts", "sample_index": 2, "review_note": "Correct possessive and two-step vowel elision."}, + "iol-2016-individual-p5-sub-a-atomic-a.3": {"method": "answer_trusted_facts", "sample_index": 2, "review_note": "Correct root and suffix meanings without extra claims."}, + "iol-2012-individual-p1-sub-b-atomic-b.1": {"method": "trusted_facts", "sample_index": 5, "review_note": "Complete checked object-subject-verb parse."}, + "iol-2012-individual-p1-sub-b-atomic-b.2": {"method": "answer_trusted_facts", "sample_index": 7, "review_note": "Complete checked object-subject-verb parse."}, + "iol-2012-individual-p1-sub-b-atomic-b.3": {"method": "answer_trusted_facts", "sample_index": 2, "review_note": "Complete checked object-subject-verb parse."}, + "iol-2011-individual-p1-sub-b-atomic-b.1": {"method": "answer_trusted_facts", "sample_index": 2, "review_note": "Exact checked morpheme sequence and surface concatenation."}, + "iol-2011-individual-p1-sub-b-atomic-b.2": {"method": "answer_trusted_facts", "sample_index": 7, "review_note": "Exact checked morpheme sequence; no invented mechanism."}, + "iol-2011-individual-p1-sub-b-atomic-b.3": {"method": "trusted_facts", "sample_index": 3, "review_note": "Exact checked morpheme sequence."}, + "iol-2011-individual-p1-sub-b-atomic-b.4": {"method": "answer_trusted_facts", "sample_index": 4, "review_note": "Exact morpheme sequence and vowel-length rule."}, + "iol-2019-individual-p5-sub-a-atomic-a.1": {"method": "trusted_facts", "sample_index": 3, "review_note": "Correct copular parse and day expression."}, + "iol-2019-individual-p5-sub-a-atomic-a.2": {"method": "trusted_facts", "sample_index": 5, "review_note": "Correct first-person forms, see construction, object, and day."}, + "iol-2019-individual-p5-sub-a-atomic-a.3": {"method": "answer_trusted_facts", "sample_index": 6, "review_note": "Complete checked tense, predicate, object, sandhi, and day parse."}, + "iol-2019-individual-p5-sub-a-atomic-a.4": {"method": "answer_trusted_facts", "sample_index": 0, "review_note": "Exact checked lexical and tense mappings."}, + "iol-2008-individual-p5-sub-b-atomic-b.1": {"method": "answer_trusted_facts", "sample_index": 1, "review_note": "Correct subject and 3rd-subject/2nd-object verb parse."}, + "iol-2008-individual-p5-sub-b-atomic-b.2": {"method": "answer_trusted_facts", "sample_index": 0, "review_note": "Exact checked subject, object, and verb parse."}, + "iol-2008-individual-p5-sub-b-atomic-b.3": {"method": "answer_trusted_facts", "sample_index": 2, "review_note": "Correct possession and consonant-final verb parse."}, + "iol-2008-individual-p5-sub-b-atomic-b.4": {"method": "answer_trusted_facts", "sample_index": 2, "review_note": "Correct indefinite object and second-person verb form."}, + "iol-2008-individual-p5-sub-b-atomic-b.5": {"method": "answer_trusted_facts", "sample_index": 0, "review_note": "Correct possessed subject, indefinite object, and third-person verb."}, + "iol-2019-individual-p5-sub-c-atomic-c.1": {"method": "answer_trusted_facts", "sample_index": 0, "review_note": "Exact checked order and lexical/tense mappings."}, + "iol-2019-individual-p5-sub-c-atomic-c.2": {"method": "answer_trusted_facts", "sample_index": 3, "review_note": "Exact subject-time-verb-object parse."}, + "iol-2019-individual-p5-sub-c-atomic-c.3": {"method": "answer_trusted_facts", "sample_index": 2, "review_note": "Correct future, first-person assimilation, object, and day."}, + "iol-2019-individual-p5-sub-c-atomic-c.4": {"method": "answer_trusted_facts", "sample_index": 2, "review_note": "Exact checked lexical mappings."}, + "iol-2019-individual-p5-sub-c-atomic-c.5": {"method": "manual", "sample_index": null, "review_note": "Sampled exact traces mislabeled person or tone behavior."}, + "iol-2016-individual-p5-sub-b-atomic-b.1": {"method": "answer_trusted_facts", "sample_index": 1, "review_note": "Correct possessive suffix and vowel deletion."}, + "iol-2016-individual-p5-sub-b-atomic-b.2": {"method": "answer_trusted_facts", "sample_index": 5, "review_note": "Correct root, suffixes, and loss of the -ma vowel."}, + "iol-2016-individual-p5-sub-b-atomic-b.3": {"method": "answer_trusted_facts", "sample_index": 4, "review_note": "Correct checked elision chain."}, + "iol-2016-individual-p5-sub-b-atomic-b.4": {"method": "answer_trusted_facts", "sample_index": 3, "review_note": "Correct suffix meanings, lost vowels, and preserved root vowel."}, + "iol-2016-individual-p5-sub-b-atomic-b.5": {"method": "trusted_facts", "sample_index": 2, "review_note": "Correct case-interrogative elision."}, + "iol-2016-individual-p5-sub-b-atomic-b.6": {"method": "answer_trusted_facts", "sample_index": 7, "review_note": "Correct root and interrogative behavior."}, + "iol-2008-individual-p5-sub-a-atomic-a.1": {"method": "trusted_facts", "sample_index": 1, "review_note": "Exact checked subject-object-verb parse."}, + "iol-2008-individual-p5-sub-a-atomic-a.2": {"method": "answer_trusted_facts", "sample_index": 2, "review_note": "Exact checked subject-object-verb parse."}, + "iol-2008-individual-p5-sub-a-atomic-a.3": {"method": "answer_trusted_facts", "sample_index": 6, "review_note": "Correct possessed subject and reflexive parse."}, + "iol-2008-individual-p5-sub-a-atomic-a.4": {"method": "answer_trusted_facts", "sample_index": 3, "review_note": "Correct definite object and person agreement."}, + "iol-2008-individual-p5-sub-a-atomic-a.5": {"method": "answer_trusted_facts", "sample_index": 2, "review_note": "Exact checked root and second-person suffixes."}, + "iol-2008-individual-p5-sub-a-atomic-a.6": {"method": "trusted_facts", "sample_index": 1, "review_note": "Exact checked indefinite-object parse."} + } +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/train_composition_cards_v1.json b/benchmark/IOL/ioling_hf/data/manual_overrides/train_composition_cards_v1.json new file mode 100644 index 0000000000000000000000000000000000000000..42d08bbbb7755d4bc7276f3e2c2fd667648bfd54 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/train_composition_cards_v1.json @@ -0,0 +1,350 @@ +{ + "schema_version": "ioling_train_composition_cards_v1", + "created_at_utc": "2026-07-12", + "selection": "source-balanced from manually checked v14 target facts", + "manual_status": "all_32_selected_cards_read; two Rotuman answer-list leaks replaced with checked generic rules", + "manual_revisions": [ + "iol-2012-individual-p5-sub-d-atomic-d.1", + "iol-2012-individual-p5-sub-d-atomic-d.2" + ], + "source_data": "data/sft/ioling_rule_rich_traces_v3/train.jsonl", + "eligible_records": 77, + "excluded_answer_exposed_records": 46, + "selected_records": 32, + "selected_sources": 14, + "seed": 42, + "records": { + "iol-2008-individual-p5-sub-a-atomic-a.6": { + "record_id": "iol-2008-individual-p5-sub-a-atomic-a.6", + "source_problem_id": "2008-individual-5", + "facts": [ + "Angunahukti-mik is the indefinite object 'a hunter'.", + "aarqi-si-j-utit is 'cure' in the indefinite-object construction with second-person subject." + ], + "full_answer_values_exposed": [] + }, + "iol-2011-individual-p1-sub-b-atomic-b.2": { + "record_id": "iol-2011-individual-p1-sub-b-atomic-b.2", + "source_problem_id": "2011-individual-1", + "facts": [ + "The components are ke- 'we1+2', kaw 'down', -en 'by hand', and transitive -æq 'we1+2'.", + "The first two vowels are short, so the second, a, lengthens to ā." + ], + "full_answer_values_exposed": [] + }, + "iol-2012-individual-p1-sub-b-atomic-b.3": { + "record_id": "iol-2012-individual-p1-sub-b-atomic-b.3", + "source_problem_id": "2012-individual-1", + "facts": [ + "Dyirbal order is object-subject-verb.", + "bayi bargan is 'the wallaby'; baNgul yaóaNgu gubimbuluNunéanaymuNagu is 'the man that is always blaming doctors'; banéan is 'is following'." + ], + "full_answer_values_exposed": [] + }, + "iol-2012-individual-p5-sub-d-atomic-d.1": { + "record_id": "iol-2012-individual-p5-sub-d-atomic-d.1", + "source_problem_id": "2012-individual-5", + "facts": [ + "In fäeag ‘u‘u, the first word is the phrase form of the word meaning 'word'.", + "In a Rotuman two-word phrase the first word changes: final -VCV and -VCu become -VC, final -VCi becomes an umlauted-vowel-plus-consonant form, and final -VCa becomes -VaC.", + "Reverse every phrase-form rule compatible with fäeag; the reverse operation may be ambiguous." + ], + "full_answer_values_exposed": [] + }, + "iol-2016-individual-p5-sub-a-atomic-a.1": { + "record_id": "iol-2016-individual-p5-sub-a-atomic-a.1", + "source_problem_id": "2016-individual-5", + "facts": [ + "uta means 'house', -nha means 'my', -na means 'in', and -txi is interrogative.", + "The suffix vowel-elision rules produce ut-nha-n-txi." + ], + "full_answer_values_exposed": [] + }, + "iol-2017-individual-p2-sub-c-atomic-c.4": { + "record_id": "iol-2017-individual-p2-sub-c-atomic-c.4", + "source_problem_id": "2017-individual-2", + "facts": [ + "A possessor precedes the possessed noun.", + "Possessor prefixes are n- for first-person singular, zero for second-person singular, h- for third-person singular, t- for 'of each of us', d- for one's own, and ri- for second-person plural.", + "Except after ri-, the possessed noun takes a- if it is a body part and e- otherwise.", + "The vocabulary recoverable from the matches includes fe 'pig', lui 'knife', ya 'mother', maama 'father', pong 'face', wei 'ear', and tama 'sea'.", + "My father is n-e-maama, contracted to ne-maama. Father then possesses the body part face, so h-a-pong gives ha-pong." + ], + "full_answer_values_exposed": [] + }, + "iol-2017-individual-p3-sub-a-atomic-a.1": { + "record_id": "iol-2017-individual-p3-sub-a-atomic-a.1", + "source_problem_id": "2017-individual-3", + "facts": [ + "Basic order is subject, verb, optional object, optional place; first-person-singular subjects are expressed by the ŋg- verb prefix.", + "A place phrase may be fronted: X V L is equivalent to L V X. A possessed noun precedes its possessive pronoun.", + "Noun-class concord uses singular mú- or dì- and plural à-, má-, or ʒì-; place expressions use mù-.", + "The last tone of a word assimilates to the first tone of the following word. The sentence-final tone is low in statements and high in questions.", + "múlóʒí is singular 'sorcerer', mwámónà is the concordant past verb 'saw', and ʒìtéténbwá is plural 'stars'. The final high tone marks a question." + ], + "full_answer_values_exposed": [] + }, + "iol-2018-individual-p2-sub-a-atomic-a.2": { + "record_id": "iol-2018-individual-p2-sub-a-atomic-a.2", + "source_problem_id": "2018-individual-2", + "facts": [ + "Order is subject, optional object, predicate, agreement complex, ne. First- and second-person singular transitive subjects take -bə; third-person and plural transitive subjects take kəmə.", + "The person hierarchy is first > second > third. If the subject outranks the object, past uses t-...-ʔ and present uses k-; if the object outranks the subject, past uses tʰ- and present uses r-.", + "The agreement suffix is -ɤ when first-person singular participates, -i when first-person plural participates, otherwise -u for second-person singular and -an for second-person plural.", + "The lexical predicates are ka 'go', ʒip 'sleep', lapkʰi 'see', cʰam 'know', and lan 'beat'.", + "ati is 'he' and nirum is 'us'. Since the first-person object outranks the third-person subject, past agreement uses tʰ- plus first-person-plural -i." + ], + "full_answer_values_exposed": [] + }, + "iol-2018-individual-p3-sub-b-atomic-b.1": { + "record_id": "iol-2018-individual-p3-sub-b-atomic-b.1", + "source_problem_id": "2018-individual-3", + "facts": [ + "For first-person singular, if a word has a voiceless consonant, the first such consonant becomes nasal plus voiced: p→mb, t→nd, h→nz, x→nj, k→ng. Otherwise the whole word is nasalized with final -m.", + "For second-person singular, a word beginning in a vowel other than i, í, or î takes y-. Otherwise the first vowel other than i, í, or î changes: a→e, á→é, â→eâ; o→e, ó→é, ô→eô; û→iû; e→i, é→í, ê→î, including immediately following syllables.", + "In Portuguese loans the second-person-singular change is á→eá, unlike native á→é and â→eâ.", + "The official missing forms preserve all accents and glottal marks shown in the source table.", + "leápina, leátana, and keápana show loanword á→eá. Native pairs such as ngásaxo/késaxo and mbâho/peâho instead show á→é and â→eâ." + ], + "full_answer_values_exposed": [] + }, + "iol-2019-individual-p5-sub-a-atomic-a.2": { + "record_id": "iol-2019-individual-p5-sub-a-atomic-a.2", + "source_problem_id": "2019-individual-5", + "facts": [ + "me is 'I', nú géː marks future today, yɛn ... lé means 'see', kèŋkfǔ is 'yam', and ɛ̀bɛ̀n is 'today'.", + "First-person n- produces the surface forms ŋgéː and nyɛ́n." + ], + "full_answer_values_exposed": [] + }, + "iol-2021-individual-p1-sub-b-atomic-b.4": { + "record_id": "iol-2021-individual-p1-sub-b-atomic-b.4", + "source_problem_id": "2021-individual-1", + "facts": [ + "ena, wija, wido, wi, idibi, benomi, waroewo, and ije are 1, 2, 3, 4, 5, 6, 8, and 9.", + "rati, mepina, joka rati, mepija, rati beo, and moeto are 10, 20, 30, 40, 50, and 60.", + "A unit followed by -ma before a multiple of ten is added to that multiple; ije may alternatively precede the next decade to subtract one.", + "X daemita moeto is 60 + X; moeto D ma X ka (D+1) forms 60D + X.", + "wima mepija is 40 + 4 = 44, and X daemita moeto adds 60, giving 104." + ], + "full_answer_values_exposed": [] + }, + "iol-2022-individual-p1-sub-c-atomic-c.3": { + "record_id": "iol-2022-individual-p1-sub-c-atomic-c.3", + "source_problem_id": "2022-individual-1", + "facts": [ + "Person prefixes identify the direct object, indirect object, and subject in that order around the fixed verb stem tʷ.", + "s-, šʼ-, w-, and ŝʷ- mark first singular, first plural, second singular, and second plural participants; third person uses a-, n-, na-, or zero according to role and number.", + "The vowel is a when the direct object is plural or a second-person-plural participant is present; otherwise it is ə. Schwa separates adjacent consonants.", + "Use šʼ- for first-person-plural direct object and w- for the second-person-singular subject; the third-person-singular indirect object is unmarked." + ], + "full_answer_values_exposed": [] + }, + "iol-2023-individual-p5-sub-b-atomic-b.2": { + "record_id": "iol-2023-individual-p5-sub-b-atomic-b.2", + "source_problem_id": "2023-individual-5", + "facts": [ + "niŋkin, shuunni, taanre, sicyɛɛre, and kaŋkuro are 1, 2, 3, 4, and 5; baa- forms 6-9 from unit words.", + "kɛ is 10, beɲjaaga is 20, ŋkuu is 80, and kampwoo is 400.", + "Before a multiplier, 20, 80, and 400 appear as bee-, ŋkwuu, and kampwɔhii; na adds components.", + "The components are 80, 20, and 9; joining them with na gives 109." + ], + "full_answer_values_exposed": [] + }, + "iol-2024-individual-p1-sub-a-atomic-a.1": { + "record_id": "iol-2024-individual-p1-sub-a-atomic-a.1", + "source_problem_id": "2024-individual-1", + "facts": [ + "Verb order is subject prefix, optional ə, tense prefix, optional ine- for a first-person-singular object, root, optional -la, tense suffix, optional ə, and person/number ending.", + "Subject prefixes are t- first singular, mət- first dual/plural, zero second singular, and ne- third dual/plural; ku- is present, je- future, and past is unmarked.", + "Object endings are -tək second dual/plural, -n third singular, -net third dual, and -new third plural; -la marks first/second plural participation.", + "Schwa breaks prohibited consonant clusters; prefix vowels delete before vowels; t+j becomes cc, t+l becomes ll, t+n becomes nn, and t+ŋ becomes ņŋ; a triggers vowel harmony.", + "The subject is unmarked second-person singular, ku- is present, lle is 'lead', -ŋ marks present, and -n marks a third-person-singular object." + ], + "full_answer_values_exposed": [] + }, + "iol-2008-individual-p5-sub-a-atomic-a.4": { + "record_id": "iol-2008-individual-p5-sub-a-atomic-a.4", + "source_problem_id": "2008-individual-5", + "facts": [ + "Ilinniaqtitsiji is the definite object 'the teacher'.", + "qukiq-t-ait is 'shot' with second-person subject and third-person definite object." + ], + "full_answer_values_exposed": [] + }, + "iol-2011-individual-p1-sub-b-atomic-b.4": { + "record_id": "iol-2011-individual-p1-sub-b-atomic-b.4", + "source_problem_id": "2011-individual-1", + "facts": [ + "Third person has no prefix; ket means 'out', -ohnæ means 'walking', and -w means 'he'.", + "In ketohnæw the first two vowels are short, so o lengthens to ō." + ], + "full_answer_values_exposed": [] + }, + "iol-2012-individual-p1-sub-b-atomic-b.2": { + "record_id": "iol-2012-individual-p1-sub-b-atomic-b.2", + "source_problem_id": "2012-individual-1", + "facts": [ + "Dyirbal order is object-subject-verb.", + "bala diban bilmbalmuNa is 'the stone that is always being pushed'; baNgun biñéiriñéu is 'the lizard'; guniñu is 'is searching for'." + ], + "full_answer_values_exposed": [] + }, + "iol-2012-individual-p5-sub-d-atomic-d.2": { + "record_id": "iol-2012-individual-p5-sub-d-atomic-d.2", + "source_problem_id": "2012-individual-5", + "facts": [ + "In a‘öf fau, the first word is the phrase form of the verb meaning 'to exhaust'.", + "In a Rotuman two-word phrase the first word changes: final -VCV and -VCu become -VC, final -VCi becomes an umlauted-vowel-plus-consonant form, and final -VCa becomes -VaC.", + "Reverse every phrase-form rule compatible with a‘öf; the reverse operation may be ambiguous." + ], + "full_answer_values_exposed": [] + }, + "iol-2016-individual-p5-sub-b-atomic-b.2": { + "record_id": "iol-2016-individual-p5-sub-b-atomic-b.2", + "source_problem_id": "2016-individual-5", + "facts": [ + "chushu means 'corner', -ma means 'your', and -na means 'in'.", + "When following -na removes the vowel of -ma, -ma leaves the root-final u, giving chushu-m-na." + ], + "full_answer_values_exposed": [] + }, + "iol-2017-individual-p2-sub-c-atomic-c.3": { + "record_id": "iol-2017-individual-p2-sub-c-atomic-c.3", + "source_problem_id": "2017-individual-2", + "facts": [ + "A possessor precedes the possessed noun.", + "Possessor prefixes are n- for first-person singular, zero for second-person singular, h- for third-person singular, t- for 'of each of us', d- for one's own, and ri- for second-person plural.", + "Except after ri-, the possessed noun takes a- if it is a body part and e- otherwise.", + "The vocabulary recoverable from the matches includes fe 'pig', lui 'knife', ya 'mother', maama 'father', pong 'face', wei 'ear', and tama 'sea'.", + "A second-person-singular possessor is unmarked, and mother is not a body part, giving e-ya. That mother is a third-person possessor of father, also not a body part, giving he-maama." + ], + "full_answer_values_exposed": [] + }, + "iol-2017-individual-p3-sub-b-atomic-b.1": { + "record_id": "iol-2017-individual-p3-sub-b-atomic-b.1", + "source_problem_id": "2017-individual-3", + "facts": [ + "Basic order is subject, verb, optional object, optional place; first-person-singular subjects are expressed by the ŋg- verb prefix.", + "A place phrase may be fronted: X V L is equivalent to L V X. A possessed noun precedes its possessive pronoun.", + "Noun-class concord uses singular mú- or dì- and plural à-, má-, or ʒì-; place expressions use mù-.", + "The last tone of a word assimilates to the first tone of the following word. The sentence-final tone is low in statements and high in questions.", + "Use ŋg- for the first-person-singular subject with the verb ʃík- 'sing', and put a high tone on the final syllable because the sentence is interrogative." + ], + "full_answer_values_exposed": [] + }, + "iol-2018-individual-p2-sub-a-atomic-a.1": { + "record_id": "iol-2018-individual-p2-sub-a-atomic-a.1", + "source_problem_id": "2018-individual-2", + "facts": [ + "Order is subject, optional object, predicate, agreement complex, ne. First- and second-person singular transitive subjects take -bə; third-person and plural transitive subjects take kəmə.", + "The person hierarchy is first > second > third. If the subject outranks the object, past uses t-...-ʔ and present uses k-; if the object outranks the subject, past uses tʰ- and present uses r-.", + "The agreement suffix is -ɤ when first-person singular participates, -i when first-person plural participates, otherwise -u for second-person singular and -an for second-person plural.", + "The lexical predicates are ka 'go', ʒip 'sleep', lapkʰi 'see', cʰam 'know', and lan 'beat'.", + "nɤ is second-person singular and ʒip is 'sleep'. Present k- plus the second-person-singular suffix -u gives ku." + ], + "full_answer_values_exposed": [] + }, + "iol-2019-individual-p5-sub-a-atomic-a.4": { + "record_id": "iol-2019-individual-p5-sub-a-atomic-a.4", + "source_problem_id": "2019-individual-5", + "facts": [ + "bèsèn is 'we', nú bóy marks future fewer than three days ahead, tɔ́ is 'come', fɔ̀wǎy is 'market', and bvúzhı᷇ːde᷆n is Bvuzhiden." + ], + "full_answer_values_exposed": [] + }, + "iol-2021-individual-p1-sub-b-atomic-b.3": { + "record_id": "iol-2021-individual-p1-sub-b-atomic-b.3", + "source_problem_id": "2021-individual-1", + "facts": [ + "ena, wija, wido, wi, idibi, benomi, waroewo, and ije are 1, 2, 3, 4, 5, 6, 8, and 9.", + "rati, mepina, joka rati, mepija, rati beo, and moeto are 10, 20, 30, 40, 50, and 60.", + "A unit followed by -ma before a multiple of ten is added to that multiple; ije may alternatively precede the next decade to subtract one.", + "X daemita moeto is 60 + X; moeto D ma X ka (D+1) forms 60D + X.", + "benomi is 6; with -ma before mepina 20 it is added, giving 20 + 6 = 26." + ], + "full_answer_values_exposed": [] + }, + "iol-2022-individual-p1-sub-b-atomic-b.2": { + "record_id": "iol-2022-individual-p1-sub-b-atomic-b.2", + "source_problem_id": "2022-individual-1", + "facts": [ + "Person prefixes identify the direct object, indirect object, and subject in that order around the fixed verb stem tʷ.", + "s-, šʼ-, w-, and ŝʷ- mark first singular, first plural, second singular, and second plural participants; third person uses a-, n-, na-, or zero according to role and number.", + "The vowel is a when the direct object is plural or a second-person-plural participant is present; otherwise it is ə. Schwa separates adjacent consonants.", + "s- marks me as direct object, ŝʷ- marks a second-person-plural subject, and the remaining third-person singular participant is the indirect object." + ], + "full_answer_values_exposed": [] + }, + "iol-2023-individual-p5-sub-b-atomic-b.3": { + "record_id": "iol-2023-individual-p5-sub-b-atomic-b.3", + "source_problem_id": "2023-individual-5", + "facts": [ + "niŋkin, shuunni, taanre, sicyɛɛre, and kaŋkuro are 1, 2, 3, 4, and 5; baa- forms 6-9 from unit words.", + "kɛ is 10, beɲjaaga is 20, ŋkuu is 80, and kampwoo is 400.", + "Before a multiplier, 20, 80, and 400 appear as bee-, ŋkwuu, and kampwɔhii; na adds components.", + "This is 80 + (20 × 3) + 10 + 2, which equals 152." + ], + "full_answer_values_exposed": [] + }, + "iol-2024-individual-p1-sub-a-atomic-a.4": { + "record_id": "iol-2024-individual-p1-sub-a-atomic-a.4", + "source_problem_id": "2024-individual-1", + "facts": [ + "Verb order is subject prefix, optional ə, tense prefix, optional ine- for a first-person-singular object, root, optional -la, tense suffix, optional ə, and person/number ending.", + "Subject prefixes are t- first singular, mət- first dual/plural, zero second singular, and ne- third dual/plural; ku- is present, je- future, and past is unmarked.", + "Object endings are -tək second dual/plural, -n third singular, -net third dual, and -new third plural; -la marks first/second plural participation.", + "Schwa breaks prohibited consonant clusters; prefix vowels delete before vowels; t+j becomes cc, t+l becomes ll, t+n becomes nn, and t+ŋ becomes ņŋ; a triggers vowel harmony.", + "t- marks 'I', je- marks future, the harmonized root is 'wait', -la marks plural participation, and -tək marks a second-person-plural object." + ], + "full_answer_values_exposed": [] + }, + "iol-2008-individual-p5-sub-a-atomic-a.2": { + "record_id": "iol-2008-individual-p5-sub-a-atomic-a.2", + "source_problem_id": "2008-individual-5", + "facts": [ + "Nanu-it is 'your polar bear' as subject, inuuhuktu-rmik is indefinite 'a boy', and aanniq-si-j-uq is 'hurt' with third-person subject." + ], + "full_answer_values_exposed": [] + }, + "iol-2011-individual-p1-sub-b-atomic-b.3": { + "record_id": "iol-2011-individual-p1-sub-b-atomic-b.3", + "source_problem_id": "2011-individual-1", + "facts": [ + "Third person has no prefix.", + "The components are taw 'pierce', -ānæhkæ 'digging', and intransitive -w 'he'." + ], + "full_answer_values_exposed": [] + }, + "iol-2012-individual-p1-sub-b-atomic-b.1": { + "record_id": "iol-2012-individual-p1-sub-b-atomic-b.1", + "source_problem_id": "2012-individual-1", + "facts": [ + "Dyirbal order is object-subject-verb.", + "balan ñalNga is 'the girl'; baNgul NumaNgu guniymuNagu is 'the father that is always being searched for'; bambunman is 'is healing'." + ], + "full_answer_values_exposed": [] + }, + "iol-2016-individual-p5-sub-a-atomic-a.2": { + "record_id": "iol-2016-individual-p5-sub-a-atomic-a.2", + "source_problem_id": "2016-individual-5", + "facts": [ + "yapu means 'field', possessive -p”a means 'his', and -psa means 'too'.", + "Possessive -p”a removes the root-final vowel, and -psa removes the vowel of the preceding suffix." + ], + "full_answer_values_exposed": [] + }, + "iol-2017-individual-p3-sub-a-atomic-a.3": { + "record_id": "iol-2017-individual-p3-sub-a-atomic-a.3", + "source_problem_id": "2017-individual-3", + "facts": [ + "Basic order is subject, verb, optional object, optional place; first-person-singular subjects are expressed by the ŋg- verb prefix.", + "A place phrase may be fronted: X V L is equivalent to L V X. A possessed noun precedes its possessive pronoun.", + "Noun-class concord uses singular mú- or dì- and plural à-, má-, or ʒì-; place expressions use mù-.", + "The last tone of a word assimilates to the first tone of the following word. The sentence-final tone is low in statements and high in questions.", + "ŋg- marks a first-person-singular subject and kínà is 'dance'; the final low tone makes the sentence declarative." + ], + "full_answer_values_exposed": [] + } + } +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v10.json b/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v10.json new file mode 100644 index 0000000000000000000000000000000000000000..03aa46a4331f89e4167d2eaf92100c992c434d75 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v10.json @@ -0,0 +1,76 @@ +{ + "schema_version": "ioling_train_expansion_v10", + "reviewed_at_utc": "2026-07-11", + "review_method": "Every prompt, target, answer, and short derivation was transcribed or checked directly against the rendered official English problem and solution pages.", + "sources": [ + { + "source_problem_id": "2011-individual-4", + "year": 2011, + "title": "Nahuatl", + "problem_pdf_page_1_indexed": 3, + "solution_pdf_page_1_indexed": 2, + "problem_body": "Problem #4 (20 points). Given are words in Nahuatl and their English translations in arbitrary order:\n\nacalhuah, achilli, atl, callah, calhuah, chilatl, chilli, colli, coltzintli, conehuah, conehuahcapil, conetl, oquichconetl, oquichhuah, oquichtotoltzintli, tehuah, tetlah, totoltetl\n\nwater, child, master of house, water pepper, revered turkey-cock, mother, village, chili water, grandfather/ancestor, stony ground, boy, possessor of stones, chili, turkey egg, canoe owner, mum(my), wife, revered grandfather/ancestor\n\n(b) Translate into Nahuatl: house, stone, possessor of water, revered man/husband.\n\n(c) Translate into English: cacahuatl, cacahuatetl, cacahuaatl, cacahuahuah.\n\nClassical Nahuatl was the language of the Aztec Empire in Mexico. c = qu = k, ch is as in church, hu = w, and tl and tz are consonants.", + "checked_rules": [ + "In a compound, the left-hand part modifies the right-hand part.", + "A noun ends in -tl or -li unless it has -capil 'diminutive', -huah 'one who has', -tlah/-lah 'place of many', or -tzintli 'revered'.", + "The variants -li and -lah occur after l; otherwise the forms are -tl and -tlah." + ], + "tasks": [ + {"subpart": "b", "id": "b.1", "target": "Translate 'house' into Nahuatl.", "answer": "calli", "reasoning": "The stem cal- takes the ordinary noun ending -li after l, giving calli."}, + {"subpart": "b", "id": "b.2", "target": "Translate 'stone' into Nahuatl.", "answer": "tetl", "reasoning": "The stem te- takes the ordinary noun ending -tl, giving tetl."}, + {"subpart": "b", "id": "b.3", "target": "Translate 'possessor of water' into Nahuatl.", "answer": "ahuah", "reasoning": "The water stem a- combines with -huah 'one who has', producing ahuah."}, + {"subpart": "b", "id": "b.4", "target": "Translate 'revered man/husband' into Nahuatl.", "answer": "oquichtzintli", "reasoning": "The stem oquich- 'man/husband' takes -tzintli 'revered', producing oquichtzintli."}, + {"subpart": "c", "id": "c.1", "target": "Translate cacahuatl into English.", "answer": "cocoa", "reasoning": "The noun ending -tl leaves the stem cacahua-, whose meaning is 'cocoa'."}, + {"subpart": "c", "id": "c.2", "target": "Translate cacahuatetl into English.", "answer": "cocoa bean", "reasoning": "This compound is cacahua- 'cocoa' + te-tl 'stone/seed-like object', conventionally 'cocoa bean'."}, + {"subpart": "c", "id": "c.3", "target": "Translate cacahuaatl into English.", "answer": "cocoa drink", "reasoning": "The compound combines cacahua- 'cocoa' with a-tl 'water', hence 'cocoa drink'."}, + {"subpart": "c", "id": "c.4", "target": "Translate cacahuahuah into English.", "answer": "possessor of cocoa", "reasoning": "The suffix -huah means 'one who has'; with cacahua- it gives 'possessor of cocoa'."} + ] + }, + { + "source_problem_id": "2021-individual-1", + "year": 2021, + "title": "Ekari", + "problem_pdf_page_1_indexed": 1, + "solution_pdf_page_1_indexed": 1, + "problem_body": "Problem 1 (20 points). Here are some numerals in Ekari and their values:\n\nwija — 2\nbenomima rati — 16\nwaroewoma joka rati — 38\nije mepija — 39\nidibima rati beo — 55\nmepina daemita moeto — 80\nenama rati beo daemita moeto — 111\nmoeto wija ma ije ka wido — 129\nmoeto wija ma ije joka rati ka wido — 149\nmoeto idibi ma widoma mepija ka benomi — 343\n\n(a) Write in digits: moeto waroewo; ijema joka rati; moeto wido ma benomi ka wi. One of these numerals has the same value as one above.\n\n(b) Write out in Ekari: 1, 19, 26, 104, 292. One number can be expressed in two ways; give both.", + "checked_rules": [ + "ena, wija, wido, wi, idibi, benomi, waroewo, and ije are 1, 2, 3, 4, 5, 6, 8, and 9.", + "rati, mepina, joka rati, mepija, rati beo, and moeto are 10, 20, 30, 40, 50, and 60.", + "A unit followed by -ma before a multiple of ten is added to that multiple; ije may alternatively precede the next decade to subtract one.", + "X daemita moeto is 60 + X; moeto D ma X ka (D+1) forms 60D + X." + ], + "tasks": [ + {"subpart": "a", "id": "a.1", "target": "Write moeto waroewo in digits.", "answer": "480", "reasoning": "moeto is 60 and waroewo is 8; juxtaposition here multiplies them, so 60 × 8 = 480."}, + {"subpart": "a", "id": "a.2", "target": "Write ijema joka rati in digits.", "answer": "39", "reasoning": "joka rati is 30 and prefixed ijema adds ije = 9, giving 39."}, + {"subpart": "a", "id": "a.3", "target": "Write moeto wido ma benomi ka wi in digits.", "answer": "186", "reasoning": "The frame moeto wido ma ... ka wi represents 60 × 3 plus the inserted benomi = 6, so the value is 186."}, + {"subpart": "b", "id": "b.1", "target": "Write 1 in Ekari.", "answer": "ena", "reasoning": "The checked unit vocabulary gives ena = 1."}, + {"subpart": "b", "id": "b.2", "target": "Write 19 in Ekari, giving both possible forms.", "answer": "ijema rati; ije mepina", "accepted_values": ["ije mepina; ijema rati", "ijema rati = ije mepina", "ije mepina = ijema rati", "ijema rati / ije mepina", "ije mepina / ijema rati"], "reasoning": "One construction adds 9 to 10: ijema rati. The subtractive construction places ije before 20: ije mepina. Both mean 19."}, + {"subpart": "b", "id": "b.3", "target": "Write 26 in Ekari.", "answer": "benomima mepina", "reasoning": "benomi is 6; with -ma before mepina 20 it is added, giving 20 + 6 = 26."}, + {"subpart": "b", "id": "b.4", "target": "Write 104 in Ekari.", "answer": "wima mepija daemita moeto", "reasoning": "wima mepija is 40 + 4 = 44, and X daemita moeto adds 60, giving 104."}, + {"subpart": "b", "id": "b.5", "target": "Write 292 in Ekari.", "answer": "moeto wi ma wijama rati beo ka idibi", "reasoning": "The outer frame gives 60 × 4, while wijama rati beo is 50 + 2; together they give 240 + 52 = 292."} + ] + }, + { + "source_problem_id": "2023-individual-5", + "year": 2023, + "title": "Supyire", + "problem_pdf_page_1_indexed": 6, + "solution_pdf_page_1_indexed": 6, + "problem_body": "Problem 5 (20 points). Here are some numerals in Supyire and their values:\n\nbaashuunni — 7\nbeɲjaaga na niŋkin — 21\nŋkwuu taanre na beeshuunni na kaŋkuro — 285\nkampwoo na ŋkwuu shuunni na beetaanre na baani — 626\nkampwɔhii sicyɛɛre na beɲjaaga na kɛ na baaricyɛɛre — 1639\n\n(a) Write in digits: kampwɔhii shuunni na kɛ; ŋkuu na baataanre.\n\n(b) Write out in Supyire: 15, 109, 152, 403, 1534.\n\nThe words use a simplified transcription. ɛ and ɔ are vowels; ŋ and ɲ are consonants.", + "checked_rules": [ + "niŋkin, shuunni, taanre, sicyɛɛre, and kaŋkuro are 1, 2, 3, 4, and 5; baa- forms 6-9 from unit words.", + "kɛ is 10, beɲjaaga is 20, ŋkuu is 80, and kampwoo is 400.", + "Before a multiplier, 20, 80, and 400 appear as bee-, ŋkwuu, and kampwɔhii; na adds components." + ], + "tasks": [ + {"subpart": "a", "id": "a.1", "target": "Write kampwɔhii shuunni na kɛ in digits.", "answer": "810", "reasoning": "kampwɔhii before shuunni is 400 × 2 = 800, and kɛ is 10; na adds them to give 810."}, + {"subpart": "a", "id": "a.2", "target": "Write ŋkuu na baataanre in digits.", "answer": "88", "reasoning": "ŋkuu is 80 and baataanre is 8; na adds them, giving 88."}, + {"subpart": "b", "id": "b.1", "target": "Write 15 in Supyire.", "answer": "kɛ na kaŋkuro", "reasoning": "kɛ is 10 and kaŋkuro is 5, so additive na gives 15."}, + {"subpart": "b", "id": "b.2", "target": "Write 109 in Supyire.", "answer": "ŋkuu na beɲjaaga na baaricyɛɛre", "reasoning": "The components are 80, 20, and 9; joining them with na gives 109."}, + {"subpart": "b", "id": "b.3", "target": "Write 152 in Supyire.", "answer": "ŋkuu na beetaanre na kɛ na shuunni", "reasoning": "This is 80 + (20 × 3) + 10 + 2, which equals 152."}, + {"subpart": "b", "id": "b.4", "target": "Write 403 in Supyire.", "answer": "kampwoo na taanre", "reasoning": "kampwoo is 400 and taanre is 3; additive na gives 403."}, + {"subpart": "b", "id": "b.5", "target": "Write 1534 in Supyire.", "answer": "kampwɔhii taanre na ŋkwuu sicyɛɛre na kɛ na sicyɛɛre", "reasoning": "The expression is (400 × 3) + (80 × 4) + 10 + 4 = 1534."} + ] + } + ] +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v15.json b/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v15.json new file mode 100644 index 0000000000000000000000000000000000000000..f1fb0651f723a4b09415b047237594a59a69f207 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v15.json @@ -0,0 +1,65 @@ +{ + "schema_version": "ioling_train_expansion_v15", + "reviewed_at_utc": "2026-07-17", + "review_method": "Every prompt example, table cell, requested item, alternative translation, rule, and canonical answer was compared directly with rendered official English problem and solution pages.", + "sources": [ + { + "source_problem_id": "2006-individual-1", + "year": 2006, + "title": "Lakhota", + "problem_pdf_page_1_indexed": 1, + "solution_pdf_page_1_indexed": 1, + "problem_body": "Problem 1 (20 marks). Below you see romanised sentences in the Lakhota language and their English translations:\n\n1. lakhota ki wičhakte — The Indian killed them.\n2. matho ki wakte — I killed the bear.\n3. lakhota ki mačho — The Indian called me.\n4. tuwa ničho he — Who called you?\n5. wičhaša ki tuwa kte — The person killed someone.\n6. tuwa hi he — Who came?\n7. matho ki wičhačho — He called the bears.\n8. yahi čha hi — You came, and he came.\n9. matho ki hipi ną lakhota ki čhopi — The bears came and called the Indian.\n10. yahi čha hokšila ki nikte — You came, and the boy killed you.\n11. lakhota ki wačho ną hokšila ki wakte — I called the Indian and killed the boy.\n12. hokšila ki wakte čha tuwa lakhota ki wičhačho — I killed the boy, and someone called the Indians.\n13. lakhota ki hipi čha mayačho — The Indians came, and you called me.\n\nAssignment 1. Translate into English:\n1. wahi čha lakhota ki matho ki wičhačhopi\n2. wičhaša ki nikte ną mačho\n3. wičhaša ki nikte čha mačho\n4. nikte\n\nAssignment 2. Translate into English in all possible ways:\ntuwa kte he\n\nAssignment 3. Translate into Lakhota:\n1. The Indians killed the boy, and the bear came.\n2. You came and killed the Indian.\n3. Whom did I call?\n4. The people came, and someone killed them.\n\nNote: š, č, h, y, w, ą are specific sounds of Lakhota.", + "checked_rules": [ + "The basic word order is SOV.", + "Nouns are followed by ki, which is an article. Interrogative sentences end in he.", + "Verb subject and object markers are: first-person singular wa- and ma-; second-person singular ya- and ni-; third-person singular zero and zero; third-person plural -pi and wičha-.", + "When both object and subject prefixes occur on the verb, the object prefix precedes the subject prefix.", + "Number is expressed on the verb rather than on the nouns. tuwa means both 'who' and 'someone'.", + "ną coordinates predicates with the same subject; čha coordinates clauses with different subjects." + ], + "tasks": [ + {"subpart":"a","id":"a.1","target":"Translate Assignment 1 item 1, 'wahi čha lakhota ki matho ki wičhačhopi', into English.","answer":"I came, and the Indians called the bears.","accepted_values":["I came and the Indians called the bears."],"reasoning":"wahi is 'I came'. The second clause has lakhota ki as the subject 'the Indians', matho ki as the object 'the bears', and wičhačhopi as the third-person-plural-subject verb 'called'; čha signals different subjects."}, + {"subpart":"a","id":"a.2","target":"Translate Assignment 1 item 2, 'wičhaša ki nikte na mačho', into English.","answer":"The person killed you and called me.","accepted_values":["The person killed you, and the person called me."],"reasoning":"wičhaša ki is 'the person'. The object marker ni- in nikte marks second-person singular, while mačho has the first-person object marker ma-. na joins two predicates with the same subject."}, + {"subpart":"a","id":"a.3","target":"Translate Assignment 1 item 3, 'wičhaša ki nikte čha mačho', into English.","answer":"The person killed you and someone called me.","accepted_values":["The person killed you, and he called me.","The person killed you and he called me."],"reasoning":"The first clause is the same as item 2. čha marks different subjects, so the subject of mačho need not be the person; the language does not force a more specific English choice than 'someone' or 'he'."}, + {"subpart":"a","id":"a.4","target":"Translate Assignment 1 item 4, 'nikte', into English.","answer":"He killed you.","accepted_values":["He killed you?"],"reasoning":"The object marker ni- is second-person singular and the absent subject marker is third-person singular. The sentence has no he, so it is a statement: 'He killed you.'"}, + {"subpart":"b","id":"b.1","target":"Give every possible English translation of Assignment 2, 'tuwa kte he'.","answer":"Who did he kill?; Who killed him?","accepted_values":["Who did he kill? / Who killed him?","Who did he kill?; who killed him?"],"reasoning":"tuwa can be either 'who' as an object or 'who' as a subject. kte has zero third-person-singular subject and zero third-person-singular object marking, and final he makes the sentence interrogative, so both role assignments are possible."}, + {"subpart":"c","id":"c.1","target":"Translate Assignment 3 item 1, 'The Indians killed the boy, and the bear came.', into Lakhota.","answer":"lakhota ki hokšita ki ktepi ną matho ki hi","accepted_values":["lakhota ki hokšita ki ktepi ną matho ki hi."],"reasoning":"Use lakhota ki for 'the Indians', hokšita ki for 'the boy', and ktepi for the third-person-plural-subject verb 'killed'. ną joins predicates with the same subject, and matho ki hi means 'the bear came'."}, + {"subpart":"c","id":"c.2","target":"Translate Assignment 3 item 2, 'You came and killed the Indian.', into Lakhota.","answer":"yahi ną lakhota ki yakte","accepted_values":["yahi ną lakhota ki yakte."],"reasoning":"yahi is 'you came'. ną joins predicates with the same subject; lakhota ki is the object 'the Indian', and ya- is the second-person-singular subject marker in yakte."}, + {"subpart":"c","id":"c.3","target":"Translate Assignment 3 item 3, 'Whom did I call?', into Lakhota.","answer":"tuwa wačho he","accepted_values":["tuwa wačho he."],"reasoning":"tuwa is the interrogative 'whom' in object position, wa- marks first-person-singular subject, and he marks the question."}, + {"subpart":"c","id":"c.4","target":"Translate Assignment 3 item 4, 'The people came, and someone killed them.', into Lakhota.","answer":"wičhaša ki hipi čha tuwa wičhakte","accepted_values":["wičhaša ki hipi čha tuwa wičhakte."],"reasoning":"wičhaša ki hipi means 'the people came'. čha introduces a different subject; tuwa is 'someone', and wičha- marks the third-person-plural object in wičhakte, 'killed them'."} + ] + }, + { + "source_problem_id": "2006-individual-2", + "year": 2006, + "title": "Catalan", + "problem_pdf_page_1_indexed": 2, + "solution_pdf_page_1_indexed": 2, + "problem_body": "Problem 2 (20 marks). The plural of Catalan nouns is usually formed by adding the ending -s. But if the noun ends in one of the letters s, x or ç, more complex rules apply. Here are the singular and plural forms of some Catalan nouns (in simplified spelling) and their English translations. Some forms are missing.\n\nSingular | Plural | Translation\nel apèndix | els apèndixs | appendix\nel bastaix | [missing] | carrier\nel troleibús | [missing] | trolleybus\nel cactus | els cactus | cactus\nla càries | les càries | caries\n[missing] | les clos | meadow\nel contumaç | els contumaços | rebel\nla faç | les façs | face\nel flux | els fluxos | stream\nel gimnàs | els gimnassos | gym\nla hèlix | les hèlixs | screw\nel índex | els índexs | index\nel iris | [missing] | rainbow\nel llaç | [missing] | loop\nel ònix | [missing] | onyx\nel pàncrees | els pàncrees | pancreas\nel pedaç | els pedaços | patch\nla pelvis | [missing] | pelvis\nel permís | els permisos | permission\nel pis | [missing] | flat, lodgings\n[missing] | els sequaços | (male) follower\n[missing] | les sequaçs | (female) follower\nel sufix | els sufixos | suffix\n[missing] | els tastaolletes | frivolous person\nel teix | els teixos | yew\nla trencadís | les trencadís | piece of crockery\nel vas | els vasos | vase\nla xeix | [missing] | the letter x\n\nAssignment 1. Fill the gaps and explain your solution. Assignment 2. The marks ` and ´ indicate the stress in certain Catalan words. Find out when they are used. Assignment 3. Which syllable is stressed in those words where there is no ` or ´ mark?\n\nCatalan is a Romance language spoken by approximately 8 million people, mostly in Spain, but also in France and Andorra.", + "checked_rules": [ + "The singular articles are el for masculine nouns and la for feminine nouns; their plurals are els and les.", + "The stress mark ` or ´ is used when stress falls on a non-default syllable.", + "For words ending in -s, the default stress is on the last syllable or the third syllable from the end; the examples show the relevant plural forms and their accent marks.", + "Feminine nouns take plural -s, with zero addition after final s. Masculine nouns take plural -os when stressed on the final or only syllable and plural -s, with zero addition after final s, otherwise.", + "The two follower nouns have the same stem sequaç and differ only in their singular articles." + ], + "tasks": [ + {"subpart":"a","id":"a.1","target":"Fill the missing plural for el bastaix 'carrier'.","answer":"els bastaixos","accepted_values":["els bastaixos."],"reasoning":"bastaix is masculine and stressed on its final syllable, so its plural takes -os: el bastaix becomes els bastaixos."}, + {"subpart":"a","id":"a.2","target":"Fill the missing plural for el troleibús 'trolleybus'.","answer":"els troleibusos","accepted_values":["els troleibusos."],"reasoning":"troleibús is masculine and stressed on its final syllable, so it takes plural -os."}, + {"subpart":"a","id":"a.3","target":"Fill the missing plural for the meadow noun whose plural is les clos.","answer":"la clos","accepted_values":["la clos."],"reasoning":"The plural article les identifies the feminine noun, and the shared stem is clos. The singular is therefore la clos."}, + {"subpart":"a","id":"a.4","target":"Fill the missing plural for el iris 'rainbow'.","answer":"els iris","accepted_values":["els iris."],"reasoning":"iris ends in s, so no additional s is written. Its masculine plural article is els, giving els iris."}, + {"subpart":"a","id":"a.5","target":"Fill the missing plural for el llaç 'loop'.","answer":"els llaços","accepted_values":["els llaços."],"reasoning":"The masculine noun ends in ç and is not one of the final-stressed exceptions, so the plural is formed with -os: llaç becomes llaços."}, + {"subpart":"a","id":"a.6","target":"Fill the missing plural for el ònix 'onyx'.","answer":"els ònixs","accepted_values":["els ònixs."],"reasoning":"ònix ends in x and is masculine but not final-stressed, so it takes plural -s: els ònixs."}, + {"subpart":"a","id":"a.7","target":"Fill the missing plural for la pelvis 'pelvis'.","answer":"les pelvis","accepted_values":["les pelvis."],"reasoning":"pelvis ends in s, and feminine nouns use zero addition after final s. The plural is les pelvis."}, + {"subpart":"a","id":"a.8","target":"Fill the missing plural for el pis 'flat, lodgings'.","answer":"els pisos","accepted_values":["els pisos."],"reasoning":"pis is masculine and ends in s. Masculine nouns with this ending take -os in the shown final-stressed class, giving els pisos."}, + {"subpart":"a","id":"a.9","target":"Fill the missing singular masculine article and noun for the (male) follower whose plural is els sequaços.","answer":"el sequaç","accepted_values":["el sequaç."],"reasoning":"The solution says the male and female follower share the stem sequaç and differ only in their singular articles. The masculine singular is el sequaç."}, + {"subpart":"a","id":"a.10","target":"Fill the missing singular feminine article and noun for the (female) follower whose plural is les sequaçs.","answer":"la sequaç","accepted_values":["la sequaç."],"reasoning":"The same stem sequaç is used with the feminine singular article la. Its plural is the supplied les sequaçs."}, + {"subpart":"a","id":"a.11","target":"Fill the missing singular for els tastaolletes 'frivolous person'.","answer":"el tastaolletes","accepted_values":["el tastaolletes."],"reasoning":"The plural article els identifies a masculine noun, and the plural already ends in s with no additional ending. The singular is el tastaolletes."}, + {"subpart":"a","id":"a.12","target":"Fill the missing plural for la xeix 'the letter x'.","answer":"les xeixs","accepted_values":["les xeixs."],"reasoning":"xeix ends in x and is feminine, so the plural takes -s: les xeixs."}, + {"subpart":"b","id":"b.1","target":"State when the Catalan marks ` and ´ are used.","answer":"They are used when stress falls on a non-default syllable.","accepted_values":["The marks are used when stress falls on a non-default syllable.","When the stress falls on a non-default syllable."],"reasoning":"The marked examples show that the accent is written when the word's stress does not follow the default pattern."}, + {"subpart":"c","id":"c.1","target":"State the default stress rule for Catalan words with no ` or ´ mark.","answer":"Stress is penultimate if the word ends in s; otherwise stress is final.","accepted_values":["If the word ends in s, the stress is penultimate; otherwise it is final.","Penultimate when ending in s, final otherwise."],"reasoning":"The official solution states that an unmarked word ending in s has penultimate stress, while an unmarked word with another ending has final stress."} + ] + } + ] +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v15_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v15_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..2a5a5ebb73902d60018762ec369c7df12530fea9 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v15_audit.json @@ -0,0 +1,79 @@ +{ + "schema_version": "ioling_train_expansion_v15_audit", + "reviewed_at_utc": "2026-07-17", + "ledger": "data/manual_overrides/train_expansion_v15.json", + "official_problem_pdfs": [ + "data/raw/pdfs/iol-2006-indiv-prob.en.pdf", + "data/raw/pdfs/iol-2006-indiv-sol.en.pdf" + ], + "manual_method": "Rendered pages 1 and 2 of both official PDFs and compared every listed example, table entry, target, rule, and solution line. The Lakhota Assignment 3 translations were rechecked against the solution text after an initial transcription discrepancy.", + "source_checks": { + "2006-individual-1": { + "problem_page": 1, + "solution_page": 1, + "task_count": 9, + "task_ids": ["a.1", "a.2", "a.3", "a.4", "b.1", "c.1", "c.2", "c.3", "c.4"], + "manual_corrections_after_second_read": [ + "Assignment 3 item 1 is lakhota ki hokšita ki ktepi ną matho ki hi, matching the official solution; an earlier draft incorrectly used hokšila, kteni, and čha.", + "Assignment 3 item 2 uses ną, not plain na." + ], + "answer_alternatives_preserved": [ + "Assignment 1 item 3 keeps the official ambiguity between 'he' and an unspecified different subject.", + "Assignment 2 keeps both role assignments: 'Whom did he kill?' and 'Who killed him?'." + ], + "status": "approved_for_training" + }, + "2006-individual-2": { + "problem_page": 2, + "solution_page": 2, + "task_count": 14, + "task_ids": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12", "b.1", "c.1"], + "table_check": "The missing singular/plural cells were transcribed from the rendered table and cross-checked against the completed solution table, including the two sequaç rows where gender is expressed only by the singular article.", + "status": "approved_for_training" + } + }, + "dataset_checks": { + "new_tasks": 23, + "new_sources": 2, + "combined_train_tasks": 146, + "combined_train_sources": 17, + "validation_sources": 3, + "source_overlap": [], + "production_exact_completion_count": 23, + "production_exact_completion_denominator": 23, + "prompt_contains_privileged_answer": false, + "scorer": "normalized_keyed_answer_v2", + "unicode_normalization": "NFKC" + }, + "matched_model_experiment": { + "base": "checkpoints/qwen3-4b-ioling-microsteps-balanced-v2-e5-merged", + "adapter": "checkpoints/qwen3-4b-ioling-microsteps-v15-breadth-e1-lr5e7", + "merged": "checkpoints/qwen3-4b-ioling-microsteps-v15-breadth-e1-lr5e7-merged", + "epochs": 1, + "learning_rate": 5e-7, + "effective_batch_size": 16, + "max_length": 4096, + "wandb_sft": "https://wandb.ai/alexgurung/ioling-research/runs/e11wkjgo", + "microstep_eval": { + "report": "reports/microsteps/qwen3_4b_microsteps_v15_breadth_e1_validation_pass8.json", + "wandb": "https://wandb.ai/alexgurung/ioling-research/runs/9tnqnua6", + "samples": 320, + "correct_samples": 50, + "pass_at_8_tasks": 14, + "manual_positive_review": "All 50 scorer-positive JSON answers were read; all were genuine positives and no false positive was found.", + "matched_baseline": "47/320 samples and 14/40 tasks; the new run gained three samples on already-passed tasks and no new task." + }, + "raw_eval": { + "report": "reports/verified_breadth_v15_v14_val_pass8.json", + "wandb": "https://wandb.ai/alexgurung/ioling-research/runs/x7ty6bks", + "records": 24, + "samples": 192, + "exact_samples": 0, + "pass_at_8_records": 0, + "format_rate": 0.9635416666666666, + "truncation_rate": 0.010416666666666666, + "manual_final_box_review": "All 192 final-answer fields were inspected. No accepted-answer alternate-format false negative was found; the model produced no exact answer." + }, + "decision": "Keep the manually corrected v15 data and the matched experiment artifacts, but retain the balanced microstep checkpoint as the current model because pass@8 coverage did not improve. Expand source coverage before another SFT or RL update." + } +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v16.json b/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v16.json new file mode 100644 index 0000000000000000000000000000000000000000..d45df3e76af9222d7b81174148cf242965e1717c --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v16.json @@ -0,0 +1,105 @@ +{ + "schema_version": "ioling_train_expansion_v16", + "reviewed_at_utc": "2026-07-17", + "review_method": "Rendered the official English problem and solution pages at high resolution, compared every Micmac example and every requested item with the page images and layout-preserving PDF text, and retained explicit aliases for the PDF text-layer encoding of the IPA symbols.", + "sources": [ + { + "source_problem_id": "2008-individual-1", + "year": 2008, + "title": "Micmac", + "problem_pdf_page_1_indexed": 1, + "solution_pdf_page_1_indexed": 1, + "problem_body": "Problem 1 (20 points). The following are words of the Micmac language written in the so-called Listuguj orthography, their phonetic transcriptions and English translations:\n\n1. tmi’gn — [dəmīgən] — axe\n2. an’stawteg — [anəstawtek] — unsafe\n3. gjiansale’wit — [əkciansalēwit] — archangel\n4. mgumie’jo’tlatl — [əmkumējōdəladəl] — to shoe (a horse)\n5. amqwanji’j — [amxw ancīc] — spoon\n6. e’jnt — [ējənt] — Indian agent\n7. tplutaqan — [ətpəludaGan] — law\n8. ge’gwising — [gēgw isink] — to lie on the top\n9. lnu’sgw — [lə nūskw] — Indian woman\n10. g’p’ta’q — [gəbədāx] — above, overhead\n11. epsaqtejg — [epsaxteck] — stove\n\n(a) Transcribe the following words:\n12. gsnqo’qon — foolishness\n13. tg’poq — spring water\n14. gmu’jmin — raspberry\n15. emtoqwatg — to worship\n16. te’plj — goat\n\n(b) Write in the Listuguj orthography:\n17. [ətpədēsən] — south\n18. [ə mteskəm] — snake\n19. [alaptək] — to look around\n20. [gəlamen] — so, therefore\n\nIn this record, Unicode ə represents the schwa glyph printed in the official PDF. The source notation uses G for the voiced counterpart of x and uses w after a consonant to mark lip rounding. The source’s [w] notation is shown without inserting a new phoneme. In the transcription, [c] is ch in church, [j] is j in judge, [x] is ch in Scottish loch, and a macron marks vowel length. The letter w stands for rounding after a consonant and for the sound [w] otherwise. The apostrophe indicates length after a vowel and is read as ə after a consonant. Schwa is pronounced but not written between a consonant and a following sonorant [l, m, n], and before an initial consonant cluster. The spelling consonants p, t, j, g, gw, q, qw are voiced at the beginning of a word or between vowels and voiceless at the end of a word or next to another consonant.", + "checked_rules": [ + "The apostrophe indicates vowel length when it follows a vowel and is pronounced as schwa when it follows a consonant.", + "The letter w marks lip rounding after a consonant and represents [w] otherwise.", + "Schwa is pronounced but not written between any consonant and a following sonorant consonant [l, m, n].", + "Schwa is also pronounced before a consonant cluster at the beginning of a word.", + "The spelling sequences p, t, j, g, gw, q, qw are voiced at the beginning of a word or between vowels and voiceless at the end of a word or next to another consonant." + ], + "tasks": [ + { + "subpart": "a", + "id": "a.1", + "target": "Transcribe item 12, gsnqo’qon ‘foolishness’, in the phonetic notation used in the problem.", + "answer": "[əksənxōGon]", + "accepted_values": ["[@ks@nxōGon]", "[əksənxōGon]"], + "reasoning": "The initial consonant cluster receives a pronounced schwa. The initial g is voiceless next to s, and a schwa is inserted between s and n. The q next to n is x, the apostrophe lengthens o, and the following q between vowels is voiced as G.", + "source_text_layer_answer": "[@ks@nxōGon]" + }, + { + "subpart": "a", + "id": "a.2", + "target": "Transcribe item 13, tg’poq ‘spring water’, in the phonetic notation used in the problem.", + "answer": "[ətkəbōx]", + "accepted_values": ["[@tk@box]", "[ətkəbōx]"], + "reasoning": "The initial cluster receives schwa. t and g are next to another consonant, so they are voiceless; the apostrophe after g is schwa. p is voiced between the resulting vowels, and final q is x.", + "source_text_layer_answer": "[@tk@box]" + }, + { + "subpart": "a", + "id": "a.3", + "target": "Transcribe item 14, gmu’jmin ‘raspberry’, in the phonetic notation used in the problem.", + "answer": "[gəmūjəmin]", + "accepted_values": ["[g@mūj@min]", "[gəmūjəmin]"], + "reasoning": "The initial g is voiced at the beginning of the word, and schwa is pronounced before the initial cluster gm. The apostrophe lengthens u. A schwa is inserted between j and the following sonorant m, so j is between vowels and remains voiced.", + "source_text_layer_answer": "[g@mūj@min]" + }, + { + "subpart": "a", + "id": "a.4", + "target": "Transcribe item 15, emtoqwatg ‘to worship’, in the phonetic notation used in the problem.", + "answer": "[emtoGwatk]", + "accepted_values": ["[emtoGw atk]", "[emtoɣʷatk]", "[emtoGwatk]"], + "reasoning": "The t next to m is voiceless. The q in qw is between vowels and is voiced as G, while w marks rounding. The final t and g are next to one another, so t is voiceless and final g is realized as k.", + "source_text_layer_answer": "[emtoGw atk]" + }, + { + "subpart": "a", + "id": "a.5", + "target": "Transcribe item 16, te’plj ‘goat’, in the phonetic notation used in the problem.", + "answer": "[dēbəlc]", + "accepted_values": ["[dēb@lc]", "[dēbəlc]"], + "reasoning": "Initial t is voiced, the apostrophe lengthens e, and p is voiced because the inserted schwa after p makes it occur between vowels. Schwa is inserted before l, and final j is voiceless c.", + "source_text_layer_answer": "[dēb@lc]" + }, + { + "subpart": "b", + "id": "b.1", + "target": "Write item 17, [ətpədēsən] ‘south’, in Listuguj orthography.", + "answer": "tp’te’sn", + "accepted_values": ["tp’te’sn", "tp'te'sn"], + "reasoning": "The initial schwa is not written, the first cluster is tp, the long vowel ē is written with an apostrophe after e, and the schwa between d and s is also represented by an apostrophe after t in the orthography. The final schwa before n is not written.", + "source_text_layer_answer": "tp’te’sn" + }, + { + "subpart": "b", + "id": "b.2", + "target": "Write item 18, [ə mteskəm] ‘snake’, in Listuguj orthography.", + "answer": "mtesgm", + "accepted_values": ["mtesgm"], + "reasoning": "The initial schwa and the schwa between the consonants are not written. The phonetic final schwa is represented by the orthographic m in the source answer, giving mtesgm.", + "source_text_layer_answer": "mtesgm" + }, + { + "subpart": "b", + "id": "b.3", + "target": "Write item 19, [alaptək] ‘to look around’, in Listuguj orthography.", + "answer": "alapt’g", + "accepted_values": ["alapt’g", "alapt'g"], + "reasoning": "The phonetic schwa before k is represented by an apostrophe after the preceding t, and the final k corresponds to orthographic g in this environment. The other vowels are not written with extra marks.", + "source_text_layer_answer": "alapt’g" + }, + { + "subpart": "b", + "id": "b.4", + "target": "Write item 20, [gəlamen] ‘so, therefore’, in Listuguj orthography.", + "answer": "glamen", + "accepted_values": ["glamen"], + "reasoning": "The schwa after the initial g is not written, leaving the consonant sequence g-l-a-m-e-n in Listuguj orthography.", + "source_text_layer_answer": "glamen" + } + ] + } + ] +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v16_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v16_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..3466be42ff74687f1c5c5bd4282ae1d93053d6ca --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v16_audit.json @@ -0,0 +1,83 @@ +{ + "schema_version": "ioling_train_expansion_v16_audit", + "reviewed_at_utc": "2026-07-17", + "ledger": "data/manual_overrides/train_expansion_v16.json", + "official_problem_pdfs": [ + "data/raw/pdfs/iol-2008-indiv-prob.en.pdf", + "data/raw/pdfs/iol-2008-indiv-sol.en.pdf" + ], + "rendered_review": { + "problem_pages": [1], + "solution_pages": [1], + "render_command": "pdftoppm -r 600 -png", + "manual_checks": [ + "All 11 supplied Micmac examples were compared with the rendered table.", + "All five phonetic transcription targets and all four orthography targets were compared with the rendered target table and official solution.", + "The official solution's emtoGwatk line was checked visually; the dataset retains both a readable Unicode alias and the PDF text-layer spacing variant.", + "The official PDF's schwa glyph is represented as Unicode ə in the readable prompt, with the extracted @ form retained as an explicit answer alias." + ] + }, + "source_checks": { + "2008-individual-1": { + "title": "Micmac", + "task_count": 9, + "task_ids": ["a.1", "a.2", "a.3", "a.4", "a.5", "b.1", "b.2", "b.3", "b.4"], + "status": "approved_for_training" + } + }, + "dataset_checks": { + "new_tasks": 9, + "new_sources": 1, + "combined_train_tasks": 155, + "combined_train_sources": 18, + "validation_sources": 3, + "source_overlap": [], + "production_exact_completion_count": 9, + "production_exact_completion_denominator": 9, + "prompt_contains_privileged_answer": false, + "scorer": "normalized_keyed_answer_v2", + "unicode_normalization": "NFKC" + }, + "matched_model_experiment": { + "base": "checkpoints/qwen3-4b-ioling-microsteps-balanced-v2-e5-merged", + "adapter": "checkpoints/qwen3-4b-ioling-microsteps-v16-breadth-e1-lr5e7", + "merged": "checkpoints/qwen3-4b-ioling-microsteps-v16-breadth-e1-lr5e7-merged", + "epochs": 1, + "learning_rate": 5e-7, + "effective_batch_size": 16, + "max_length": 4096, + "wandb_sft": "https://wandb.ai/alexgurung/ioling-research/runs/u8je387u", + "microstep_eval": { + "report": "reports/microsteps/qwen3_4b_microsteps_v16_breadth_e1_validation_pass8.json", + "wandb": "https://wandb.ai/alexgurung/ioling-research/runs/otzhb4ai", + "samples": 320, + "correct_samples": 47, + "pass_at_8_tasks": 13, + "manual_positive_review": "All 47 scorer-positive JSON answers were read; all were genuine positives and no false positive was found.", + "matched_baseline": "v15 produced 50/320 exact samples and 14/40 passed tasks. v16 lost the prior Arammba-36 task and solved no new task." + }, + "raw_eval": { + "report": "reports/verified_breadth_v16_v14_val_pass8.json", + "wandb": "https://wandb.ai/alexgurung/ioling-research/runs/5j3ybbqa", + "records": 24, + "samples": 192, + "exact_samples": 0, + "pass_at_8_records": 0, + "format_rate": 0.9791666666666666, + "truncation_rate": 0.010416666666666666, + "manual_final_box_review": "All 192 final-answer fields were inspected. No accepted-answer alternate-format false negative was found; the model produced no exact answer." + }, + "source_seen_micmac_probe": { + "report": "reports/verified_breadth_v16_micmac_train_pass8.json", + "wandb": "https://wandb.ai/alexgurung/ioling-research/runs/q76gayc0", + "records": 9, + "samples": 72, + "exact_samples": 2, + "pass_at_8_records": 2, + "format_rate": 0.9861111111111112, + "truncation_rate": 0.013888888888888888, + "manual_exact_review": "Both exact final answers were read. The b.3 trace reached alapt’g but included unsupported invented rules; the b.4 trace reached glamen after a 4.9k-token loop containing repeated contradictory analyses. Neither is approved as a reasoning trace." + }, + "decision": "Publish the manually checked v16 data and retain the run for comparison, but do not select the v16 checkpoint: matched microstep coverage regressed and raw held-out accuracy remained zero." + } +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v17.json b/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v17.json new file mode 100644 index 0000000000000000000000000000000000000000..df307c5918238e246cf23c4c228542db38efa65e --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v17.json @@ -0,0 +1,35 @@ +{ + "schema_version": "ioling_train_expansion_v17", + "reviewed_at_utc": "2026-07-17", + "review_method": "Rendered the official English problem and solution pages at high resolution, compared every Creek example and every requested word with the page images and layout-preserving PDF text, and manually separated phonemic stress marks from the solution's visual structural dots and syllable separators.", + "sources": [ + { + "source_problem_id": "2018-individual-1", + "year": 2018, + "title": "Creek", + "problem_pdf_page_1_indexed": 1, + "solution_pdf_page_1_indexed": 1, + "problem_body": "Problem 1 (20 points). Here are some words in Creek and their English translations. The mark [ˊ] indicates stress:\n\n[cokó] house\n[cáːlo] trout\n[sókca] sack\n[waːkocí] calf\n[pocóswa] axe\n[famíːca] muskmelon\n[yanása] bison // buffalo\n[iyanawá] his/her cheek\n[hîːspákwa] robin\n[aklowahíː] mud\n[imahicíta] to look out for\n[inkosapitá] to implore\n[tapassóːla] daddy longlegs\n[akkopánka] playing\n[cokpilâːpilá] whippoorwill\n[toknaːphotí] wallet\n[coːkakiɬɬitá] learning\n[ɬafotaháya] pumpkin // winter squash\n[itiwanayipíta] to tie each other\n[ipahankatíta] to count us\n[pokkoɬakkoakkopankacóko] basketball gym\n\nMark the stress:\n[ifa] dog\n[nâːnaki] things\n[aktopa] bridge\n[wanayita] to tie\n[isiskitoci] little drinking vessel\n[honantaːki] men\n[ifoci] puppy\n[sâːsakwa] goose\n[hoktaki] women\n[awanayita] to tie to\n[aːtamihoma] bonnet (car hood)\n[ilitohtaɬita] to cross legs\n\nCreek (Muskogee) belongs to the Muskogean family. The consonant ɬ is a consonant. The mark ˆ indicates falling tone and the mark ː indicates that the preceding vowel is long. In this record the acute accent on a vowel is the requested stress mark. The official solution also prints periods between syllables and repeated visual dots for the abstract word structure; those dots and periods are not additional Creek sounds.", + "checked_rules": [ + "The official solution represents a word as zero or more repetitions of a structural three-row pattern followed by a stressed structural column.", + "The open circle in the solution is a syllable of the form (C)V, while the filled circle is one of the forms (C)VC, (C)V:C, or (C)V:C’ shown in the official diagram.", + "The structural dots in the official solution are visual slots, not phonemes and not characters that need to be inserted into the Creek word.", + "The acute accent marks the stressed vowel. The circumflex marks falling tone and the length mark ː belongs to the preceding vowel." + ], + "tasks": [ + {"subpart":"a","id":"a.1","target":"Mark stress in [ifa] ‘dog’.","answer":"[ifá]","accepted_values":["ifá","[ifá]"],"reasoning":"The official solution gives [ifá]. The final vowel is the stressed vowel; the brackets are the source's phonetic notation."}, + {"subpart":"a","id":"a.2","target":"Mark stress in [nâːnaki] ‘things’.","answer":"[nâːnakí]","accepted_values":["nâːnakí","[nâː . . nakí]","[nâːnakí]"],"reasoning":"The official solution displays [nâː . . nakí]. Removing only its non-phonemic structural dots gives the original word [nâːnaki] with stress on the final i: [nâːnakí]."}, + {"subpart":"a","id":"a.3","target":"Mark stress in [aktopa] ‘bridge’.","answer":"[aktopá]","accepted_values":["aktopá","[ak . . topá]","[aktopá]"],"reasoning":"The solution display is [ak . . topá]. Its dots are structural separators, so the source word is [aktopa] with stress on the final a: [aktopá]."}, + {"subpart":"a","id":"a.4","target":"Mark stress in [wanayita] ‘to tie’.","answer":"[wanayitá]","accepted_values":["wanayitá","[wana.yitá]","[wanayitá]"],"reasoning":"The official solution displays [wana.yitá], which is the same word with a presentation period between syllables and stress on the final a. The readable answer is [wanayitá]."}, + {"subpart":"a","id":"a.5","target":"Mark stress in [isiskitoci] ‘little drinking vessel’.","answer":"[isiskitóci]","accepted_values":["isiskitóci","[isis . . kitó.ci]","[isiskitóci]"],"reasoning":"The official solution displays [isis . . kitó.ci]. The acute is on o in the penultimate syllable; the dots and period are structural or syllable separators, not extra letters."}, + {"subpart":"a","id":"a.6","target":"Mark stress in [honantaːki] ‘men’.","answer":"[honantáːki]","accepted_values":["honantáːki","[honan.táː.ki]","[honantáːki]"],"reasoning":"The official solution displays [honan.táː.ki], with stress on the long a in taː. Keeping the source word and its length mark gives [honantáːki]."}, + {"subpart":"a","id":"a.7","target":"Mark stress in [ifoci] ‘puppy’.","answer":"[ifóci]","accepted_values":["ifóci","[ifó.ci]","[ifóci]"],"reasoning":"The solution display [ifó.ci] places stress on o. The period only separates syllables, so the answer without presentation punctuation is [ifóci]."}, + {"subpart":"a","id":"a.8","target":"Mark stress in [sâːsakwa] ‘goose’.","answer":"[sâːsákwa]","accepted_values":["sâːsákwa","[sâː . . . . . . sák.wa]","[sâːsákwa]"],"reasoning":"The official solution displays [sâː . . . . . . sák.wa], with stress on the long a in the second syllable sák. The source's falling tone and length on the first vowel remain unchanged."}, + {"subpart":"a","id":"a.9","target":"Mark stress in [hoktaki] ‘women’.","answer":"[hoktakí]","accepted_values":["hoktakí","[hok . . . . takí]","[hoktakí]"],"reasoning":"The official solution displays [hok . . . . takí], with stress on the final i. Removing the structural dots gives [hoktakí]."}, + {"subpart":"a","id":"a.10","target":"Mark stress in [awanayita] ‘to tie to’.","answer":"[awanayíta]","accepted_values":["awanayíta","[awa . . . . nayí.ta]","[awanayíta]"],"reasoning":"The solution display [awa . . . . nayí.ta] places stress on the i in the penultimate syllable. The readable source-word answer is [awanayíta]."}, + {"subpart":"a","id":"a.11","target":"Mark stress in [aːtamihoma] ‘bonnet (car hood)’.","answer":"[aːtamihomá]","accepted_values":["aːtamihomá","[aː.tami.homá]","[aːtamihomá]"],"reasoning":"The official solution displays [aː.tami.homá], with stress on the final a. The first vowel's length mark remains on aː."}, + {"subpart":"a","id":"a.12","target":"Mark stress in [ilitohtaɬita] ‘to cross legs’.","answer":"[ilitohtaɬíta]","accepted_values":["ilitohtaɬíta","[ili . toh . taɬí.ta]","[ilitohtaɬíta]"],"reasoning":"The solution display [ili . toh . taɬí.ta] places stress on i in the syllable taɬi, before the final a. The consonant ɬ is preserved, yielding [ilitohtaɬíta]."} + ] + } + ] +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v17_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v17_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..c44e772754d3bfef879972632fb705d97cecfcb8 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/train_expansion_v17_audit.json @@ -0,0 +1,41 @@ +{ + "schema_version": "ioling_train_expansion_v17_audit", + "reviewed_at_utc": "2026-07-17", + "ledger": "data/manual_overrides/train_expansion_v17.json", + "official_problem_pdfs": [ + "data/raw/pdfs/iol-2018-indiv-prob.en.pdf", + "data/raw/pdfs/iol-2018-indiv-sol.en.pdf" + ], + "rendered_review": { + "problem_pages": [1], + "solution_pages": [1], + "render_command": "pdftoppm -r 600 -png", + "manual_checks": [ + "All 21 supplied Creek examples were compared with the rendered problem page.", + "All 12 target words were compared with the rendered target list and the bold stress positions in the rendered official solution.", + "The official solution's circle and dot diagram was checked to distinguish structural slots from phonemic segments.", + "The official solution's printed syllable periods and repeated structural dots are retained only as explicit aliases; the canonical answer preserves the original word and adds stress." + ] + }, + "source_checks": { + "2018-individual-1": { + "title": "Creek", + "task_count": 12, + "task_ids": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12"], + "status": "approved_for_training" + } + }, + "dataset_checks": { + "new_tasks": 12, + "new_sources": 1, + "combined_train_tasks": 167, + "combined_train_sources": 19, + "validation_sources": 3, + "source_overlap": [], + "production_exact_completion_count": 12, + "production_exact_completion_denominator": 12, + "prompt_contains_privileged_answer": false, + "scorer": "normalized_keyed_answer_v2", + "unicode_normalization": "NFKC" + } +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/train_microsteps_v1.json b/benchmark/IOL/ioling_hf/data/manual_overrides/train_microsteps_v1.json new file mode 100644 index 0000000000000000000000000000000000000000..2ac6c5d9743047ad41d0872ffb279b7b1dc45bc0 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/train_microsteps_v1.json @@ -0,0 +1,138 @@ +{ + "schema_version": "ioling_train_microsteps_v1", + "reviewed_at_utc": "2026-07-12", + "review_method": "Each task was manually written from the rendered-official-page rule cards and checked target facts already approved for v14.", + "rule_card_source": "data/sft/ioling_rule_rich_traces_v3/train.jsonl", + "sources": { + "2008-individual-5": [ + {"id": "inuktitut-definite-order", "type": "word_order", "question": "What is the order of subject, definite object, and verb in a definite transitive clause?", "answer": "subject-up, object-(q), verb"}, + {"id": "inuktitut-indefinite-object", "type": "morpheme_mapping", "question": "Which noun suffix marks an indefinite object?", "answer": "-(r)mik"}, + {"id": "inuktitut-indefinite-verb", "type": "morpheme_mapping", "question": "Which verb element accompanies an indefinite object?", "answer": "-si"}, + {"id": "inuktitut-linker-vowel", "type": "allomorph_rule", "question": "Which linker precedes a person ending after a vowel-final verb?", "answer": "-j"}, + {"id": "inuktitut-linker-consonant", "type": "allomorph_rule", "question": "Which linker precedes a person ending after a consonant-final verb?", "answer": "-t"}, + {"id": "inuktitut-third-to-second", "type": "morpheme_mapping", "question": "Which ending marks a third-person subject acting on a second-person object?", "answer": "-aatit"}, + {"id": "inuktitut-your-noun", "type": "transformation_rule", "question": "How is 'your' marked on a subject or object noun ending in -(q)?", "answer": "replace -(q) with -it"} + ], + "2011-individual-1": [ + {"id": "menominee-order", "type": "morpheme_order", "question": "What is the order of components in a Menominee verb?", "answer": "person prefix, lexical element, verb element, person ending"}, + {"id": "menominee-first-prefix", "type": "morpheme_mapping", "question": "Which prefix marks first-person singular?", "answer": "ne-"}, + {"id": "menominee-inclusive-prefix", "type": "morpheme_mapping", "question": "Which prefix marks inclusive we (we1+2)?", "answer": "ke-"}, + {"id": "menominee-by-mouth", "type": "morpheme_mapping", "question": "Which transitive element means 'by mouth'?", "answer": "-aht"}, + {"id": "menominee-by-hand", "type": "morpheme_mapping", "question": "Which transitive element means 'by hand'?", "answer": "-en"}, + {"id": "menominee-transitive-first", "type": "morpheme_mapping", "question": "Which transitive ending marks first-person singular?", "answer": "-an"}, + {"id": "menominee-length-rule", "type": "transformation_rule", "question": "What happens when the first two vowels of an assembled word are both short?", "answer": "the second vowel becomes long"} + ], + "2011-individual-4": [ + {"id": "nahuatl-compound-order", "type": "word_order", "question": "Which part of a Nahuatl compound modifies which other part?", "answer": "the left-hand part modifies the right-hand part"}, + {"id": "nahuatl-noun-after-l", "type": "allomorph_rule", "question": "Which ordinary noun ending occurs after l?", "answer": "-li"}, + {"id": "nahuatl-noun-elsewhere", "type": "allomorph_rule", "question": "Which ordinary noun ending occurs when the stem does not end in l?", "answer": "-tl"}, + {"id": "nahuatl-many-after-l", "type": "allomorph_rule", "question": "Which 'place of many' suffix occurs after l?", "answer": "-lah"}, + {"id": "nahuatl-diminutive", "type": "morpheme_mapping", "question": "Which suffix is the diminutive?", "answer": "-capil"} + ], + "2012-individual-1": [ + {"id": "dyirbal-order", "type": "word_order", "question": "What is the basic constituent order in the Dyirbal data?", "answer": "object, subject, verb"}, + {"id": "dyirbal-adjective-order", "type": "word_order", "question": "Where does an adjective occur relative to its noun?", "answer": "after the noun"}, + {"id": "dyirbal-causative", "type": "morpheme_mapping", "question": "Which suffix forms a causative verb from an adjective?", "answer": "-man"}, + {"id": "dyirbal-object-dangerous", "type": "class_mapping", "question": "Which object article is used for women and dangerous animals or objects?", "answer": "balan"}, + {"id": "dyirbal-object-men", "type": "class_mapping", "question": "Which object article is used for men and other animals?", "answer": "bayi"}, + {"id": "dyirbal-object-other", "type": "class_mapping", "question": "Which object article is used for the remaining noun class?", "answer": "bala"} + ], + "2012-individual-5": [ + {"id": "rotuman-changed-position", "type": "word_order", "question": "Which word in a Rotuman two-word phrase undergoes the phrase-form change?", "answer": "the first word"}, + {"id": "rotuman-vcv", "type": "transformation_rule", "question": "What phrase form results from a citation form ending in -VCV?", "answer": "-VC"}, + {"id": "rotuman-vcu", "type": "transformation_rule", "question": "What phrase form results from a citation form ending in -VCu?", "answer": "-VC"}, + {"id": "rotuman-vca", "type": "transformation_rule", "question": "What happens to final -VCa in phrase form?", "answer": "it becomes -VaC"}, + {"id": "rotuman-noun-adjective", "type": "word_order", "question": "What is the order of a noun and its adjective?", "answer": "noun, adjective"} + ], + "2016-individual-5": [ + {"id": "jaqaru-possessor-his", "type": "morpheme_mapping", "question": "Which Jaqaru possessor suffix means 'his'?", "answer": "-p”a"}, + {"id": "jaqaru-possessor-our", "type": "morpheme_mapping", "question": "Which possessor suffix means inclusive 'our1+2'?", "answer": "-sa"}, + {"id": "jaqaru-possessor-my", "type": "morpheme_mapping", "question": "Which possessor suffix means 'my'?", "answer": "-nha"}, + {"id": "jaqaru-possessor-your", "type": "morpheme_mapping", "question": "Which possessor suffix means 'your'?", "answer": "-ma"}, + {"id": "jaqaru-from", "type": "morpheme_mapping", "question": "Which suffix means 'from'?", "answer": "-t”a"}, + {"id": "jaqaru-interrogative", "type": "morpheme_mapping", "question": "Which suffix is interrogative?", "answer": "-txi"}, + {"id": "jaqaru-case-vowel-rule", "type": "transformation_rule", "question": "When an oral case suffix follows a root-final vowel, is that root vowel consumed or preserved?", "answer": "preserved"} + ], + "2017-individual-2": [ + {"id": "abui-possessor-order", "type": "word_order", "question": "Where does a possessor occur relative to the possessed noun?", "answer": "before the possessed noun"}, + {"id": "abui-first-possessor", "type": "morpheme_mapping", "question": "Which possessor prefix marks first-person singular?", "answer": "n-"}, + {"id": "abui-second-possessor", "type": "morpheme_mapping", "question": "Which possessor prefix marks second-person singular?", "answer": "zero"}, + {"id": "abui-third-possessor", "type": "morpheme_mapping", "question": "Which possessor prefix marks third-person singular?", "answer": "h-"}, + {"id": "abui-body-part", "type": "class_mapping", "question": "Except after ri-, which prefix appears on a possessed body-part noun?", "answer": "a-"}, + {"id": "abui-other-noun", "type": "class_mapping", "question": "Except after ri-, which prefix appears on another possessed noun?", "answer": "e-"} + ], + "2017-individual-3": [ + {"id": "kimbundu-basic-order", "type": "word_order", "question": "What is the basic order of subject, verb, optional object, and optional place?", "answer": "subject, verb, object, place"}, + {"id": "kimbundu-first-subject", "type": "morpheme_mapping", "question": "Which verb prefix expresses a first-person-singular subject?", "answer": "ŋg-"}, + {"id": "kimbundu-possessed-order", "type": "word_order", "question": "Where does a possessed noun occur relative to its possessive pronoun?", "answer": "before the possessive pronoun"}, + {"id": "kimbundu-place-concord", "type": "class_mapping", "question": "Which concord prefix marks place expressions?", "answer": "mù-"}, + {"id": "kimbundu-statement-tone", "type": "prosody_rule", "question": "What is the sentence-final tone of a statement?", "answer": "low"}, + {"id": "kimbundu-question-tone", "type": "prosody_rule", "question": "What is the sentence-final tone of a question?", "answer": "high"} + ], + "2018-individual-2": [ + {"id": "hakhun-order", "type": "word_order", "question": "What is the order of subject, optional object, predicate, agreement complex, and final ne?", "answer": "subject, object, predicate, agreement complex, ne"}, + {"id": "hakhun-singular-transitive", "type": "morpheme_mapping", "question": "Which marker follows a first- or second-person-singular transitive subject?", "answer": "-bə"}, + {"id": "hakhun-other-transitive", "type": "morpheme_mapping", "question": "Which marker follows a third-person or plural transitive subject?", "answer": "kəmə"}, + {"id": "hakhun-hierarchy", "type": "role_rule", "question": "What is the person hierarchy from highest to lowest?", "answer": "first > second > third"}, + {"id": "hakhun-present-higher-subject", "type": "morpheme_mapping", "question": "Which agreement prefix marks present tense when the subject outranks the object?", "answer": "k-"}, + {"id": "hakhun-present-higher-object", "type": "morpheme_mapping", "question": "Which agreement prefix marks present tense when the object outranks the subject?", "answer": "r-"}, + {"id": "hakhun-sleep", "type": "lexical_mapping", "question": "Which predicate means 'sleep'?", "answer": "ʒip"} + ], + "2018-individual-3": [ + {"id": "terena-first-p", "type": "transformation_rule", "question": "For first-person singular, what does the first voiceless p become?", "answer": "mb"}, + {"id": "terena-first-t", "type": "transformation_rule", "question": "For first-person singular, what does the first voiceless t become?", "answer": "nd"}, + {"id": "terena-first-k", "type": "transformation_rule", "question": "For first-person singular, what does the first voiceless k become?", "answer": "ng"}, + {"id": "terena-second-a", "type": "transformation_rule", "question": "For second-person singular in a native word, what does the first eligible a become?", "answer": "e"}, + {"id": "terena-second-o", "type": "transformation_rule", "question": "For second-person singular, what does the first eligible o become?", "answer": "e"}, + {"id": "terena-portuguese-accent", "type": "transformation_rule", "question": "In a Portuguese loan, what does á become for second-person singular?", "answer": "eá"} + ], + "2019-individual-5": [ + {"id": "nooni-copular-order", "type": "word_order", "question": "What is the order of the two terms in the Nooni copular construction?", "answer": "A nú B"}, + {"id": "nooni-clause-order", "type": "word_order", "question": "What is the ordinary order of subject, tense, verb, object, place, and day?", "answer": "subject, tense, verb, object, place, day"}, + {"id": "nooni-see", "type": "morpheme_order", "question": "What is the discontinuous construction meaning 'see'?", "answer": "yɛn (object) lé"}, + {"id": "nooni-past-today", "type": "morpheme_mapping", "question": "Which tense marker means past today?", "answer": "bɛ̂ː"}, + {"id": "nooni-near-future", "type": "morpheme_mapping", "question": "Which marker means future fewer than three days ahead?", "answer": "nú bóy"}, + {"id": "nooni-far-future", "type": "morpheme_mapping", "question": "Which marker means future more than three days ahead?", "answer": "nú yúː"}, + {"id": "nooni-first-person", "type": "morpheme_mapping", "question": "Which prefix marks first-person singular on the tense marker or verb?", "answer": "n-"}, + {"id": "nooni-le-after-consonant", "type": "allomorph_rule", "question": "What does lé become after a consonant?", "answer": "é"} + ], + "2021-individual-1": [ + {"id": "ekari-one", "type": "lexical_mapping", "question": "Which Ekari numeral means 1?", "answer": "ena"}, + {"id": "ekari-six", "type": "lexical_mapping", "question": "Which Ekari numeral means 6?", "answer": "benomi"}, + {"id": "ekari-nine", "type": "lexical_mapping", "question": "Which Ekari numeral means 9?", "answer": "ije"}, + {"id": "ekari-ten", "type": "lexical_mapping", "question": "Which Ekari numeral means 10?", "answer": "rati"}, + {"id": "ekari-sixty", "type": "lexical_mapping", "question": "Which Ekari numeral means 60?", "answer": "moeto"}, + {"id": "ekari-addition", "type": "arithmetic_rule", "question": "What operation is expressed when a unit with -ma precedes a multiple of ten?", "answer": "addition"}, + {"id": "ekari-subtractive-nine", "type": "arithmetic_rule", "question": "Which unit may precede the next decade to express subtraction by one?", "answer": "ije"}, + {"id": "ekari-daemita", "type": "arithmetic_rule", "question": "What value does X daemita moeto represent?", "answer": "60 + X"} + ], + "2022-individual-1": [ + {"id": "ubykh-role-order", "type": "morpheme_order", "question": "In what role order do person prefixes occur around the fixed verb stem?", "answer": "direct object, indirect object, subject"}, + {"id": "ubykh-first-singular", "type": "morpheme_mapping", "question": "Which person prefix marks first-person singular?", "answer": "s-"}, + {"id": "ubykh-first-plural", "type": "morpheme_mapping", "question": "Which person prefix marks first-person plural?", "answer": "šʼ-"}, + {"id": "ubykh-second-singular", "type": "morpheme_mapping", "question": "Which person prefix marks second-person singular?", "answer": "w-"}, + {"id": "ubykh-second-plural", "type": "morpheme_mapping", "question": "Which person prefix marks second-person plural?", "answer": "ŝʷ-"}, + {"id": "ubykh-a-vowel", "type": "allomorph_rule", "question": "When is the verb vowel a rather than ə?", "answer": "when the direct object is plural or a second-person-plural participant is present"} + ], + "2023-individual-5": [ + {"id": "supyire-one", "type": "lexical_mapping", "question": "Which Supyire numeral means 1?", "answer": "niŋkin"}, + {"id": "supyire-five", "type": "lexical_mapping", "question": "Which Supyire numeral means 5?", "answer": "kaŋkuro"}, + {"id": "supyire-ten", "type": "lexical_mapping", "question": "Which Supyire numeral means 10?", "answer": "kɛ"}, + {"id": "supyire-twenty", "type": "lexical_mapping", "question": "Which Supyire numeral means 20?", "answer": "beɲjaaga"}, + {"id": "supyire-eighty", "type": "lexical_mapping", "question": "Which Supyire numeral means 80?", "answer": "ŋkuu"}, + {"id": "supyire-four-hundred", "type": "lexical_mapping", "question": "Which Supyire numeral means 400?", "answer": "kampwoo"}, + {"id": "supyire-addition", "type": "arithmetic_rule", "question": "What arithmetic operation does na express?", "answer": "addition"}, + {"id": "supyire-400-multiplier", "type": "allomorph_rule", "question": "Which form of 400 occurs before a multiplier?", "answer": "kampwɔhii"} + ], + "2024-individual-1": [ + {"id": "arapesh-verb-order", "type": "morpheme_order", "question": "Which comes first in the verb: subject prefix or tense prefix?", "answer": "subject prefix"}, + {"id": "arapesh-first-subject", "type": "morpheme_mapping", "question": "Which subject prefix marks first-person singular?", "answer": "t-"}, + {"id": "arapesh-third-nonsingular", "type": "morpheme_mapping", "question": "Which subject prefix marks third-person dual or plural?", "answer": "ne-"}, + {"id": "arapesh-present", "type": "morpheme_mapping", "question": "Which prefix marks present tense?", "answer": "ku-"}, + {"id": "arapesh-future", "type": "morpheme_mapping", "question": "Which prefix marks future tense?", "answer": "je-"}, + {"id": "arapesh-third-singular-object", "type": "morpheme_mapping", "question": "Which ending marks a third-person-singular object?", "answer": "-n"}, + {"id": "arapesh-third-plural-object", "type": "morpheme_mapping", "question": "Which ending marks a third-person-plural object?", "answer": "-new"}, + {"id": "arapesh-tj", "type": "transformation_rule", "question": "What does the sequence t+j become?", "answer": "cc"} + ] + } +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/train_source_rules_v1.json b/benchmark/IOL/ioling_hf/data/manual_overrides/train_source_rules_v1.json new file mode 100644 index 0000000000000000000000000000000000000000..4e5a803138eeed7e638eb88084c083fa47631e69 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/train_source_rules_v1.json @@ -0,0 +1,37 @@ +{ + "schema_version": "ioling_train_source_rules_v1", + "reviewed_at_utc": "2026-07-11", + "reviewer": "Codex, transcribed from rendered official IOL solution pages", + "sources": { + "2008-individual-5": { + "solution_pdf": "data/raw/pdfs/iol-2008-indiv-sol.en.pdf", + "solution_page_1_indexed": 3, + "rule_card": "Inuktitut has three relevant sentence patterns. (1) X-(q) V: X acts on himself or herself. (2) X-(q) Y-(r)mik V-si: X acts on an indefinite Y. (3) X-up Y-(q) V: X acts on the definite Y. A noun that has final -q as a subject or definite object uses -r before indefinite-object -mik; a vowel-final noun takes -mik directly. To mark 'your', replace subject/object -(q) by -it and possessor -up by -vit. A verb takes -j after a vowel and -t after a consonant, then a person ending. In patterns (1) and (2), -utit marks second-person subject and -uq marks third-person subject. In pattern (3), -ait marks second-person subject with third-person object, -anga marks third-person subject with third-person object, and -aatit marks third-person subject with second-person object. A transitive verb with no object is reflexive. Useful roots visible in the examples include qingmi 'dog', inuuhuktu 'boy', iluaqhaiji 'doctor', angatkuq 'shaman', nanuq 'polar bear', angunahukti 'hunter', amaruq 'wolf', ilinniaqtitsiji 'teacher'; taku 'see', qukiq 'shoot', aanniq 'hurt', aarqi 'cure', iputu 'spear', qai 'come', and ukiakhaq 'fall'." + }, + "2011-individual-1": { + "solution_pdf": "data/raw/pdfs/iol-2011-indiv-sol.en-gb.pdf", + "solution_page_1_indexed": 1, + "rule_card": "A Menominee verb is assembled from a person prefix, a directional or lexical element, a verb element, and a person ending. Prefix ne- means first-person singular, ke- means inclusive we (we1+2), and third person has no prefix. Directional or lexical elements include kaw 'down', ket 'out', kesk 'through', pahk 'off', pāhk 'open', pīt 'hither', taw 'pierce', wack 'around', and wǣp 'begin'. Intransitive elements include -āhpe 'laughing', -ānæhkæ 'digging', -eqta 'lying flat', and -ohnæ 'walking', followed by -m 'I', -q 'we1+2', or -w 'he'. Transitive elements include -ah 'by tool', -aht 'by mouth', -en 'by hand', and -es 'cutting', followed by -an 'I', -æq 'we1+2', or -am 'he'. If the first two vowels in the assembled word are both short, the second becomes long; for example e becomes ǣ." + }, + "2012-individual-1": { + "solution_pdf": "data/raw/pdfs/iol-2012-indiv-sol.en.pdf", + "solution_page_1_indexed": 1, + "rule_card": "Dyirbal order is object-subject-verb, and adjectives follow nouns. An adjective can form a causative verb with -man ('make adjective'). A verb can form an adjective meaning 'that is always being V-ed' or 'that is always V-ing nouns'; the surface suffix depends on the final sound of the verb. Every noun phrase starts with an article. Object articles are balan for women and dangerous animals or objects, bayi for men and other animals, and bala for the remaining class. Corresponding subject articles are baNgun, baNgul, and baNgu. The subject noun and its attributes take -Ngu after a vowel in a two-syllable word, -gu after a vowel in a longer word, and a homorganic stop plus -u after a consonant. Use the lexical correspondences supplied in the numbered examples; preserve object-subject-verb order when translating the target." + }, + "2012-individual-5": { + "solution_pdf": "data/raw/pdfs/iol-2012-indiv-sol.en.pdf", + "solution_page_1_indexed": 4, + "rule_card": "In a Rotuman two-word phrase, the first word changes its final part. Officially: final -VCV becomes -VC; final -VCu also becomes -VC; final -VCi changes to an umlauted-vowel-plus-consonant form; and final -VCa becomes -VaC. The same changes occur in reduplicated adjectives. Word order is modified noun then modifier noun, noun then adjective, and verb then object. Thus the first component of an observed phrase may have several possible citation forms when the reverse operation is ambiguous. For the target, reverse the phrase form fäeag in fäeag ‘u‘u 'to use sign language' to recover possible forms meaning 'word', and reverse a‘öf in a‘öf fau 'year's end' to recover possible forms meaning 'to exhaust'." + }, + "2016-individual-5": { + "solution_pdf": "data/raw/pdfs/iol-2016-indiv-sol.en.pdf", + "solution_page_1_indexed": 5, + "rule_card": "A Jaqaru form has a root followed by up to three suffixes. Possessor suffixes are -p”a 'his', -sa 'our1+2', -nha 'my', and -ma 'your'. Case or other suffixes are -p”a 'through', -psa 'too', -t”a 'from', -txi interrogative, and -na 'in'. The oral suffixes -p”a, -sa, -p”a, -psa, -t”a, and -txi affect a preceding vowel: the first possessor group always consumes it, while the case group consumes a vowel belonging to another suffix but preserves a root vowel. Nasal -nha and -ma consume a preceding vowel if they retain their own vowel; -na follows the corresponding nasal rule. Relevant roots in the problem are aq” 'cave', qucxa 'lake', chushu 'corner', marka 'town', ishi 'bed', uta 'house', p”ak”u 'pot', yapu 'field', and qaqa 'cliff'. Analyze suffix order and vowel loss, but preserve the exact orthography shown in the verified answer." + }, + "2019-individual-5": { + "solution_pdf": "data/raw/pdfs/iol-2019-indiv-sol.en.pdf", + "solution_page_1_indexed": 5, + "rule_card": "Nooni copular order is A (T) nú B, meaning A is or was B; cí marks past and no tense word marks future in this construction. Ordinary clause order is subject, tense, verb, object, optional lé, place, day. The verb 'see' is yɛn (object) lé; after a consonant, lé becomes é. Past tense uses nɔ̂ː for just now, bɛ̂ː for today, cí nɔ̂ː for fewer than three days ago, and tɔ̀ nɔ̂ː for more than three days ago. Future uses nú for 'be about to', nú géː for today, nú bóy for fewer than three days ahead, and nú yúː for more than three days ahead. First-person singular adds n- to the tense marker or verb, with nb becoming mb, nk/ng becoming ŋk/ŋg, and nn becoming n. After a falling, high-falling, or low tone, a following high tone becomes rising. Use the day sequence and lexical correspondences established by the numbered examples, and preserve all tones and vowel lengths in Nooni output." + } + } +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/train_target_derivations_v1.json b/benchmark/IOL/ioling_hf/data/manual_overrides/train_target_derivations_v1.json new file mode 100644 index 0000000000000000000000000000000000000000..31b3b30af1f0ee3c307f166c013c120a5da5b14e --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/train_target_derivations_v1.json @@ -0,0 +1,306 @@ +{ + "schema_version": "ioling_train_target_derivations_v1", + "reviewed_at_utc": "2026-07-11", + "review_method": "Each target and derivation was checked against the rendered official solution page and the atomic problem prompt.", + "records": { + "iol-2012-individual-p5-sub-d-atomic-d.1": { + "source_problem_id": "2012-individual-5", + "facts": [ + "In fäeag ‘u‘u, the first word is the phrase form of the word meaning 'word'.", + "Reversing every applicable phrase-form rule for fäeag gives exactly fäega, fäeaga, and fäeagu." + ], + "assistant_completion": "The phrase fäeag ‘u‘u means 'to use sign language', so fäeag is the changed phrase form of the word for 'word'. Reversing each applicable final-vowel rule gives the three possible citation forms fäega, fäeaga, and fäeagu; the data do not distinguish among them.\n\n\\boxed{d.1: fäega (or fäeaga, fäeagu)}" + }, + "iol-2012-individual-p5-sub-d-atomic-d.2": { + "source_problem_id": "2012-individual-5", + "facts": [ + "In a‘öf fau, the first word is the phrase form of the verb meaning 'to exhaust'.", + "Exhaustively reversing the phrase-form rules gives exactly a‘ofi, a‘öfi, a‘öfö, a‘öfu, a‘öfü, and a‘ofü." + ], + "assistant_completion": "The compound a‘öf fau is 'to exhaust + year', so a‘öf is the changed phrase form of the required verb. Applying all inverse phrase-form possibilities, including the ambiguous vowel changes, gives six and only six citation forms.\n\n\\boxed{d.2: a‘ofi (or a‘öfi, a‘öfö, a‘öfu, a‘öfü, a‘ofü)}" + }, + "iol-2016-individual-p5-sub-a-atomic-a.1": { + "source_problem_id": "2016-individual-5", + "facts": [ + "uta means 'house', -nha means 'my', -na means 'in', and -txi is interrogative.", + "The suffix vowel-elision rules produce ut-nha-n-txi." + ], + "assistant_completion": "Segment utnhantxi as uta 'house' + -nha 'my' + -na 'in' + -txi interrogative. The regular elisions give ut-nha-n-txi, so the whole form asks whether something is in the speaker's house.\n\n\\boxed{a.1: is it in my house?}" + }, + "iol-2016-individual-p5-sub-a-atomic-a.2": { + "source_problem_id": "2016-individual-5", + "facts": [ + "yapu means 'field', possessive -p”a means 'his', and -psa means 'too'.", + "Possessive -p”a removes the root-final vowel, and -psa removes the vowel of the preceding suffix." + ], + "assistant_completion": "Here -p”a is the possessive suffix 'his', not the homophonous case suffix 'through'. In yapu + -p”a + -psa, possessive -p”a consumes the root vowel and -psa consumes the preceding suffix vowel, producing yapp”psa: 'his field too'.\n\n\\boxed{a.2: his field too}" + }, + "iol-2016-individual-p5-sub-a-atomic-a.3": { + "source_problem_id": "2016-individual-5", + "facts": [ + "yapu means 'field', case -p”a means 'through', and -psa means 'too'.", + "Case -p”a preserves a root vowel, while -psa removes the vowel belonging to the preceding suffix." + ], + "assistant_completion": "In yapup”psa, -p”a is the case suffix 'through'. Unlike possessive -p”a, it leaves the root-final u; final -psa 'too' removes the vowel of the preceding suffix. Thus the form means 'through the field too'.\n\n\\boxed{a.3: through the field too}" + }, + "iol-2012-individual-p1-sub-b-atomic-b.1": { + "source_problem_id": "2012-individual-1", + "facts": [ + "Dyirbal order is object-subject-verb.", + "balan ñalNga is 'the girl'; baNgul NumaNgu guniymuNagu is 'the father that is always being searched for'; bambunman is 'is healing'." + ], + "assistant_completion": "Use the object-subject-verb order. The object balan ñalNga is 'the girl'. The subject phrase baNgul NumaNgu guniymuNagu is 'the father that is always being searched for', and bambunman is the causative verb 'is healing'.\n\n\\boxed{b.1: The father that is always being searched for is healing the girl.}" + }, + "iol-2012-individual-p1-sub-b-atomic-b.2": { + "source_problem_id": "2012-individual-1", + "facts": [ + "Dyirbal order is object-subject-verb.", + "bala diban bilmbalmuNa is 'the stone that is always being pushed'; baNgun biñéiriñéu is 'the lizard'; guniñu is 'is searching for'." + ], + "assistant_completion": "The first noun phrase is the object: bala diban bilmbalmuNa is 'the stone that is always being pushed'. The marked subject baNgun biñéiriñéu is 'the lizard', and final guniñu means 'is searching for'. Reordering into English gives the translation.\n\n\\boxed{b.2: The lizard is searching for the stone that is always being pushed.}" + }, + "iol-2012-individual-p1-sub-b-atomic-b.3": { + "source_problem_id": "2012-individual-1", + "facts": [ + "Dyirbal order is object-subject-verb.", + "bayi bargan is 'the wallaby'; baNgul yaóaNgu gubimbuluNunéanaymuNagu is 'the man that is always blaming doctors'; banéan is 'is following'." + ], + "assistant_completion": "The object bayi bargan is 'the wallaby'. The subject is baNgul yaóaNgu followed by the derived modifier gubimbuluNunéanaymuNagu, giving 'the man that is always blaming doctors'. Final banéan is 'is following'.\n\n\\boxed{b.3: The man that is always blaming doctors is following the wallaby.}" + }, + "iol-2011-individual-p1-sub-b-atomic-b.1": { + "source_problem_id": "2011-individual-1", + "facts": [ + "The components are ne- 'I', wǣp 'begin', -aht 'by mouth', and transitive -an 'I'.", + "Their surface concatenation is newǣpahtan." + ], + "assistant_completion": "This is a transitive 'by mouth' form. Combine ne- for first-person singular, wǣp 'begin', -aht 'by mouth', and the transitive first-person ending -an. The resulting Menominee word is newǣpahtan.\n\n\\boxed{b.1: newǣpahtan}" + }, + "iol-2011-individual-p1-sub-b-atomic-b.2": { + "source_problem_id": "2011-individual-1", + "facts": [ + "The components are ke- 'we1+2', kaw 'down', -en 'by hand', and transitive -æq 'we1+2'.", + "The first two vowels are short, so the second, a, lengthens to ā." + ], + "assistant_completion": "Use ke- for inclusive 'we1+2', kaw 'down', -en 'by hand', and the transitive inclusive ending -æq. Before the length rule this is kekawenæq. Its first two vowels are short, so the second vowel a becomes ā, yielding kekāwenæq.\n\n\\boxed{b.2: kekāwenæq}" + }, + "iol-2011-individual-p1-sub-b-atomic-b.3": { + "source_problem_id": "2011-individual-1", + "facts": [ + "Third person has no prefix.", + "The components are taw 'pierce', -ānæhkæ 'digging', and intransitive -w 'he'." + ], + "assistant_completion": "Third person takes no prefix. Combine taw 'pierce' with the intransitive element -ānæhkæ 'digging' and the third-person ending -w. This gives tawānæhkæw, literally the construction for 'he digs a hole'.\n\n\\boxed{b.3: tawānæhkæw}" + }, + "iol-2011-individual-p1-sub-b-atomic-b.4": { + "source_problem_id": "2011-individual-1", + "facts": [ + "Third person has no prefix; ket means 'out', -ohnæ means 'walking', and -w means 'he'.", + "In ketohnæw the first two vowels are short, so o lengthens to ō." + ], + "assistant_completion": "For third-person 'he' there is no prefix. Join ket 'out', -ohnæ 'walking', and intransitive -w 'he' to obtain ketohnæw. The first two vowels e and o are short, so the second lengthens: ketōhnæw.\n\n\\boxed{b.4: ketōhnæw}" + }, + "iol-2019-individual-p5-sub-a-atomic-a.1": { + "source_problem_id": "2019-individual-5", + "facts": [ + "The copular pattern A nú B means 'A is B'.", + "fɔ̀ shě ntfǔː means 'the day after tomorrow'." + ], + "assistant_completion": "This uses the copular order A nú B, 'A is B'. The expression fɔ̀ shě ntfǔː is 'the day after tomorrow', as in the parallel dated example. Therefore Bvusɔw is identified as that day.\n\n\\boxed{a.1: Bvusɔw is the day after tomorrow.}" + }, + "iol-2019-individual-p5-sub-a-atomic-a.2": { + "source_problem_id": "2019-individual-5", + "facts": [ + "me is 'I', nú géː marks future today, yɛn ... lé means 'see', kèŋkfǔ is 'yam', and ɛ̀bɛ̀n is 'today'.", + "First-person n- produces the surface forms ŋgéː and nyɛ́n." + ], + "assistant_completion": "Read the ordinary clause in subject-tense-verb-object-day order. me is 'I'; nú ŋgéː is the first-person form of today's future; nyɛ́n ... lé is 'see'; kèŋkfǔ is 'yam'; and ɛ̀bɛ̀n is 'today'.\n\n\\boxed{a.2: Today, I will see the yam.}" + }, + "iol-2019-individual-p5-sub-a-atomic-a.3": { + "source_problem_id": "2019-individual-5", + "facts": [ + "wvù is 'he', tɔ̀ nɔ̂ː marks past more than three days ago, yɛn ... lé means 'see', bèsèn is 'us', and bvúmbòn is the day Bvumbon.", + "After a consonant, lé appears as é; tone sandhi gives the written ě." + ], + "assistant_completion": "wvù is 'he' and tɔ̀ nɔ̂ː places the event more than three days in the past. The predicate yɛ᷅n bèsèn ě is 'saw us'; ě is the conditioned form of lé after the object. The final day is Bvumbon.\n\n\\boxed{a.3: On Bvumbon, he saw us.}" + }, + "iol-2019-individual-p5-sub-a-atomic-a.4": { + "source_problem_id": "2019-individual-5", + "facts": [ + "bèsèn is 'we', nú bóy marks future fewer than three days ahead, tɔ́ is 'come', fɔ̀wǎy is 'market', and bvúzhı᷇ːde᷆n is Bvuzhiden." + ], + "assistant_completion": "The clause follows subject-tense-verb-place-day order. bèsèn is 'we', nú bóy is the near-future marker, tɔ́ means 'come', fɔ̀wǎy is 'market', and the final word is the day Bvuzhiden.\n\n\\boxed{a.4: On Bvuzhiden, we will come to the market.}" + }, + "iol-2008-individual-p5-sub-b-atomic-b.1": { + "source_problem_id": "2008-individual-5", + "facts": [ + "A definite transitive clause has subject-up, then the definite object if overt, then the verb.", + "Angatku-up is 'the shaman' as subject; aanniq-t-aatit is 'hurt' plus the 3rd-subject/2nd-object ending." + ], + "assistant_completion": "Use the definite transitive pattern. Angatku takes subject -up, giving Angatkuup. The consonant-final verb aanniq takes -t, and -aatit marks third-person subject acting on second-person object.\n\n\\boxed{b.1: Angatkuup aanniqtaatit.}" + }, + "iol-2008-individual-p5-sub-b-atomic-b.2": { + "source_problem_id": "2008-individual-5", + "facts": [ + "Ilinniaqtitsiji-up is 'the teacher' as subject and inuuhuktu-q is the definite boy object.", + "taku-j-anga is 'see' with the 3rd-subject/3rd-object ending." + ], + "assistant_completion": "This is a definite transitive clause: Ilinniaqtitsijiup is the teacher marked as subject, and inuuhuktuq is the definite boy object. Vowel-final taku takes -j, followed by -anga for a third-person subject and third-person object.\n\n\\boxed{b.2: Ilinniaqtitsijiup inuuhuktuq takujanga.}" + }, + "iol-2008-individual-p5-sub-b-atomic-b.3": { + "source_problem_id": "2008-individual-5", + "facts": [ + "Replacing subject -q with -it marks 'your', so amaruq becomes amaruit.", + "ukiakhaq-t-uq is consonant-final 'fall' with a third-person subject." + ], + "assistant_completion": "The possessed subject 'your wolf' is formed by replacing the wolf's -q with -it: amaruit. The consonant-final verb ukiakhaq takes -t and the third-person ending -uq, giving ukiakhaqtuq.\n\n\\boxed{b.3: Amaruit ukiakhaqtuq.}" + }, + "iol-2008-individual-p5-sub-b-atomic-b.4": { + "source_problem_id": "2008-individual-5", + "facts": [ + "An indefinite object uses -(r)mik, so qingmiq becomes qingmirmik.", + "qukiq-si-j-utit is the indefinite-object verb form with second-person subject." + ], + "assistant_completion": "A dog is indefinite here, so qingmiq takes -rmik: qingmirmik. With an indefinite object, qukiq uses -si; the resulting vowel-final form takes -j and then -utit for second-person subject, giving qukiqsijutit.\n\n\\boxed{b.4: Qingmirmik qukiqsijutit.}" + }, + "iol-2008-individual-p5-sub-b-atomic-b.5": { + "source_problem_id": "2008-individual-5", + "facts": [ + "Replacing subject -q with -it gives qingmiit 'your dog'.", + "The vowel-final indefinite object is ilinniaqtitsiji-mik; aanniq-si-j-uq marks a third-person subject." + ], + "assistant_completion": "The subject 'your dog' is qingmiit, with -it replacing -q. The vowel-final indefinite object 'a teacher' is ilinniaqtitsijimik. The indefinite-object verb is aanniq-si-j-uq, with third-person subject ending -uq.\n\n\\boxed{b.5: Qingmiit ilinniaqtitsijimik aanniqsijuq.}" + }, + "iol-2019-individual-p5-sub-c-atomic-c.1": { + "source_problem_id": "2019-individual-5", + "facts": [ + "The order is subject-tense-verb-object-day.", + "me is 'I'; first-person n- gives ncí and nfı᷅; cí nɔ̂ː is the required past interval; dìɛ̀msɛ̌n is 'man'; bvúsɔ̀w is Bvusɔw." + ], + "assistant_completion": "Use subject-tense-verb-object-day order. me is 'I'. For this past interval the tense is cí nɔ̂ː, with first-person n- producing ncí; the same prefix gives nfı᷅ for 'help'. Then place dìɛ̀msɛ̌n 'man' before the day Bvusɔw.\n\n\\boxed{c.1: me ncí nɔ̂ː nfı᷅ dìɛ̀msɛ̌n bvúsɔ̀w.}" + }, + "iol-2019-individual-p5-sub-c-atomic-c.2": { + "source_problem_id": "2019-individual-5", + "facts": [ + "cɔ̌ŋ is 'thief', nɔ̂ː is 'just now', cɔ᷅ŋ is 'steal', and kèŋkfǔ is 'yam'." + ], + "assistant_completion": "The ordinary clause order is subject-tense-verb-object. Use cɔ̌ŋ 'thief', nɔ̂ː 'just now', cɔ᷅ŋ 'steal', and kèŋkfǔ 'yam' in that order.\n\n\\boxed{c.2: cɔ̌ŋ nɔ̂ː cɔ᷅ŋ kèŋkfǔ.}" + }, + "iol-2019-individual-p5-sub-c-atomic-c.3": { + "source_problem_id": "2019-individual-5", + "facts": [ + "me is 'I'; nú yúː marks future more than three days ahead; yów is 'hear'; mutù is 'car'; bvûŋka᷆ːde᷆n is Bvuŋkaden.", + "First-person n- produces nyúː and nyów." + ], + "assistant_completion": "Bvuŋkaden lies in the more-than-three-days future category, so use nú yúː. With subject me 'I', first-person n- gives nyúː and also nyów from yów 'hear'. Follow this with mutù 'car' and the day Bvuŋkaden.\n\n\\boxed{c.3: me nú nyúː nyów mutù bvûŋka᷆ːde᷆n.}" + }, + "iol-2019-individual-p5-sub-c-atomic-c.4": { + "source_problem_id": "2019-individual-5", + "facts": [ + "kwɔ᷆ːn is 'woman', nú géː is today's future, yó is 'kill', dìɛ̀msɛ̌n is 'man', and ɛ̀bɛ̀n is 'today'." + ], + "assistant_completion": "Use subject-tense-verb-object-day order. kwɔ᷆ːn is 'woman', nú géː marks future today, yó is 'kill', dìɛ̀msɛ̌n is 'man', and ɛ̀bɛ̀n is the day word 'today'.\n\n\\boxed{c.4: kwɔ᷆ːn nǔ géː yó dìɛ̀msɛ̌n ɛ̀bɛ̀n.}" + }, + "iol-2019-individual-p5-sub-c-atomic-c.5": { + "source_problem_id": "2019-individual-5", + "facts": [ + "dìɛ̀msɛ̌n is 'man', bɛ̂ː marks past today, yɛn ... lé is 'see', wɔ̀ is singular 'you', and ɛ̀bɛ̀n is 'today'.", + "Tone sandhi gives the written forms yɛ᷅n and lě." + ], + "assistant_completion": "Place dìɛ̀msɛ̌n 'man' before the past-today marker bɛ̂ː. The 'see' construction is yɛn object lé, here with wɔ̀ 'you(sg)'; the required tone changes produce yɛ᷅n and lě. End with ɛ̀bɛ̀n 'today'.\n\n\\boxed{c.5: dìɛ̀msɛ̌n bɛ̂ː yɛ᷅n wɔ̀ lě ɛ̀bɛ̀n.}" + }, + "iol-2016-individual-p5-sub-b-atomic-b.1": { + "source_problem_id": "2016-individual-5", + "facts": [ + "qaqa means 'cliff' and possessive -sa means 'our1+2'.", + "Oral possessive -sa consumes the root-final vowel." + ], + "assistant_completion": "Attach possessive -sa 'our1+2' to qaqa 'cliff'. Because oral possessor suffixes always consume the preceding vowel, qaqa + -sa becomes qaqsa.\n\n\\boxed{b.1: qaqsa}" + }, + "iol-2016-individual-p5-sub-b-atomic-b.2": { + "source_problem_id": "2016-individual-5", + "facts": [ + "chushu means 'corner', -ma means 'your', and -na means 'in'.", + "When following -na removes the vowel of -ma, -ma leaves the root-final u, giving chushu-m-na." + ], + "assistant_completion": "Combine chushu 'corner', possessive -ma 'your', and locative -na 'in'. The locative causes -ma to lose its vowel; a nasal suffix that gives up its vowel leaves the preceding root vowel intact. Thus chushu-ma-na surfaces as chushumna.\n\n\\boxed{b.2: chushumna}" + }, + "iol-2016-individual-p5-sub-b-atomic-b.3": { + "source_problem_id": "2016-individual-5", + "facts": [ + "The suffixes are -ma 'your', -na 'in', and -psa 'too'.", + "-psa removes the vowel of -na; -na then leaves the vowel of -ma, while -ma consumes the root-final u, yielding chush-ma-n-psa." + ], + "assistant_completion": "Start with chushu 'corner' and add -ma 'your', -na 'in', and -psa 'too'. Final -psa removes the vowel of -na. The resulting elision chain leaves -ma's a but removes the root-final u, producing chush-ma-n-psa.\n\n\\boxed{b.3: chushmanpsa}" + }, + "iol-2016-individual-p5-sub-b-atomic-b.4": { + "source_problem_id": "2016-individual-5", + "facts": [ + "The suffixes are -ma 'your', -t”a 'from', and -psa 'too'.", + "The elision chain removes the vowels of -ma and -t”a but preserves the root-final u, yielding chushu-m-t”-psa." + ], + "assistant_completion": "Add -ma 'your', -t”a 'from', and -psa 'too' to chushu 'corner'. Successive suffix-triggered elision removes the vowels of -ma and -t”a; because nasal -ma gives up its vowel, the root-final u remains. The surface form is chushumt”psa.\n\n\\boxed{b.4: chushumt”psa}" + }, + "iol-2016-individual-p5-sub-b-atomic-b.5": { + "source_problem_id": "2016-individual-5", + "facts": [ + "aq”i is the citation form 'cave', -t”a means 'from', and -txi is interrogative.", + "-t”a preserves the root vowel, while -txi removes the vowel of the preceding suffix, giving aq”i-t”-txi." + ], + "assistant_completion": "Use aq”i 'cave' with case -t”a 'from' and interrogative -txi. The case suffix leaves the root vowel i, while -txi consumes the vowel belonging to -t”a. This yields aq”it”txi.\n\n\\boxed{b.5: aq”it”txi}" + }, + "iol-2016-individual-p5-sub-b-atomic-b.6": { + "source_problem_id": "2016-individual-5", + "facts": [ + "uta means 'house' and -txi is interrogative.", + "Interrogative -txi leaves a root-final vowel." + ], + "assistant_completion": "Attach interrogative -txi directly to uta 'house'. As an oral case suffix it leaves a vowel that belongs to the root, so uta + -txi surfaces as utatxi.\n\n\\boxed{b.6: utatxi}" + }, + "iol-2008-individual-p5-sub-a-atomic-a.1": { + "source_problem_id": "2008-individual-5", + "facts": [ + "Amaru-up is 'the wolf' as subject, angatku-it is the definite object 'your shaman', and taku-j-anga is 'saw' with 3rd-person subject and object." + ], + "assistant_completion": "The -up on Amaru marks the wolf as subject. On angatku, -it replaces the ordinary definite ending and means 'your', so the object is 'your shaman'. taku-j-anga is 'saw' with a third-person subject and object.\n\n\\boxed{a.1: The wolf saw your shaman.}" + }, + "iol-2008-individual-p5-sub-a-atomic-a.2": { + "source_problem_id": "2008-individual-5", + "facts": [ + "Nanu-it is 'your polar bear' as subject, inuuhuktu-rmik is indefinite 'a boy', and aanniq-si-j-uq is 'hurt' with third-person subject." + ], + "assistant_completion": "Nanu-it is the possessed subject 'your polar bear'. The object inuuhuktu-rmik is indefinite, hence 'a boy'. With an indefinite object, aanniq takes -si-j-uq, whose ending marks a third-person subject.\n\n\\boxed{a.2: Your polar bear hurt a boy.}" + }, + "iol-2008-individual-p5-sub-a-atomic-a.3": { + "source_problem_id": "2008-individual-5", + "facts": [ + "Angunahukti-it is 'your hunter' as subject.", + "A transitive verb without an expressed object is reflexive, so aarqi-j-uq means 'cured himself'." + ], + "assistant_completion": "The ending -it on Angunahukti marks 'your hunter'. aarqi is transitive 'cure', but there is no object; the problem's rule therefore gives a reflexive reading. Its -j-uq ending has a third-person subject.\n\n\\boxed{a.3: Your hunter cured himself.}" + }, + "iol-2008-individual-p5-sub-a-atomic-a.4": { + "source_problem_id": "2008-individual-5", + "facts": [ + "Ilinniaqtitsiji is the definite object 'the teacher'.", + "qukiq-t-ait is 'shot' with second-person subject and third-person definite object." + ], + "assistant_completion": "Ilinniaqtitsiji is the definite third-person object 'the teacher'. The consonant-final verb qukiq takes -t, and -ait marks a second-person subject acting on a third-person definite object.\n\n\\boxed{a.4: You shot the teacher.}" + }, + "iol-2008-individual-p5-sub-a-atomic-a.5": { + "source_problem_id": "2008-individual-5", + "facts": [ + "qai means 'come'.", + "After the vowel-final root comes -j, and -utit marks second-person subject." + ], + "assistant_completion": "The intransitive root qai means 'come'. Because it ends in a vowel it takes -j, and the following -utit is the second-person subject ending. Thus Qaijutit means 'You came'.\n\n\\boxed{a.5: You came.}" + }, + "iol-2008-individual-p5-sub-a-atomic-a.6": { + "source_problem_id": "2008-individual-5", + "facts": [ + "Angunahukti-mik is the indefinite object 'a hunter'.", + "aarqi-si-j-utit is 'cure' in the indefinite-object construction with second-person subject." + ], + "assistant_completion": "The -mik ending makes Angunahukti an indefinite object, 'a hunter'. The verb aarqi uses the indefinite-object marker -si, then -j after the resulting vowel and -utit for a second-person subject.\n\n\\boxed{a.6: You cured a hunter.}" + } + } +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/v14_rule_rich_and_opd_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/v14_rule_rich_and_opd_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..bff9fde18eb6ae4d3422ebd990a049d1b1b3a684 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/v14_rule_rich_and_opd_audit.json @@ -0,0 +1,180 @@ +{ + "schema_version": "v14_rule_rich_and_opd_audit_v1", + "reviewed_at_utc": "2026-07-12T04:02:00Z", + "decision_rule": "A reasoning trace is accepted only if its final answer is exact and every supporting claim is true, grounded in the displayed problem or verified prior answers, and sufficient to derive the result. Answer-only and contradictory traces are rejected.", + "experiments": { + "matched_rule_rich_sft": { + "model": "Qwen/Qwen3-4B-Instruct-2507", + "data": "data/sft/ioling_rule_rich_traces_v3/train.jsonl", + "epochs": 2, + "learning_rate": 0.000005, + "report": "reports/sft_rule_rich_v3_e2_lr5e6_v14_val_pass8.json", + "wandb_run": "https://wandb.ai/alexgurung/ioling-research/runs/ixfwun9l" + }, + "rule_hinted_on_policy_distillation": { + "starting_adapter": "checkpoints/qwen3-4b-ioling-selected-v6-e2", + "raw_rollouts": "reports/sft_selected_v6_e2_v14_train_pass8.json", + "teacher_context": "manually checked source rules without the final answer", + "objective": "full-vocabulary forward KL on the first 128 raw student reasoning tokens; boxed-answer tokens excluded", + "records": 61, + "source_problems": 12, + "reasoning_tokens": 7808, + "optimizer_updates": 8, + "learning_rate": 0.0000005, + "validation_report": "reports/opd_rules_v1_v14_val_pass8.json", + "source_probe_report": "reports/opd_rules_v1_v14_train_one_per_source_pass8.json", + "wandb_run": "https://wandb.ai/alexgurung/ioling-research/runs/m993n7f2", + "implementation_note": "This first pilot used sequence-summed KL followed by gradient clipping. Subsequent runs use mean per-token KL so loss scale does not depend on trace length." + }, + "target_facts_on_policy_distillation": { + "starting_adapter": "checkpoints/qwen3-4b-ioling-selected-v6-e2", + "raw_rollouts": "reports/sft_selected_v6_e2_v14_train_pass8.json", + "teacher_context": "manually checked target-specific privileged facts without a boxed final answer; some facts are answer-derived", + "objective": "mean per-token full-vocabulary forward KL on at most 256 raw student reasoning tokens; boxed-answer tokens excluded", + "records": 14, + "source_problems": 4, + "reasoning_tokens": 3467, + "optimizer_updates": 4, + "learning_rate": 0.0000005, + "mean_forward_kl": 0.46686862089804243, + "validation_report": "reports/opd_target_facts_v2_v14_val_pass8.json", + "source_probe_report": "reports/opd_target_facts_v2_v14_train_one_per_source_pass8.json", + "wandb_run": "https://wandb.ai/alexgurung/ioling-research/runs/9it72z9y", + "coverage_note": "The checked target-fact ledger has 38 records, but only 14 had a nontrivial raw reasoning prefix under the rollout filter. This is a diagnostic, not a full training run." + }, + "checked_derivation_reference_dependence": { + "reference_report": "reports/opd_checked_derivation_reference_dependence_v2.json", + "records": 61, + "source_problems": 12, + "reasoning_tokens": 15499, + "conditions": "Compare the effect of adding the checked reference with the raw question against the effect of adding it to a neutral prompt.", + "probability_shift_cosine": 0.21307059679888968, + "reference_projection_on_full_shift": 0.3025029411014585, + "mean_question_conditioned_kl": 0.26097384061542, + "mean_reference_only_effect_kl": 0.6669720613354213, + "mean_sampled_token_logp_change": -0.22129928606526683, + "decision": "The question-conditioned update is not mostly reproduced by the reference-only effect, so reference subtraction is not used for the next pilot.", + "wandb_run": "https://wandb.ai/alexgurung/ioling-research/runs/ud6vsyaq" + }, + "checked_derivation_on_policy_distillation": { + "starting_adapter": "checkpoints/qwen3-4b-ioling-selected-v6-e2", + "raw_rollouts": "reports/sft_selected_v6_e2_v14_train_pass8.json", + "teacher_context": "all 61 eligible manually checked reference derivations, with boxed answers removed", + "manual_context_review": "Every privileged reference used in this run was read before launch. Many contain answer-derived target forms and are treated as privileged references, not evaluation hints.", + "objective": "mean per-token full-vocabulary forward KL on at most 256 raw student reasoning tokens; boxed-answer tokens excluded", + "records": 61, + "source_problems": 12, + "reasoning_tokens": 15499, + "optimizer_updates": 16, + "learning_rate": 0.0000005, + "mean_forward_kl": 0.25968009764786626, + "validation_report": "reports/opd_checked_derivation_v3_v14_val_pass8.json", + "source_probe_report": "reports/opd_checked_derivation_v3_v14_train_one_per_source_pass8.json", + "wandb_run": "https://wandb.ai/alexgurung/ioling-research/runs/uxwjnc9l" + }, + "checked_derivation_prefix_compatibility": { + "report": "reports/opd_checked_derivation_prefix_compatibility_v1.json", + "records": 61, + "source_problems": 12, + "tokens": 15499, + "top_k": 16, + "compatibility_threshold": 0.7, + "mean_top_k_overlap": 0.8693625330924988, + "low_compatibility_fraction": 0.09942577034235, + "sampled_token_teacher_top_k_rate": 0.993677020072937, + "effective_reliable_tokens": 15499, + "decision": "Prune-OPD-style weighting would retain every token and the privileged teacher accepts nearly every sampled student token in its top 16. Prefix drift is not the main failure; this same-model teacher is insufficiently corrective.", + "wandb_run": "https://wandb.ai/alexgurung/ioling-research/runs/2srarr0l" + } + }, + "summary": { + "rule_rich_validation_samples": 192, + "rule_rich_validation_exact_samples": 0, + "rule_rich_validation_visible_finals_reviewed": 181, + "rule_rich_validation_format_rate": 0.9427083333333334, + "rule_rich_validation_truncation_rate": 0.057291666666666664, + "opd_validation_samples": 192, + "opd_validation_exact_samples": 0, + "opd_validation_visible_finals_reviewed": 174, + "opd_validation_format_rate": 0.90625, + "opd_validation_truncation_rate": 0.09375, + "opd_source_probe_samples": 120, + "opd_source_probe_exact_samples": 6, + "opd_source_probe_exact_records": 2, + "target_facts_validation_samples": 192, + "target_facts_validation_exact_samples": 0, + "target_facts_validation_visible_finals_reviewed": 170, + "target_facts_validation_format_rate": 0.8854166666666666, + "target_facts_validation_truncation_rate": 0.11458333333333333, + "target_facts_source_probe_samples": 120, + "target_facts_source_probe_exact_samples": 4, + "target_facts_source_probe_exact_records": 2, + "checked_derivation_validation_samples": 192, + "checked_derivation_validation_exact_samples": 0, + "checked_derivation_validation_visible_finals_reviewed": 170, + "checked_derivation_validation_format_rate": 0.8854166666666666, + "checked_derivation_validation_truncation_rate": 0.11458333333333333, + "checked_derivation_source_probe_samples": 120, + "checked_derivation_source_probe_exact_samples": 8, + "checked_derivation_source_probe_exact_records": 2, + "accepted_reasoning_traces": 0, + "rejected_exact_reasoning_traces": 18, + "scorer_false_negatives_found": 0, + "accuracy_rl_gate": "closed", + "direct_opd_status": "tested_rule_target_facts_and_checked_derivations_without_gain", + "prefix_compatibility_status": "high_overlap_teacher_insufficiently_corrective" + }, + "validation_review": { + "decision": "no_scorer_false_negatives_found", + "scope": "Every valid final box in all four validation reports was grouped by record and compared with all manually verified canonical answers and aliases. For the expanded OPD run, 137 outputs were identical to the already reviewed target-facts run; all 33 changed valid boxes were separately checked and were wrong.", + "findings": [ + "Nahuatl and Arammba outputs used the wrong numeral components or values.", + "Kunuz Nubian outputs changed lexical roots, participant roles, number, or inflection.", + "Kilivila outputs changed predicates, noun classes, quantities, tense, or subject-object roles.", + "English near-misses such as 'How many women will look after this man?' omit 'old' and reverse the direction of looking after; they are correctly rejected." + ] + }, + "opd_exact_review": [ + { + "record_id": "iol-2016-individual-p5-sub-a-atomic-a.1", + "sample_indices": [5], + "decision": "reject", + "reason": "The Jaqaru output eventually reaches the correct translation but repeatedly proposes mutually inconsistent suffix analyses and false generalizations before restating the target." + }, + { + "record_id": "iol-2018-individual-p2-sub-a-atomic-a.1", + "sample_indices": [0, 4, 5, 6, 7], + "decision": "reject", + "reason": "All five Hakhun outputs contain only the final answer and no derivation." + } + ], + "target_facts_exact_review": [ + { + "record_id": "iol-2016-individual-p5-sub-a-atomic-a.1", + "sample_indices": [7], + "decision": "reject", + "reason": "The Jaqaru output reaches the correct translation only after a long contradictory analysis that repeatedly misidentifies the possessive, locative, and interrogative suffixes." + }, + { + "record_id": "iol-2018-individual-p2-sub-a-atomic-a.1", + "sample_indices": [0, 5, 6], + "decision": "reject", + "reason": "All three Hakhun outputs contain only the final answer and no derivation." + } + ], + "checked_derivation_exact_review": [ + { + "record_id": "iol-2016-individual-p5-sub-a-atomic-a.1", + "sample_indices": [0, 6, 7], + "decision": "reject", + "reason": "All three Jaqaru outputs reach the right translation after contradictory suffix analyses, false generalizations, or unsupported claims about the interrogative and locative markers." + }, + { + "record_id": "iol-2018-individual-p2-sub-a-atomic-a.1", + "sample_indices": [0, 4, 5, 6, 7], + "decision": "reject", + "reason": "All five Hakhun outputs contain only the final answer and no derivation." + } + ], + "decision": "Direct on-policy distillation can provide a dense learning signal when strict rewards are all zero, so it is not blocked by the accuracy-RL gate. A corrected four-condition diagnostic showed that the checked-reference update depends strongly on the raw question, so reference subtraction was not warranted. Even so, expanding normalized forward-KL training to all 61 eligible raw trajectories, 12 sources, 15,499 tokens, and 16 optimizer updates produced zero held-out exact answers and no valid exact rationale. A later compatibility audit found 0.869 mean top-16 overlap and 99.4% acceptance of sampled student tokens by the privileged teacher; pruning would retain every token. Do not run another pass with this same-model teacher. Test a stronger tokenizer-compatible teacher on a small source-balanced prefix set before any further OPD training." +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/v14_selected_sft_bootstrap_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/v14_selected_sft_bootstrap_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..cbeb42b2cccf029b736116c6b7d932d47b7eb282 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/v14_selected_sft_bootstrap_audit.json @@ -0,0 +1,96 @@ +{ + "schema_version": "v14_selected_sft_bootstrap_audit_v1", + "reviewed_at_utc": "2026-07-12T02:57:00Z", + "training": { + "model": "Qwen/Qwen3-4B-Instruct-2507", + "data": "data/sft/ioling_selected_student_traces_v6_expanded_clean/train.jsonl", + "rows": 123, + "epochs": 2, + "learning_rate": 0.000005, + "effective_batch_size": 8, + "max_length": 4096, + "lora_rank": 32, + "wandb_run": "https://wandb.ai/alexgurung/ioling-research/runs/tsz84otq" + }, + "reports": { + "fresh_base_validation": "reports/qwen3_4b_instruct_base_v14_val_pass8.json", + "selected_sft_validation": "reports/sft_selected_v6_e2_v14_val_pass8.json", + "selected_sft_train": "reports/sft_selected_v6_e2_v14_train_pass8.json", + "selected_sft_one_per_source": "reports/sft_selected_v6_e2_v14_train_one_per_source_pass8.json" + }, + "decision_rule": "A reasoning trace is accepted only if the final answer is exact and every supporting claim is true, grounded in the displayed problem or verified prior answers, and sufficient to derive the result. An answer-only output is not an accepted reasoning trace.", + "summary": { + "fresh_base_validation_samples": 192, + "fresh_base_validation_exact_samples": 0, + "fresh_base_validation_visible_finals_reviewed": 79, + "selected_sft_validation_samples": 192, + "selected_sft_validation_exact_samples": 0, + "selected_sft_validation_visible_finals_reviewed": 175, + "selected_sft_train_samples": 984, + "selected_sft_train_exact_samples": 12, + "selected_sft_train_exact_records": 4, + "selected_sft_train_exact_sources": 4, + "selected_sft_one_per_source_samples": 120, + "selected_sft_one_per_source_exact_samples": 5, + "selected_sft_one_per_source_exact_records": 2, + "exact_reasoning_traces_reviewed": 17, + "accepted_reasoning_traces": 0, + "rejected_reasoning_traces": 17, + "rl_gate": "closed" + }, + "validation_review": { + "decision": "no_scorer_false_negatives_found", + "scope": "Every visible final box from both fresh-base and selected-SFT validation runs was compared by record with the verified canonical answer and aliases.", + "findings": [ + "Nahuatl and Arammba outputs were incomplete or arithmetically wrong numeral forms.", + "Kunuz Nubian outputs changed the verb, argument roles, number, or recipient.", + "Kilivila outputs changed the predicate, noun class, quantity, tense, or subject-object assignment.", + "The repeated 'How many women will look after this man?' candidate omits 'old' and reverses who looks after whom; it is correctly rejected." + ] + }, + "full_train_exact_review": [ + { + "record_id": "iol-2016-individual-p5-sub-a-atomic-a.2", + "source_problem_id": "2016-individual-5", + "sample_indices": [4, 6], + "decision": "reject", + "reason": "Both Jaqaru traces eventually identify his field plus too, but they invent forms, conflate case and question suffixes, and make false segmentations before reaching the exact box." + }, + { + "record_id": "iol-2017-individual-p3-sub-a-atomic-a.2", + "source_problem_id": "2017-individual-3", + "sample_indices": [0, 1, 2, 3, 6, 7], + "decision": "reject", + "reason": "All six outputs contain only the final answer and no derivation." + }, + { + "record_id": "iol-2018-individual-p2-sub-a-atomic-a.1", + "source_problem_id": "2018-individual-2", + "sample_indices": [1, 4, 5], + "decision": "reject", + "reason": "All three outputs contain only the final answer and no derivation." + }, + { + "record_id": "iol-2018-individual-p3-sub-a-atomic-a.7", + "source_problem_id": "2018-individual-3", + "sample_indices": [6], + "decision": "reject", + "reason": "The Terena trace eventually applies nd to t and long-o fronting correctly, but it includes multiple false consonant and vowel comparisons and reverses several person-form pairs." + } + ], + "one_per_source_exact_review": [ + { + "record_id": "iol-2016-individual-p5-sub-a-atomic-a.1", + "sample_indices": [2, 3], + "decision": "reject", + "reason": "The Jaqaru traces reach the right translation but misquote an example and repeatedly conflate possessive, locative, and interrogative suffixes." + }, + { + "record_id": "iol-2018-individual-p2-sub-a-atomic-a.1", + "sample_indices": [0, 5, 6], + "decision": "reject", + "reason": "The outputs contain only the final answer and no derivation." + } + ], + "decision": "Two-epoch low-learning-rate SFT on concise manually written traces substantially improves formatting and termination, but it produces no held-out exact answer and no manually valid exact reasoning trace. Do not start accuracy-only RL or verifier-grounded online distillation from this checkpoint." +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/v14_transfer_and_scaffold_trace_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/v14_transfer_and_scaffold_trace_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..0cf25a43175f8878463a1c73199862b4447f82ef --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/v14_transfer_and_scaffold_trace_audit.json @@ -0,0 +1,129 @@ +{ + "schema_version": "v14_transfer_and_scaffold_trace_audit_v1", + "reviewed_at_utc": "2026-07-12T02:20:00Z", + "decision_rule": "Accept a generated trace only when its final answer is exact, every supporting claim is consistent with the displayed examples and checked rules, the target is derived rather than cited, and no privileged answer is used as evidence. A correct box does not rescue a false or unsupported derivation.", + "reports": { + "matched_validation": "reports/sft_rule_rich_v3_15sources_val_pass8.json", + "source_seen_probe": "reports/sft_rule_rich_v3_15sources_train_one_per_source_pass8.json", + "base_unseen_v14_sources": "reports/qwen3_4b_base_unseen_v14_sources_pass8.json", + "v2_unseen_v14_sources": "reports/sft_rule_rich_v2_unseen_v14_sources_pass8.json", + "manual_rules": "reports/answer_given_rationale/Qwen_Qwen3-4B-Instruct-2507__v14_exact_trace_repair_manual_rules_n8.json", + "manual_derivation": "reports/answer_given_rationale/Qwen_Qwen3-4B-Instruct-2507__v14_exact_trace_repair_manual_derivation_n8.json", + "hakhun_manual_derivation": "reports/answer_given_rationale/Qwen_Qwen3-4B-Instruct-2507__v14_hakhun_manual_derivation_n4.json" + }, + "summary": { + "matched_validation_samples": 192, + "matched_validation_exact_samples": 0, + "matched_validation_visible_finals_reviewed": 159, + "source_seen_samples": 120, + "source_seen_exact_samples": 1, + "base_unseen_samples": 280, + "base_unseen_exact_samples": 7, + "v2_unseen_samples": 280, + "v2_unseen_exact_samples": 2, + "answer_conditioned_samples": 104, + "answer_conditioned_exact_samples": 104, + "raw_exact_traces_reviewed": 114, + "raw_traces_accepted": 0, + "raw_traces_rejected": 114, + "rl_gate": "closed" + }, + "matched_validation_review": { + "decision": "no_scorer_false_negatives_found", + "scope": "Every non-empty visible final line was read and compared with its record. The closest Koryak, Kunuz Nubian, Nahuatl, Arammba, and Kilivila candidates were also checked against the accepted aliases.", + "notable_errors": [ + { + "source_problem_id": "2015-individual-1", + "pattern": "invented or arithmetically inconsistent numeral compounds", + "decision": "incorrect" + }, + { + "source_problem_id": "2016-individual-3", + "pattern": "wrong verb, argument, number, or recipient", + "decision": "incorrect" + }, + { + "source_problem_id": "2021-individual-3", + "pattern": "How many women will look after this/that man?", + "decision": "incorrect: omits old and reverses who looks after whom" + } + ] + }, + "source_seen_exact_review": [ + { + "record_id": "iol-2016-individual-p5-sub-a-atomic-a.1", + "sample_index": 4, + "decision": "reject", + "reason": "The box is exact, but the preceding text is unrelated invented prose and contains no derivation from the Nen examples." + } + ], + "unseen_exact_review": { + "base_model": [ + { + "record_id": "iol-2017-individual-p3-sub-a-atomic-a.2", + "sample_indices": [0, 1, 3], + "decision": "reject", + "reason": "All three reach the copied example translation while assigning false meanings or syntactic roles to Kimbundu forms." + }, + { + "record_id": "iol-2017-individual-p3-sub-a-atomic-a.3", + "sample_indices": [5, 7], + "decision": "reject", + "reason": "The core first-person and dance analysis eventually appears, but each trace contains contradictory lexical guesses and unsupported claims." + }, + { + "record_id": "iol-2018-individual-p2-sub-a-atomic-a.5", + "sample_indices": [7], + "decision": "reject", + "reason": "The final composition is right, but the trace first assigns incorrect person, tense, or agreement facts before correcting itself." + }, + { + "record_id": "iol-2018-individual-p3-sub-a-atomic-a.5", + "sample_indices": [1], + "decision": "reject", + "reason": "The output guesses the right form while making false claims about acute versus circumflex vowels and consonant changes." + } + ], + "rule_rich_v2": [ + { + "record_id": "iol-2018-individual-p2-sub-a-atomic-a.1", + "sample_indices": [0], + "decision": "reject", + "reason": "The rationale is invented grammatical jargon with no valid alignment to the Hakhun examples." + }, + { + "record_id": "iol-2018-individual-p2-sub-b-atomic-b.2", + "sample_indices": [1], + "decision": "reject", + "reason": "The box is exact, but the trace misidentifies pronouns, predicate pieces, and the agreement complex." + } + ] + }, + "answer_conditioned_review": [ + { + "condition": "checked source rules plus known final answer", + "records": 4, + "samples": 32, + "exact_boxes": 32, + "accepted_raw_traces": 0, + "reason": "Every trace invented at least one lexical, example-alignment, person, tense, or sound-change claim." + }, + { + "condition": "checked target derivation plus known final answer", + "records": 4, + "samples": 32, + "exact_boxes": 32, + "accepted_raw_traces": 0, + "reason": "Target-specific working reduced the errors, but all raw traces still contained a false contrast, malformed rule, or unsupported citation." + }, + { + "condition": "checked target derivation on all Hakhun targets", + "records": 10, + "samples": 40, + "exact_boxes": 40, + "accepted_raw_traces": 0, + "reason": "The best traces were close, but each either misquoted an example, compared present with past markers incorrectly, or grounded a claim only in the target itself." + } + ], + "decision": "The v14 data and deterministic answer scorer are suitable for controlled exact-answer experiments, but these generated rationales are not suitable as automatic SFT labels. Continue training only from manually written or manually corrected completions. Do not start accuracy-only RL from the v3 checkpoint." +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/validation_composition_cards_v1.json b/benchmark/IOL/ioling_hf/data/manual_overrides/validation_composition_cards_v1.json new file mode 100644 index 0000000000000000000000000000000000000000..4f35caa509bc444d4d6985e3d00b4498f733b95a --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/validation_composition_cards_v1.json @@ -0,0 +1,130 @@ +{ + "schema_version": "ioling_validation_composition_cards_v1", + "reviewed_at_utc": "2026-07-12", + "privilege_level": "answer-derived target decomposition without an assembled final answer", + "review_method": "Every component was manually transcribed from the rendered official English solution pages 2015:1-2, 2016:3-4, and 2021:2-3 and checked against the atomic prompt.", + "records": { + "iol-2015-individual-p1-sub-b-atomic-b.1": [ + "Use the decomposition 42 = 2×20 + 2.", + "The 2 multiplier before a power of 20 is öm; 20 is pöhualli; standalone 2 is öme.", + "The additive linker is -oM- and M is m before m, p, or a vowel." + ], + "iol-2015-individual-p1-sub-b-atomic-b.2": [ + "Use the decomposition 494 = 1×400 + 4×20 + 10 + 4.", + "The 1 multiplier is ceM, the 4 multiplier is näuh, 400 is tzontli, and 20 is pöhualli.", + "Standalone 10 is mahtlactli and standalone 4 is nähui.", + "Join additive parts with -oM-; M is m before m, p, or a vowel and n otherwise." + ], + "iol-2015-individual-p1-sub-c-atomic-c.1": [ + "Use the decomposition 43 = 36 + 6 + 1.", + "In Arammba, 36 is fete, 6 is nimbo, and 1 is ngámbi.", + "An addition with a power of 6 places the higher-power expression before its remainder." + ], + "iol-2015-individual-p1-sub-c-atomic-c.2": [ + "Use the decomposition 569 = 2×216 + 3×36 + 4×6 + 5.", + "In Arammba, 2 is yànparo, 3 is yenówe, 4 is asàr, 5 is tambaroy, 36 is fete, and 216 is tarumba.", + "A coefficient precedes a power word; multiplication by 6 is expressed by placing tàxwo after the coefficient.", + "Place each lower-power remainder after the higher-power expression." + ], + "iol-2016-individual-p3-sub-a-atomic-a.1": [ + "Segment magasi as magas 'thief' plus plural, and it is the subject.", + "argi is the direct object 'us'.", + "Segment ajomirra as present a- + jom 'strike' + plural-object -ir + present -r + third-person-plural subject -a." + ], + "iol-2016-individual-p3-sub-a-atomic-a.2": [ + "ay is the first-person-singular subject 'I'.", + "kanarriːg is the indirect object 'the neighbour', and baːbki is the direct object 'the door'.", + "Segment alletirsi as alle 'repair' + tir 'for a second/third person' + past -s + first-person-singular -i." + ], + "iol-2016-individual-p3-sub-a-atomic-a.3": [ + "hanu is the singular subject 'the donkey'.", + "tirtiːg is tirt 'owner' plus plural and object case.", + "Segment elirsu as el 'find' + plural-object -ir + past -s + third-person-singular -u." + ], + "iol-2016-individual-p3-sub-a-atomic-a.4": [ + "tirti is tirt 'owner' plus plural and is the subject.", + "argi is the indirect object 'us', and kamgi is the direct object 'the camel'.", + "Segment deːccirsa as deːn 'give to first person' + plural-indirect-object -ccir + past -s + third-person-plural -a." + ], + "iol-2016-individual-p3-sub-a-atomic-a.5": [ + "ay is the first-person-singular subject 'I', and darbadki is the singular object 'the chicken'.", + "Segment bijaːndi as future bi- + jaːn 'buy' + future -r, which becomes d after n, + first-person-singular -i." + ], + "iol-2016-individual-p3-sub-b-atomic-b.1": [ + "Use S–O′–O–V order.", + "kanarriː 'neighbour' takes plural -ːcci as the subject; tirt 'owner' takes object -ki; beyyeː 'necklace' takes object -ːg.", + "The present verb 'give to the owner' is a- + tir + present -r + third-person-plural -a." + ], + "iol-2016-individual-p3-sub-b-atomic-b.2": [ + "Use S–O′–O–V order.", + "jahal is 'young man'; argi is the indirect object 'us'; wal 'dog' takes object -gi.", + "The past verb is jaːn 'buy' + deːn 'for first person' + plural-indirect-object -ccir + past -s + third-person-singular -u." + ], + "iol-2016-individual-p3-sub-b-atomic-b.3": [ + "Use S–O–V order: ar is the subject 'we' and man 'he/him' takes object -gi.", + "The future verb is bi- + maːg 'steal' + future -r + first-person-plural -u." + ], + "iol-2016-individual-p3-sub-b-atomic-b.4": [ + "Use S–O–V order.", + "tirt 'owner' takes plural -i as the subject; magas 'thief' takes plural -i followed by object -ːg.", + "The past verb is jom 'strike' + plural-object -ir + past -s + third-person-plural -a." + ], + "iol-2016-individual-p3-sub-b-atomic-b.5": [ + "Use S–O′–O–V order.", + "wal 'dog' takes plural -i as subject; sarkaːy 'coward' takes object -gi; darbad 'chicken' takes plural -i plus object -ːg.", + "The past verb is el 'find' + tir 'for a second/third person' + past -s + third-person-plural -a." + ], + "iol-2021-individual-p3-sub-a-atomic-a.1": [ + "Navila vivila is the queried object 'how many women'.", + "biyamata is bi- future plus yamata 'look after'.", + "tomwaya mtona is the subject 'this old man'; interrogative order is Q–V–X." + ], + "iol-2021-individual-p3-sub-a-atomic-a.2": [ + "bikamkwamsi is bi- future + kamkwam 'eat' + plural-subject -si.", + "kweyu is kwe- thing class plus -yu 'two', so kweyu vivila is not one noun phrase.", + "vivila minasina is the subject 'these women'; ordinary order is V–O–S." + ], + "iol-2021-individual-p3-sub-a-atomic-a.3": [ + "Amagudina gwadi is the interrogative phrase 'which child'.", + "lekota is le- past plus kota 'arrive'; use Q–V order." + ], + "iol-2021-individual-p3-sub-a-atomic-a.4": [ + "Tevila tauwau is 'how many men'.", + "bigisesi is bi- future + gisi 'see' + plural-subject -si.", + "gugwadi gudigasisi is 'wild children'.", + "Both noun phrases are plural, so the morphology permits either one to be the subject; give both role assignments." + ], + "iol-2021-individual-p3-sub-a-atomic-a.5": [ + "legisesi is le- past + gisi 'see' + plural-subject -si.", + "ketala waga is the object 'one canoe'.", + "vivila minasiwena is the subject 'those women'; ordinary order is V–O–S." + ], + "iol-2021-individual-p3-sub-b-atomic-b.1": [ + "Use Q–V–X order.", + "'How many canoes' is ke-vila followed by waga.", + "'saw' with a plural subject is le- + gisi + -si; 'old women' is nunumwaya; 'those' agreeing with women is minasiwena." + ], + "iol-2021-individual-p3-sub-b-atomic-b.2": [ + "Use V–O–S order.", + "'will look after' with a plural subject is bi- + yamata + -si.", + "The object components are gwadi 'child', magudina 'this' in the child class, and gudikabitam 'clever' in the child class.", + "The subject components are tevasi 'four' in the men class, dimdim 'white', and mtosina 'these men'." + ], + "iol-2021-individual-p3-sub-b-atomic-b.3": [ + "Use Q–V–X order.", + "The queried subject is gudivila gugwadi 'how many children'.", + "'will eat' with a plural subject is bi- + kamkwam + -si; the remaining noun phrase is bunukwa minasina 'these pigs'." + ], + "iol-2021-individual-p3-sub-b-atomic-b.4": [ + "Use Q–V–X order.", + "The queried subject is aminana vivila 'which woman'.", + "'caught' is le- + bani; the object components are yena 'fish', minasiwena 'those', and namanabweta 'beautiful' with animal-class agreement." + ], + "iol-2021-individual-p3-sub-b-atomic-b.5": [ + "Use V–O–S order.", + "'saw' with a plural subject is le- + gisi + -si.", + "The object is tomwaya mtowena 'that old man'.", + "The subject components are nayu 'two' in the animal class, ka’ukwa 'dog', and nagasisi 'wild' with plural animal-class agreement." + ] + } +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/validation_microsteps_v1.json b/benchmark/IOL/ioling_hf/data/manual_overrides/validation_microsteps_v1.json new file mode 100644 index 0000000000000000000000000000000000000000..40c2f990f23b45948b7a01bcb51bd0ef67b973d5 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/validation_microsteps_v1.json @@ -0,0 +1,65 @@ +{ + "schema_version": "ioling_validation_microsteps_v1", + "reviewed_at_utc": "2026-07-12", + "review_method": "Manually transcribed and checked against rendered official English solution pages.", + "sources": { + "2015-individual-1": { + "solution_pdf": "data/raw/pdfs/iol-2015-indiv-sol.en-gb.pdf", + "solution_pages_1_indexed": [1, 2], + "tasks": [ + {"id": "nahuatl-base-20", "type": "lexical_mapping", "question": "What value does the Nahuatl numeral pöhualli represent?", "answer": "20"}, + {"id": "nahuatl-base-400", "type": "lexical_mapping", "question": "What value does the Nahuatl numeral tzontli represent?", "answer": "400"}, + {"id": "nahuatl-base-8000", "type": "lexical_mapping", "question": "What value does the Nahuatl numeral xiquipilli represent?", "answer": "8000"}, + {"id": "nahuatl-multiplier-2", "type": "morpheme_mapping", "question": "Which Nahuatl multiplier form represents 2 before a power-of-20 numeral?", "answer": "öm"}, + {"id": "nahuatl-linker-rule", "type": "allomorph_rule", "question": "In an additive Nahuatl numeral, when is the linker M realized as m rather than n?", "answer": "before m, p, or a vowel"}, + {"id": "nahuatl-494-decomposition", "type": "target_decomposition", "question": "Decompose 494 into the powers and small addends used by the Nahuatl system.", "answer": "1×400+4×20+10+4"}, + {"id": "arammba-base", "type": "system_rule", "question": "What is the multiplicative base of the Arammba numeral system in this problem?", "answer": "6"}, + {"id": "arammba-unit-1", "type": "lexical_mapping", "question": "Which Arammba word represents 1?", "answer": "ngámbi"}, + {"id": "arammba-power-36", "type": "lexical_mapping", "question": "Which Arammba word represents 6² = 36?", "answer": "fete"}, + {"id": "arammba-power-216", "type": "lexical_mapping", "question": "Which Arammba word represents 6³ = 216?", "answer": "tarumba"}, + {"id": "arammba-569-decomposition", "type": "target_decomposition", "question": "Decompose 569 into the base-6 powers and remainder terms used by the Arammba system.", "answer": "2×216+3×36+4×6+5"} + ] + }, + "2016-individual-3": { + "solution_pdf": "data/raw/pdfs/iol-2016-indiv-sol.en.pdf", + "solution_pages_1_indexed": [3, 4], + "tasks": [ + {"id": "kunuz-order", "type": "word_order", "question": "Write the Kunuz Nubian constituent order using S for subject, O' for indirect object, O for direct object, and V for predicate.", "answer": "S (O') O V"}, + {"id": "kunuz-plural-after-consonant", "type": "allomorph_rule", "question": "Which plural suffix follows a consonant in the Kunuz Nubian data?", "answer": "-i"}, + {"id": "kunuz-plural-after-vowel", "type": "allomorph_rule", "question": "Which plural suffix follows a vowel in the Kunuz Nubian data?", "answer": "-ːcci"}, + {"id": "kunuz-object-case-after-vowel", "type": "allomorph_rule", "question": "Which indirect/direct-object case suffix follows a vowel?", "answer": "-ːg"}, + {"id": "kunuz-object-case-after-sonorant", "type": "allomorph_rule", "question": "Which indirect/direct-object case suffix follows a sonorant consonant?", "answer": "-gi"}, + {"id": "kunuz-object-case-after-obstruent", "type": "allomorph_rule", "question": "Which indirect/direct-object case suffix follows an obstruent consonant?", "answer": "-ki"}, + {"id": "kunuz-present-prefix", "type": "morpheme_mapping", "question": "Which Kunuz Nubian verb prefix marks present tense?", "answer": "a-"}, + {"id": "kunuz-future-prefix", "type": "morpheme_mapping", "question": "Which Kunuz Nubian verb prefix marks future tense?", "answer": "bi-"}, + {"id": "kunuz-benefactive-first", "type": "morpheme_mapping", "question": "Which verbal element means 'for/to somebody' when that person is first person?", "answer": "deːn"}, + {"id": "kunuz-benefactive-nonfirst", "type": "morpheme_mapping", "question": "Which verbal element means 'for/to somebody' when that person is second or third person?", "answer": "tir"}, + {"id": "kunuz-past-suffix", "type": "morpheme_mapping", "question": "Which Kunuz Nubian suffix marks past tense after the object-agreement slot?", "answer": "-s"}, + {"id": "kunuz-third-plural-subject", "type": "morpheme_mapping", "question": "Which final verb suffix marks a third-person plural subject?", "answer": "-a"} + ] + }, + "2021-individual-3": { + "solution_pdf": "data/raw/pdfs/iol-2021-indiv-sol.en.pdf", + "solution_pages_1_indexed": [2, 3], + "tasks": [ + {"id": "kilivila-clause-order", "type": "word_order", "question": "Write the ordinary Kilivila clause order using V for verb, O for optional object, and S for subject.", "answer": "V (O) S", "aliases": ["VOS"]}, + {"id": "kilivila-question-order", "type": "word_order", "question": "Write the Kilivila interrogative order using Q for interrogative element, V for verb, and X for the remaining constituent.", "answer": "Q V X", "aliases": ["QVX"]}, + {"id": "kilivila-noun-phrase-order", "type": "word_order", "question": "After an optional 'which' or quantity element, what is the order of noun, optional demonstrative, and optional adjective? Use N, D, and A.", "answer": "N (D) (A)", "aliases": ["NDA"]}, + {"id": "kilivila-past", "type": "morpheme_mapping", "question": "Which Kilivila verb prefix marks past tense?", "answer": "le-"}, + {"id": "kilivila-future", "type": "morpheme_mapping", "question": "Which Kilivila verb prefix marks future tense?", "answer": "bi-"}, + {"id": "kilivila-plural-subject", "type": "morpheme_mapping", "question": "Which Kilivila verb suffix marks a plural subject?", "answer": "-si"}, + {"id": "kilivila-man-plural", "type": "lexical_mapping", "question": "What is the plural of Kilivila tau 'man'?", "answer": "tauwau"}, + {"id": "kilivila-child-plural", "type": "lexical_mapping", "question": "What is the plural of Kilivila gwadi 'child'?", "answer": "gugwadi"}, + {"id": "kilivila-old-woman-plural", "type": "lexical_mapping", "question": "What is the plural of Kilivila namwaya 'old woman'?", "answer": "nunumwaya", "aliases": ["namwaya becomes nunumwaya"]}, + {"id": "kilivila-men-class", "type": "class_mapping", "question": "Which class prefixes mark men, using the quantity form first and the other agreement form second?", "answer": "te-, to-"}, + {"id": "kilivila-women-animal-class", "type": "class_mapping", "question": "Which class prefix marks women and animals?", "answer": "na-"}, + {"id": "kilivila-children-class", "type": "class_mapping", "question": "Which class prefix marks children?", "answer": "gudi-"}, + {"id": "kilivila-canoe-class", "type": "class_mapping", "question": "Which class prefix marks canoes?", "answer": "ke-"}, + {"id": "kilivila-things-class", "type": "class_mapping", "question": "Which class prefix marks things such as stones?", "answer": "kwe-"}, + {"id": "kilivila-how-many", "type": "quantity_rule", "question": "How is 'how many' formed from a Kilivila class prefix Cl?", "answer": "Cl-vila"}, + {"id": "kilivila-two", "type": "quantity_rule", "question": "How is the quantity 2 formed from a Kilivila class prefix Cl?", "answer": "Cl-yu"}, + {"id": "kilivila-four", "type": "quantity_rule", "question": "How is the quantity 4 formed from a Kilivila class prefix Cl?", "answer": "Cl-vasi"} + ] + } + } +} diff --git a/benchmark/IOL/ioling_hf/data/manual_overrides/verified_distillation_v1_audit.json b/benchmark/IOL/ioling_hf/data/manual_overrides/verified_distillation_v1_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..0792a7391121cbda0e90c5b1f56df487d287bf17 --- /dev/null +++ b/benchmark/IOL/ioling_hf/data/manual_overrides/verified_distillation_v1_audit.json @@ -0,0 +1,79 @@ +{ + "schema_version": "ioling_verified_distillation_audit_v1", + "created_at_utc": "2026-07-17", + "training_set": { + "path": "data/sft/ioling_verified_distillation_v1/train.jsonl", + "records": 32, + "sources": 14, + "raw_training_prompts": 32, + "prompts_containing_privileged_scaffold": 0, + "student_samples_with_checked_facts": 12, + "answer_exposed_student_reconstructions": 10, + "manually_written_from_checked_cards": 10, + "all_completions_manually_reviewed": true, + "all_completions_score_exact": true + }, + "trace_discovery": { + "guided_report": "reports/composition_guided_train_v1_balanced_pass8.json", + "guided_outputs": 256, + "guided_exact_outputs": 44, + "guided_exact_outputs_manually_reviewed": 44, + "guided_reasoning_accepted": 18, + "guided_records_selected": 12, + "answer_reconstruction_v1_report": "reports/composition_answer_reconstruction_v1_balanced_pass2.json", + "answer_reconstruction_v1_outputs_reviewed": 40, + "answer_reconstruction_v1_reasoning_accepted": 5, + "answer_reconstruction_v1_records_selected": 5, + "answer_reconstruction_v2_report": "reports/composition_answer_reconstruction_v2_balanced_pass2.json", + "answer_reconstruction_v2_outputs_reviewed": 30, + "answer_reconstruction_v2_reasoning_accepted": 7, + "answer_reconstruction_v2_records_selected": 5, + "selection_policy": "At most one sampled trace per record; exact matching alone never qualifies a trace. Ten uncovered records received manually written concise derivations." + }, + "training": { + "starting_checkpoint": "checkpoints/qwen3-4b-ioling-microsteps-balanced-v2-e5-merged", + "output_adapter": "checkpoints/qwen3-4b-ioling-balanced-verified-distill-v1", + "epochs": 2, + "optimizer_steps": 8, + "learning_rate": 0.000005, + "effective_batch_size": 8, + "max_length": 2048, + "lora_rank": 16, + "lora_alpha": 32, + "wandb_run": "https://wandb.ai/alexgurung/ioling-research/runs/ivtcm5j7" + }, + "raw_validation": { + "report": "reports/verified_distill_v1_v14_val_pass8.json", + "wandb_run": "https://wandb.ai/alexgurung/ioling-research/runs/c76b0jwu", + "records": 24, + "samples": 192, + "exact_samples": 0, + "records_pass_at_8": 0, + "valid_final_boxes": 185, + "invalid_or_absent_final_boxes": 7, + "truncated_outputs": 5, + "all_outputs_manually_reviewed": 192, + "alternate_format_false_negatives": 0 + }, + "microstep_validation": { + "report": "reports/microsteps/qwen3_4b_verified_distill_v1_validation_pass8.json", + "wandb_run": "https://wandb.ai/alexgurung/ioling-research/runs/dg8i5dlc", + "samples": 320, + "correct_samples": 47, + "tasks_pass_at_8": 13, + "scorer_positive_outputs_manually_reviewed": 47, + "true_positive_outputs": 47, + "false_positive_outputs": 0, + "baseline_correct_samples": 47, + "baseline_tasks_pass_at_8": 14, + "newly_passed_tasks": [], + "lost_tasks": [ + "arammba-power-36" + ], + "sample_count_changes": { + "arammba-power-36": -1, + "kilivila-man-plural": 1 + } + }, + "decision": "Do not replace the balanced microstep checkpoint and do not add more epochs. Verified guided continuations can be elicited, but this 32-record raw-prompt continuation SFT did not transfer to source-disjoint complete solutions or expand microstep task coverage." +} diff --git a/benchmark/IOL/ioling_hf/evals/results/Qwen__Qwen3-4B-Instruct-2507.scores.jsonl b/benchmark/IOL/ioling_hf/evals/results/Qwen__Qwen3-4B-Instruct-2507.scores.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..97694c00425591d9e64b9fdc3d2ba295b3d0e5d2 --- /dev/null +++ b/benchmark/IOL/ioling_hf/evals/results/Qwen__Qwen3-4B-Instruct-2507.scores.jsonl @@ -0,0 +1,3 @@ +{"record_id": "iol-2006-individual-p1", "score": 0.0, "max_score": 9.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["assignment_1.1", "assignment_1.2", "assignment_1.3", "assignment_1.4", "assignment_2.1", "assignment_3.1", "assignment_3.2", "assignment_3.3", "assignment_3.4"], "unit_results": [{"unit_id": "assignment_1.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 90.0, "full_output_similarity": 90.0}, {"unit_id": "assignment_1.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 81.818, "full_output_similarity": 81.818}, {"unit_id": "assignment_1.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 56.818, "full_output_similarity": 56.818}, {"unit_id": "assignment_1.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 85.714, "full_output_similarity": 85.714}, {"unit_id": "assignment_2.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 61.111, "full_output_similarity": 61.111}, {"unit_id": "assignment_3.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 65.116, "full_output_similarity": 65.116}, {"unit_id": "assignment_3.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 79.167, "full_output_similarity": 79.167}, {"unit_id": "assignment_3.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 84.615, "full_output_similarity": 84.615}, {"unit_id": "assignment_3.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.727, "full_output_similarity": 72.727}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2006-individual-p1-sub-assignment_1", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["assignment_1.1", "assignment_1.2", "assignment_1.3", "assignment_1.4"], "unit_results": [{"unit_id": "assignment_1.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 80.0}, {"unit_id": "assignment_1.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 78.788}, {"unit_id": "assignment_1.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 59.091}, {"unit_id": "assignment_1.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 85.714}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2006-individual-p1-sub-assignment_2", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["assignment_2.1"], "unit_results": [{"unit_id": "assignment_2.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 63.889, "full_output_similarity": 63.889}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} diff --git a/benchmark/IOL/ioling_hf/evals/results/Qwen__Qwen3-4B-Instruct-2507__diverse5.scores.jsonl b/benchmark/IOL/ioling_hf/evals/results/Qwen__Qwen3-4B-Instruct-2507__diverse5.scores.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bc85a7d956fc01b55f87077c24b2a72bb8d3c02e --- /dev/null +++ b/benchmark/IOL/ioling_hf/evals/results/Qwen__Qwen3-4B-Instruct-2507__diverse5.scores.jsonl @@ -0,0 +1,5 @@ +{"record_id": "iol-2006-individual-p1-sub-assignment_1", "score": 1.0, "max_score": 4.0, "score_fraction": 0.25, "verdict": "partial", "matched_units": ["assignment_1.1"], "missed_units": ["assignment_1.2", "assignment_1.3", "assignment_1.4"], "unit_results": [{"unit_id": "assignment_1.1", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 92.5, "full_output_similarity": 92.5}, {"unit_id": "assignment_1.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.727, "full_output_similarity": 72.727}, {"unit_id": "assignment_1.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 56.818, "full_output_similarity": 56.818}, {"unit_id": "assignment_1.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 85.714, "full_output_similarity": 85.714}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2011-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.5, "full_output_similarity": 48.5}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2015-individual-p5-sub-b", "score": 0.0, "max_score": 9.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["b.1", "b.2", "b.3", "b.4", "b.5", "b.6", "b.7", "b.8", "b.9"], "unit_results": [{"unit_id": "b.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 22.857, "full_output_similarity": 77.778}, {"unit_id": "b.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 22.222, "full_output_similarity": 82.609}, {"unit_id": "b.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 20.0, "full_output_similarity": 77.778}, {"unit_id": "b.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.0, "full_output_similarity": 75.0}, {"unit_id": "b.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 22.222, "full_output_similarity": 75.0}, {"unit_id": "b.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 25.0, "full_output_similarity": 75.862}, {"unit_id": "b.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 22.222, "full_output_similarity": 80.0}, {"unit_id": "b.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 24.242, "full_output_similarity": 73.333}, {"unit_id": "b.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 22.222, "full_output_similarity": 77.778}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2021-individual-p2-sub-a", "score": 0.0, "max_score": 9.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 50.0}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.0, "full_output_similarity": 70.0}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.0, "full_output_similarity": 75.0}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 89.286, "full_output_similarity": 89.286}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.606, "full_output_similarity": 60.606}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.222, "full_output_similarity": 72.222}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.968, "full_output_similarity": 70.968}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 80.556, "full_output_similarity": 80.556}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2025-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 32.738, "full_output_similarity": 32.738}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} diff --git a/benchmark/IOL/ioling_hf/evals/results/Qwen__Qwen3-4B-Instruct-2507__strict30.scores.jsonl b/benchmark/IOL/ioling_hf/evals/results/Qwen__Qwen3-4B-Instruct-2507__strict30.scores.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..42790640a1c70abb186ca41f2d936dd5163a2655 --- /dev/null +++ b/benchmark/IOL/ioling_hf/evals/results/Qwen__Qwen3-4B-Instruct-2507__strict30.scores.jsonl @@ -0,0 +1,30 @@ +{"record_id": "iol-2006-individual-p1-sub-assignment_1", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["assignment_1.1", "assignment_1.2", "assignment_1.3", "assignment_1.4"], "unit_results": [{"unit_id": "assignment_1.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 77.5, "full_output_similarity": 77.5}, {"unit_id": "assignment_1.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.727, "full_output_similarity": 72.727}, {"unit_id": "assignment_1.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 56.818, "full_output_similarity": 56.818}, {"unit_id": "assignment_1.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 78.571, "full_output_similarity": 78.571}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2006-individual-p5", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 43.911}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2007-individual-p5", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 62.069, "full_output_similarity": 62.069}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.429, "full_output_similarity": 51.429}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.174, "full_output_similarity": 52.174}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 45.161, "full_output_similarity": 45.161}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2008-individual-p2-sub-b", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["b.1"], "unit_results": [{"unit_id": "b.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 68.0, "full_output_similarity": 68.0}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2008-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.552, "full_output_similarity": 46.552}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2009-individual-p4-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.974, "full_output_similarity": 54.974}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2010-individual-p2-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 82.787, "full_output_similarity": 82.787}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2010-team-p1", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 35.847, "full_output_similarity": 35.847}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2011-individual-p3-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 68.345, "full_output_similarity": 68.345}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2012-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.174, "full_output_similarity": 52.174}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2012-individual-p5-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 83.673}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2013-individual-p3", "score": 0.0, "max_score": 5.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.765, "full_output_similarity": 51.765}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 50.0}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 45.333, "full_output_similarity": 45.333}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.92, "full_output_similarity": 60.92}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2014-individual-p2", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2014-individual-p5-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 44.942, "full_output_similarity": 44.942}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2015-individual-p3-sub-a", "score": 0.0, "max_score": 5.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 73.333, "full_output_similarity": 73.333}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 65.823, "full_output_similarity": 65.823}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 57.143, "full_output_similarity": 57.143}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.973, "full_output_similarity": 72.973}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 58.75, "full_output_similarity": 58.75}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2016-individual-p1", "score": 0.0, "max_score": 15.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5", "full.6", "full.7", "full.8", "full.9", "full.10", "full.11", "full.12", "full.13", "full.14", "full.15"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 76.596, "full_output_similarity": 76.596}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 82.222, "full_output_similarity": 82.222}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 85.0, "full_output_similarity": 85.0}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.61, "full_output_similarity": 75.61}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.556, "full_output_similarity": 75.556}, {"unit_id": "full.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.732, "full_output_similarity": 70.732}, {"unit_id": "full.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.0, "full_output_similarity": 75.0}, {"unit_id": "full.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 71.795, "full_output_similarity": 71.795}, {"unit_id": "full.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 80.952, "full_output_similarity": 80.952}, {"unit_id": "full.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.0, "full_output_similarity": 70.0}, {"unit_id": "full.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 85.714, "full_output_similarity": 85.714}, {"unit_id": "full.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 79.545, "full_output_similarity": 79.545}, {"unit_id": "full.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 71.429, "full_output_similarity": 71.429}, {"unit_id": "full.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.0, "full_output_similarity": 75.0}, {"unit_id": "full.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.34, "full_output_similarity": 72.34}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2016-individual-p5-sub-a", "score": 0.0, "max_score": 2.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 43.75, "full_output_similarity": 65.217}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 47.368, "full_output_similarity": 68.75}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2017-individual-p2-sub-a", "score": 0.0, "max_score": 16.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12", "a.13", "a.14", "a.15", "a.16"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 62.295, "full_output_similarity": 62.295}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 62.264, "full_output_similarity": 62.264}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 79.167, "full_output_similarity": 79.167}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 73.171, "full_output_similarity": 73.171}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 57.143, "full_output_similarity": 57.143}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 58.0, "full_output_similarity": 58.0}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 73.684, "full_output_similarity": 73.684}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 71.429, "full_output_similarity": 71.429}, {"unit_id": "a.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.222, "full_output_similarity": 72.222}, {"unit_id": "a.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 88.0, "full_output_similarity": 88.0}, {"unit_id": "a.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 80.0, "full_output_similarity": 80.0}, {"unit_id": "a.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 73.171, "full_output_similarity": 73.171}, {"unit_id": "a.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.465, "full_output_similarity": 60.465}, {"unit_id": "a.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 61.364, "full_output_similarity": 61.364}, {"unit_id": "a.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 76.667, "full_output_similarity": 76.667}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2017-team-p1", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 63.082, "full_output_similarity": 63.082}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2018-individual-p4-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 50.0}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2019-individual-p2-sub-a", "score": 0.0, "max_score": 17.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12", "a.13", "a.14", "a.15", "a.16", "a.17"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 74.419, "full_output_similarity": 74.419}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.758, "full_output_similarity": 75.758}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 71.429, "full_output_similarity": 71.429}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 67.5, "full_output_similarity": 67.5}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 61.538, "full_output_similarity": 61.538}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 65.714, "full_output_similarity": 65.714}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.727, "full_output_similarity": 72.727}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 85.294, "full_output_similarity": 85.294}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 81.818, "full_output_similarity": 81.818}, {"unit_id": "a.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 68.293, "full_output_similarity": 68.293}, {"unit_id": "a.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 80.645, "full_output_similarity": 80.645}, {"unit_id": "a.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}, {"unit_id": "a.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}, {"unit_id": "a.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 85.366, "full_output_similarity": 85.366}, {"unit_id": "a.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 62.963, "full_output_similarity": 62.963}, {"unit_id": "a.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 71.875, "full_output_similarity": 71.875}, {"unit_id": "a.17", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.37, "full_output_similarity": 70.37}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2019-team-p1", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 71.615, "full_output_similarity": 71.615}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2021-individual-p3-sub-a", "score": 1.0, "max_score": 4.0, "score_fraction": 0.25, "verdict": "partial", "matched_units": ["a.1"], "missed_units": ["a.2", "a.3", "a.4"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": true, "match_type": "normalized_final_substring", "final_similarity": 100.0, "full_output_similarity": 100.0}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.87, "full_output_similarity": 60.87}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.381, "full_output_similarity": 52.381}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 71.795, "full_output_similarity": 71.795}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2022-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 83.784, "full_output_similarity": 83.784}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2022-individual-p5-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 58.333}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2023-individual-p3", "score": 0.0, "max_score": 13.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5", "full.6", "full.7", "full.8", "full.9", "full.10", "full.11", "full.12", "full.13"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 87.5, "full_output_similarity": 87.5}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 58.065, "full_output_similarity": 58.065}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 55.556, "full_output_similarity": 55.556}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 69.231, "full_output_similarity": 69.231}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 62.857, "full_output_similarity": 62.857}, {"unit_id": "full.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 74.074, "full_output_similarity": 74.074}, {"unit_id": "full.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 68.75, "full_output_similarity": 68.75}, {"unit_id": "full.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 78.947, "full_output_similarity": 78.947}, {"unit_id": "full.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 83.673, "full_output_similarity": 83.673}, {"unit_id": "full.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.588, "full_output_similarity": 70.588}, {"unit_id": "full.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 67.647, "full_output_similarity": 67.647}, {"unit_id": "full.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.676, "full_output_similarity": 75.676}, {"unit_id": "full.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.0, "full_output_similarity": 75.0}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2024-individual-p1", "score": 1.0, "max_score": 17.0, "score_fraction": 0.058823529411764705, "verdict": "partial", "matched_units": ["full.5"], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.6", "full.7", "full.8", "full.9", "full.10", "full.11", "full.12", "full.13", "full.14", "full.15", "full.16", "full.17"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.538, "full_output_similarity": 50.538}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.875, "full_output_similarity": 46.875}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 62.5, "full_output_similarity": 62.5}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.333, "full_output_similarity": 53.333}, {"unit_id": "full.5", "points": 1.0, "matched": true, "match_type": "normalized_final_substring", "final_similarity": 100.0, "full_output_similarity": 100.0}, {"unit_id": "full.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.571, "full_output_similarity": 53.571}, {"unit_id": "full.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.606, "full_output_similarity": 60.606}, {"unit_id": "full.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.875, "full_output_similarity": 46.875}, {"unit_id": "full.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.684, "full_output_similarity": 48.684}, {"unit_id": "full.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 65.625, "full_output_similarity": 65.625}, {"unit_id": "full.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 62.963, "full_output_similarity": 62.963}, {"unit_id": "full.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 67.568, "full_output_similarity": 67.568}, {"unit_id": "full.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 80.0, "full_output_similarity": 80.0}, {"unit_id": "full.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 68.0, "full_output_similarity": 68.0}, {"unit_id": "full.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 61.29, "full_output_similarity": 61.29}, {"unit_id": "full.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 58.065, "full_output_similarity": 58.065}, {"unit_id": "full.17", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 62.5, "full_output_similarity": 62.5}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2024-individual-p4-sub-a", "score": 0.0, "max_score": 19.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12", "a.13", "a.14", "a.15", "a.16", "a.17", "a.18", "a.19"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.515, "full_output_similarity": 51.515}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.941, "full_output_similarity": 52.941}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 55.556, "full_output_similarity": 55.556}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.976, "full_output_similarity": 60.976}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 50.0}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.515, "full_output_similarity": 51.515}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 61.818, "full_output_similarity": 61.818}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.125, "full_output_similarity": 53.125}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.348, "full_output_similarity": 54.348}, {"unit_id": "a.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.351, "full_output_similarity": 51.351}, {"unit_id": "a.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.545, "full_output_similarity": 54.545}, {"unit_id": "a.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.762, "full_output_similarity": 54.762}, {"unit_id": "a.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.778, "full_output_similarity": 52.778}, {"unit_id": "a.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 56.757, "full_output_similarity": 56.757}, {"unit_id": "a.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 64.865, "full_output_similarity": 64.865}, {"unit_id": "a.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 63.636, "full_output_similarity": 63.636}, {"unit_id": "a.17", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 59.259, "full_output_similarity": 59.259}, {"unit_id": "a.18", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.0, "full_output_similarity": 60.0}, {"unit_id": "a.19", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.846, "full_output_similarity": 53.846}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2025-individual-p2-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 37.234, "full_output_similarity": 37.234}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} +{"record_id": "iol-2025-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 32.738, "full_output_similarity": 32.738}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Instruct-2507"} diff --git a/benchmark/IOL/ioling_hf/evals/results/Qwen__Qwen3-4B-Thinking-2507__diverse5.scores.jsonl b/benchmark/IOL/ioling_hf/evals/results/Qwen__Qwen3-4B-Thinking-2507__diverse5.scores.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c08b36a0db4de2ccc8669d25bb1aaec5845c4047 --- /dev/null +++ b/benchmark/IOL/ioling_hf/evals/results/Qwen__Qwen3-4B-Thinking-2507__diverse5.scores.jsonl @@ -0,0 +1,5 @@ +{"record_id": "iol-2006-individual-p1-sub-assignment_1", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["assignment_1.1", "assignment_1.2", "assignment_1.3", "assignment_1.4"], "unit_results": [{"unit_id": "assignment_1.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 77.5, "full_output_similarity": 77.5}, {"unit_id": "assignment_1.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.727, "full_output_similarity": 72.727}, {"unit_id": "assignment_1.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.545, "full_output_similarity": 54.545}, {"unit_id": "assignment_1.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 85.714, "full_output_similarity": 85.714}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2011-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.5, "full_output_similarity": 52.5}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2015-individual-p5-sub-b", "score": 0.0, "max_score": 9.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["b.1", "b.2", "b.3", "b.4", "b.5", "b.6", "b.7", "b.8", "b.9"], "unit_results": [{"unit_id": "b.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 77.778, "full_output_similarity": 77.778}, {"unit_id": "b.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 82.609, "full_output_similarity": 82.609}, {"unit_id": "b.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 77.778, "full_output_similarity": 77.778}, {"unit_id": "b.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.0, "full_output_similarity": 75.0}, {"unit_id": "b.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.0, "full_output_similarity": 75.0}, {"unit_id": "b.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.862, "full_output_similarity": 75.862}, {"unit_id": "b.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 80.0, "full_output_similarity": 80.0}, {"unit_id": "b.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.0, "full_output_similarity": 70.0}, {"unit_id": "b.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 77.778, "full_output_similarity": 77.778}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2021-individual-p2-sub-a", "score": 1.0, "max_score": 9.0, "score_fraction": 0.1111111111111111, "verdict": "partial", "matched_units": ["a.4"], "missed_units": ["a.1", "a.2", "a.3", "a.5", "a.6", "a.7", "a.8", "a.9"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 50.0}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.0, "full_output_similarity": 70.0}, {"unit_id": "a.4", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 92.857, "full_output_similarity": 92.857}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.606, "full_output_similarity": 60.606}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 73.333, "full_output_similarity": 73.333}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 77.778, "full_output_similarity": 77.778}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 67.742, "full_output_similarity": 67.742}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 77.778, "full_output_similarity": 77.778}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2025-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 31.548, "full_output_similarity": 31.548}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} diff --git a/benchmark/IOL/ioling_hf/evals/results/Qwen__Qwen3-4B-Thinking-2507__strict30.scores.jsonl b/benchmark/IOL/ioling_hf/evals/results/Qwen__Qwen3-4B-Thinking-2507__strict30.scores.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..78157bce1b101b2aacc559d46789c4aa66a85bba --- /dev/null +++ b/benchmark/IOL/ioling_hf/evals/results/Qwen__Qwen3-4B-Thinking-2507__strict30.scores.jsonl @@ -0,0 +1,30 @@ +{"record_id": "iol-2006-individual-p1-sub-assignment_1", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["assignment_1.1", "assignment_1.2", "assignment_1.3", "assignment_1.4"], "unit_results": [{"unit_id": "assignment_1.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 82.5, "full_output_similarity": 82.5}, {"unit_id": "assignment_1.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 63.636, "full_output_similarity": 63.636}, {"unit_id": "assignment_1.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.409, "full_output_similarity": 53.409}, {"unit_id": "assignment_1.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 85.714, "full_output_similarity": 85.714}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2006-individual-p5", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 44.219, "full_output_similarity": 44.219}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2007-individual-p5", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 55.172, "full_output_similarity": 55.172}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.571, "full_output_similarity": 48.571}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 47.826, "full_output_similarity": 47.826}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.387, "full_output_similarity": 48.387}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2008-individual-p2-sub-b", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["b.1"], "unit_results": [{"unit_id": "b.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 47.368, "full_output_similarity": 47.368}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2008-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.621, "full_output_similarity": 48.621}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2009-individual-p4-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.88, "full_output_similarity": 52.88}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2010-individual-p2-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 83.197, "full_output_similarity": 83.197}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2010-team-p1", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 35.741, "full_output_similarity": 35.741}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2011-individual-p3-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 68.345, "full_output_similarity": 68.345}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2012-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.174, "full_output_similarity": 52.174}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2012-individual-p5-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.082, "full_output_similarity": 54.082}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2013-individual-p3", "score": 0.0, "max_score": 5.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 50.0}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.0, "full_output_similarity": 60.0}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.5, "full_output_similarity": 52.5}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.0, "full_output_similarity": 48.0}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 57.471, "full_output_similarity": 57.471}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2014-individual-p2", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2014-individual-p5-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 43.947, "full_output_similarity": 43.947}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2015-individual-p3-sub-a", "score": 0.0, "max_score": 5.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.667, "full_output_similarity": 60.0}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 47.134, "full_output_similarity": 62.025}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 47.143, "full_output_similarity": 54.286}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.649, "full_output_similarity": 81.081}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.229, "full_output_similarity": 67.5}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2016-individual-p1", "score": 0.0, "max_score": 15.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5", "full.6", "full.7", "full.8", "full.9", "full.10", "full.11", "full.12", "full.13", "full.14", "full.15"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.809, "full_output_similarity": 46.809}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 42.222, "full_output_similarity": 42.222}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 47.5, "full_output_similarity": 47.5}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.341, "full_output_similarity": 46.341}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 42.222, "full_output_similarity": 42.222}, {"unit_id": "full.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 43.902, "full_output_similarity": 43.902}, {"unit_id": "full.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.667, "full_output_similarity": 41.667}, {"unit_id": "full.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 43.59, "full_output_similarity": 43.59}, {"unit_id": "full.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 42.857, "full_output_similarity": 42.857}, {"unit_id": "full.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 42.5, "full_output_similarity": 42.5}, {"unit_id": "full.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 42.857, "full_output_similarity": 42.857}, {"unit_id": "full.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 45.455, "full_output_similarity": 45.455}, {"unit_id": "full.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.476, "full_output_similarity": 40.476}, {"unit_id": "full.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 45.833, "full_output_similarity": 45.833}, {"unit_id": "full.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 42.553, "full_output_similarity": 42.553}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2016-individual-p5-sub-a", "score": 0.0, "max_score": 2.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 82.609, "full_output_similarity": 82.609}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 62.5, "full_output_similarity": 62.5}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2017-individual-p2-sub-a", "score": 2.0, "max_score": 16.0, "score_fraction": 0.125, "verdict": "partial", "matched_units": ["a.11", "a.15"], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.12", "a.13", "a.14", "a.16"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 65.574, "full_output_similarity": 65.574}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 62.264, "full_output_similarity": 62.264}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 83.333, "full_output_similarity": 83.333}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.317, "full_output_similarity": 60.317}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 73.171, "full_output_similarity": 73.171}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.0, "full_output_similarity": 54.0}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 73.684, "full_output_similarity": 73.684}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 77.143, "full_output_similarity": 77.143}, {"unit_id": "a.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 77.778, "full_output_similarity": 77.778}, {"unit_id": "a.11", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 96.0, "full_output_similarity": 96.0}, {"unit_id": "a.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 80.0, "full_output_similarity": 80.0}, {"unit_id": "a.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 78.049, "full_output_similarity": 78.049}, {"unit_id": "a.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 69.767, "full_output_similarity": 69.767}, {"unit_id": "a.15", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 93.182, "full_output_similarity": 93.182}, {"unit_id": "a.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 76.667, "full_output_similarity": 76.667}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2017-team-p1", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 62.772, "full_output_similarity": 62.772}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2018-individual-p4-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 43.056, "full_output_similarity": 43.056}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2019-individual-p2-sub-a", "score": 0.0, "max_score": 17.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12", "a.13", "a.14", "a.15", "a.16", "a.17"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 79.07, "full_output_similarity": 79.07}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.758, "full_output_similarity": 75.758}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 74.286, "full_output_similarity": 74.286}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.5, "full_output_similarity": 72.5}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 69.231, "full_output_similarity": 69.231}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 74.286, "full_output_similarity": 74.286}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 81.818, "full_output_similarity": 81.818}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 85.294, "full_output_similarity": 85.294}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 81.818, "full_output_similarity": 81.818}, {"unit_id": "a.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.732, "full_output_similarity": 70.732}, {"unit_id": "a.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 83.871, "full_output_similarity": 83.871}, {"unit_id": "a.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.0, "full_output_similarity": 70.0}, {"unit_id": "a.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.37, "full_output_similarity": 70.37}, {"unit_id": "a.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 80.488, "full_output_similarity": 80.488}, {"unit_id": "a.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}, {"unit_id": "a.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.0, "full_output_similarity": 75.0}, {"unit_id": "a.17", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.37, "full_output_similarity": 70.37}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2019-team-p1", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 60.922}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2021-individual-p3-sub-a", "score": 4.0, "max_score": 4.0, "score_fraction": 1.0, "verdict": "correct", "matched_units": ["a.1", "a.2", "a.3", "a.4"], "missed_units": [], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": true, "match_type": "normalized_final_substring", "final_similarity": 100.0, "full_output_similarity": 100.0}, {"unit_id": "a.2", "points": 1.0, "matched": true, "match_type": "normalized_final_substring", "final_similarity": 100.0, "full_output_similarity": 100.0}, {"unit_id": "a.3", "points": 1.0, "matched": true, "match_type": "normalized_final_substring", "final_similarity": 100.0, "full_output_similarity": 100.0}, {"unit_id": "a.4", "points": 1.0, "matched": true, "match_type": "normalized_final_substring", "final_similarity": 100.0, "full_output_similarity": 100.0}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2022-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 57.895, "full_output_similarity": 86.486}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2022-individual-p5-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2023-individual-p3", "score": 0.0, "max_score": 13.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5", "full.6", "full.7", "full.8", "full.9", "full.10", "full.11", "full.12", "full.13"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 87.5}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 58.065}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 62.963}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 69.231}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 54.286}, {"unit_id": "full.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 66.667}, {"unit_id": "full.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 72.917}, {"unit_id": "full.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 73.684}, {"unit_id": "full.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 65.306}, {"unit_id": "full.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 70.588}, {"unit_id": "full.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 73.529}, {"unit_id": "full.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 78.378}, {"unit_id": "full.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 77.083}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2024-individual-p1", "score": 1.0, "max_score": 17.0, "score_fraction": 0.058823529411764705, "verdict": "partial", "matched_units": ["full.5"], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.6", "full.7", "full.8", "full.9", "full.10", "full.11", "full.12", "full.13", "full.14", "full.15", "full.16", "full.17"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 49.462, "full_output_similarity": 49.462}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 45.833, "full_output_similarity": 45.833}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.0, "full_output_similarity": 70.0}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.333, "full_output_similarity": 53.333}, {"unit_id": "full.5", "points": 1.0, "matched": true, "match_type": "normalized_final_substring", "final_similarity": 100.0, "full_output_similarity": 100.0}, {"unit_id": "full.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 55.357, "full_output_similarity": 55.357}, {"unit_id": "full.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.727, "full_output_similarity": 72.727}, {"unit_id": "full.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 45.833, "full_output_similarity": 45.833}, {"unit_id": "full.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.632, "full_output_similarity": 52.632}, {"unit_id": "full.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 65.625, "full_output_similarity": 65.625}, {"unit_id": "full.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 62.963, "full_output_similarity": 62.963}, {"unit_id": "full.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 67.568, "full_output_similarity": 67.568}, {"unit_id": "full.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 80.0, "full_output_similarity": 80.0}, {"unit_id": "full.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 68.0, "full_output_similarity": 68.0}, {"unit_id": "full.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.968, "full_output_similarity": 70.968}, {"unit_id": "full.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.968, "full_output_similarity": 70.968}, {"unit_id": "full.17", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2024-individual-p4-sub-a", "score": 0.0, "max_score": 19.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12", "a.13", "a.14", "a.15", "a.16", "a.17", "a.18", "a.19"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 57.576, "full_output_similarity": 57.576}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 55.882, "full_output_similarity": 55.882}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 57.447, "full_output_similarity": 57.447}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 58.537, "full_output_similarity": 58.537}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.471, "full_output_similarity": 51.471}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.545, "full_output_similarity": 54.545}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 63.636, "full_output_similarity": 63.636}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.125, "full_output_similarity": 53.125}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.348, "full_output_similarity": 54.348}, {"unit_id": "a.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.351, "full_output_similarity": 51.351}, {"unit_id": "a.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.515, "full_output_similarity": 51.515}, {"unit_id": "a.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.762, "full_output_similarity": 54.762}, {"unit_id": "a.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 55.556, "full_output_similarity": 55.556}, {"unit_id": "a.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.054, "full_output_similarity": 54.054}, {"unit_id": "a.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 62.162, "full_output_similarity": 62.162}, {"unit_id": "a.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 61.818, "full_output_similarity": 61.818}, {"unit_id": "a.17", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 59.259, "full_output_similarity": 59.259}, {"unit_id": "a.18", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 61.667, "full_output_similarity": 61.667}, {"unit_id": "a.19", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.846, "full_output_similarity": 53.846}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2025-individual-p2-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 56.383, "full_output_similarity": 56.383}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} +{"record_id": "iol-2025-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 36.31, "full_output_similarity": 36.31}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "Qwen/Qwen3-4B-Thinking-2507"} diff --git a/benchmark/IOL/ioling_hf/evals/results/microsoft__Phi-4-mini-instruct__strict30.scores.jsonl b/benchmark/IOL/ioling_hf/evals/results/microsoft__Phi-4-mini-instruct__strict30.scores.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d6fc4cb0bbf970b7edf9f9eb6e0ad985ddd09529 --- /dev/null +++ b/benchmark/IOL/ioling_hf/evals/results/microsoft__Phi-4-mini-instruct__strict30.scores.jsonl @@ -0,0 +1,30 @@ +{"record_id": "iol-2006-individual-p1-sub-assignment_1", "score": 1.0, "max_score": 4.0, "score_fraction": 0.25, "verdict": "partial", "matched_units": ["assignment_1.4"], "missed_units": ["assignment_1.1", "assignment_1.2", "assignment_1.3"], "unit_results": [{"unit_id": "assignment_1.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 65.672, "full_output_similarity": 77.5}, {"unit_id": "assignment_1.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 65.455, "full_output_similarity": 66.667}, {"unit_id": "assignment_1.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.273, "full_output_similarity": 55.682}, {"unit_id": "assignment_1.4", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 92.308, "full_output_similarity": 85.714}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2006-individual-p5", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.945, "full_output_similarity": 40.945}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2007-individual-p5", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 44.828, "full_output_similarity": 44.828}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.0, "full_output_similarity": 40.0}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 47.826, "full_output_similarity": 47.826}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.935, "full_output_similarity": 41.935}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2008-individual-p2-sub-b", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["b.1"], "unit_results": [{"unit_id": "b.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 64.912, "full_output_similarity": 64.912}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2008-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 47.931, "full_output_similarity": 47.931}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2009-individual-p4-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 0.0}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2010-individual-p2-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 83.607, "full_output_similarity": 83.607}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2010-team-p1", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 30.476, "full_output_similarity": 30.476}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2011-individual-p3-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 0.0}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2012-individual-p1-sub-a", "score": 1.0, "max_score": 1.0, "score_fraction": 1.0, "verdict": "correct", "matched_units": ["a.1"], "missed_units": [], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 46.377}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2012-individual-p5-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 45.918, "full_output_similarity": 45.918}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2013-individual-p3", "score": 0.0, "max_score": 5.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 50.0}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 37.647, "full_output_similarity": 37.647}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 39.189, "full_output_similarity": 39.189}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 32.0, "full_output_similarity": 32.0}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 36.782, "full_output_similarity": 36.782}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2014-individual-p2", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2014-individual-p5-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.083, "full_output_similarity": 50.083}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2015-individual-p3-sub-a", "score": 0.0, "max_score": 5.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.333, "full_output_similarity": 60.0}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.835, "full_output_similarity": 51.899}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 55.714, "full_output_similarity": 64.286}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.176, "full_output_similarity": 67.568}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.75, "full_output_similarity": 53.75}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2016-individual-p1", "score": 0.0, "max_score": 15.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5", "full.6", "full.7", "full.8", "full.9", "full.10", "full.11", "full.12", "full.13", "full.14", "full.15"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 89.655, "full_output_similarity": 74.468}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 89.655, "full_output_similarity": 77.778}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.846, "full_output_similarity": 85.0}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.276, "full_output_similarity": 78.049}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 81.481, "full_output_similarity": 75.556}, {"unit_id": "full.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 81.481, "full_output_similarity": 75.61}, {"unit_id": "full.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 81.481, "full_output_similarity": 83.333}, {"unit_id": "full.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.667, "full_output_similarity": 79.487}, {"unit_id": "full.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.846, "full_output_similarity": 76.19}, {"unit_id": "full.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 90.0}, {"unit_id": "full.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.846, "full_output_similarity": 88.095}, {"unit_id": "full.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 55.172, "full_output_similarity": 79.545}, {"unit_id": "full.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 59.259, "full_output_similarity": 83.333}, {"unit_id": "full.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 55.172, "full_output_similarity": 85.417}, {"unit_id": "full.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 89.655, "full_output_similarity": 82.979}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2016-individual-p5-sub-a", "score": 0.0, "max_score": 2.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 65.217, "full_output_similarity": 65.217}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 58.824, "full_output_similarity": 58.824}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2017-individual-p2-sub-a", "score": 0.0, "max_score": 16.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12", "a.13", "a.14", "a.15", "a.16"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 47.541, "full_output_similarity": 47.541}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.509, "full_output_similarity": 41.509}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.667, "full_output_similarity": 41.667}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 49.206, "full_output_similarity": 49.206}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.78, "full_output_similarity": 48.78}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.935, "full_output_similarity": 41.935}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.0, "full_output_similarity": 46.0}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 47.368, "full_output_similarity": 47.368}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 62.069, "full_output_similarity": 62.069}, {"unit_id": "a.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 50.0}, {"unit_id": "a.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.0, "full_output_similarity": 52.0}, {"unit_id": "a.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 44.0, "full_output_similarity": 44.0}, {"unit_id": "a.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.659, "full_output_similarity": 53.659}, {"unit_id": "a.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.86, "full_output_similarity": 41.86}, {"unit_id": "a.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 45.455, "full_output_similarity": 45.455}, {"unit_id": "a.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.667, "full_output_similarity": 46.667}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2017-team-p1", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 28.55, "full_output_similarity": 28.55}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2018-individual-p4-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.071, "full_output_similarity": 33.071}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2019-individual-p2-sub-a", "score": 0.0, "max_score": 17.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12", "a.13", "a.14", "a.15", "a.16", "a.17"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 44.186, "full_output_similarity": 44.186}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.515, "full_output_similarity": 51.515}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 68.571, "full_output_similarity": 68.571}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 65.0, "full_output_similarity": 65.0}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.154, "full_output_similarity": 46.154}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.0, "full_output_similarity": 40.0}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.727, "full_output_similarity": 72.727}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 73.529, "full_output_similarity": 73.529}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.515, "full_output_similarity": 51.515}, {"unit_id": "a.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 43.902, "full_output_similarity": 43.902}, {"unit_id": "a.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.839, "full_output_similarity": 54.839}, {"unit_id": "a.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.0, "full_output_similarity": 40.0}, {"unit_id": "a.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.741, "full_output_similarity": 40.741}, {"unit_id": "a.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 43.902, "full_output_similarity": 43.902}, {"unit_id": "a.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 37.037, "full_output_similarity": 37.037}, {"unit_id": "a.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 43.75, "full_output_similarity": 43.75}, {"unit_id": "a.17", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.741, "full_output_similarity": 40.741}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2019-team-p1", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 42.408, "full_output_similarity": 42.408}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2021-individual-p3-sub-a", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 0.0}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 0.0}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 0.0}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 0.0}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2022-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 83.784}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2022-individual-p5-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.667, "full_output_similarity": 41.667}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2023-individual-p3", "score": 0.0, "max_score": 13.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5", "full.6", "full.7", "full.8", "full.9", "full.10", "full.11", "full.12", "full.13"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 37.5, "full_output_similarity": 37.5}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.387, "full_output_similarity": 48.387}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.667, "full_output_similarity": 41.667}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 69.231, "full_output_similarity": 69.231}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 37.143, "full_output_similarity": 37.143}, {"unit_id": "full.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.37, "full_output_similarity": 70.37}, {"unit_id": "full.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.917, "full_output_similarity": 72.917}, {"unit_id": "full.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 76.316, "full_output_similarity": 76.316}, {"unit_id": "full.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 65.306, "full_output_similarity": 65.306}, {"unit_id": "full.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.588, "full_output_similarity": 70.588}, {"unit_id": "full.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 73.529, "full_output_similarity": 73.529}, {"unit_id": "full.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 78.378, "full_output_similarity": 78.378}, {"unit_id": "full.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 79.167, "full_output_similarity": 79.167}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2024-individual-p1", "score": 0.0, "max_score": 17.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5", "full.6", "full.7", "full.8", "full.9", "full.10", "full.11", "full.12", "full.13", "full.14", "full.15", "full.16", "full.17"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.935, "full_output_similarity": 41.935}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.875, "full_output_similarity": 46.875}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.0, "full_output_similarity": 40.0}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 42.667, "full_output_similarity": 42.667}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 55.556, "full_output_similarity": 55.556}, {"unit_id": "full.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 39.286, "full_output_similarity": 39.286}, {"unit_id": "full.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 39.394, "full_output_similarity": 39.394}, {"unit_id": "full.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.875, "full_output_similarity": 46.875}, {"unit_id": "full.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 38.158, "full_output_similarity": 38.158}, {"unit_id": "full.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 43.75, "full_output_similarity": 43.75}, {"unit_id": "full.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.741, "full_output_similarity": 40.741}, {"unit_id": "full.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.541, "full_output_similarity": 40.541}, {"unit_id": "full.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.0, "full_output_similarity": 40.0}, {"unit_id": "full.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.0, "full_output_similarity": 40.0}, {"unit_id": "full.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 38.71, "full_output_similarity": 38.71}, {"unit_id": "full.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.935, "full_output_similarity": 41.935}, {"unit_id": "full.17", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.667, "full_output_similarity": 41.667}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2024-individual-p4-sub-a", "score": 0.0, "max_score": 19.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12", "a.13", "a.14", "a.15", "a.16", "a.17", "a.18", "a.19"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 39.394, "full_output_similarity": 39.394}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.176, "full_output_similarity": 41.176}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 38.889, "full_output_similarity": 38.889}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 58.537, "full_output_similarity": 58.537}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 47.059, "full_output_similarity": 47.059}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 45.455, "full_output_similarity": 45.455}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.509, "full_output_similarity": 41.509}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.625, "full_output_similarity": 40.625}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 36.957, "full_output_similarity": 36.957}, {"unit_id": "a.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.541, "full_output_similarity": 40.541}, {"unit_id": "a.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 36.364, "full_output_similarity": 36.364}, {"unit_id": "a.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.476, "full_output_similarity": 40.476}, {"unit_id": "a.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.667, "full_output_similarity": 41.667}, {"unit_id": "a.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.58, "full_output_similarity": 40.58}, {"unit_id": "a.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 37.838, "full_output_similarity": 37.838}, {"unit_id": "a.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 34.545, "full_output_similarity": 34.545}, {"unit_id": "a.17", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.741, "full_output_similarity": 40.741}, {"unit_id": "a.18", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 38.333, "full_output_similarity": 38.333}, {"unit_id": "a.19", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.026, "full_output_similarity": 41.026}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2025-individual-p2-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.0, "full_output_similarity": 40.0}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} +{"record_id": "iol-2025-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 32.738, "full_output_similarity": 32.738}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "microsoft/Phi-4-mini-instruct"} diff --git a/benchmark/IOL/ioling_hf/evals/results/mistralai__Mistral-7B-Instruct-v0.3__diverse5.scores.jsonl b/benchmark/IOL/ioling_hf/evals/results/mistralai__Mistral-7B-Instruct-v0.3__diverse5.scores.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b972340c863dd30fdbe7cb51206c8cde58f81ca6 --- /dev/null +++ b/benchmark/IOL/ioling_hf/evals/results/mistralai__Mistral-7B-Instruct-v0.3__diverse5.scores.jsonl @@ -0,0 +1,5 @@ +{"record_id": "iol-2006-individual-p1-sub-assignment_1", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["assignment_1.1", "assignment_1.2", "assignment_1.3", "assignment_1.4"], "unit_results": [{"unit_id": "assignment_1.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.0, "full_output_similarity": 75.0}, {"unit_id": "assignment_1.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}, {"unit_id": "assignment_1.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.545, "full_output_similarity": 54.545}, {"unit_id": "assignment_1.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 71.429, "full_output_similarity": 71.429}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2011-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.562, "full_output_similarity": 54.696}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2015-individual-p5-sub-b", "score": 0.0, "max_score": 9.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["b.1", "b.2", "b.3", "b.4", "b.5", "b.6", "b.7", "b.8", "b.9"], "unit_results": [{"unit_id": "b.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 34.615, "full_output_similarity": 77.778}, {"unit_id": "b.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 26.087, "full_output_similarity": 82.609}, {"unit_id": "b.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 32.0, "full_output_similarity": 77.778}, {"unit_id": "b.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.333, "full_output_similarity": 75.0}, {"unit_id": "b.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 28.571, "full_output_similarity": 75.0}, {"unit_id": "b.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 34.483, "full_output_similarity": 75.862}, {"unit_id": "b.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.909, "full_output_similarity": 80.0}, {"unit_id": "b.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.333, "full_output_similarity": 70.0}, {"unit_id": "b.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.333, "full_output_similarity": 77.778}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2021-individual-p2-sub-a", "score": 0.0, "max_score": 9.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.154, "full_output_similarity": 46.154}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 63.333, "full_output_similarity": 63.333}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.0, "full_output_similarity": 60.0}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 85.185, "full_output_similarity": 85.185}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.606, "full_output_similarity": 60.606}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.333, "full_output_similarity": 53.333}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 77.778, "full_output_similarity": 77.778}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 61.29, "full_output_similarity": 61.29}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.222, "full_output_similarity": 72.222}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2025-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 31.548, "full_output_similarity": 31.548}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} diff --git a/benchmark/IOL/ioling_hf/evals/results/mistralai__Mistral-7B-Instruct-v0.3__strict30.scores.jsonl b/benchmark/IOL/ioling_hf/evals/results/mistralai__Mistral-7B-Instruct-v0.3__strict30.scores.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..352a158c6ee150b68b8a8c2591b518fdb990eb5b --- /dev/null +++ b/benchmark/IOL/ioling_hf/evals/results/mistralai__Mistral-7B-Instruct-v0.3__strict30.scores.jsonl @@ -0,0 +1,30 @@ +{"record_id": "iol-2006-individual-p1-sub-assignment_1", "score": 0.0, "max_score": 4.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["assignment_1.1", "assignment_1.2", "assignment_1.3", "assignment_1.4"], "unit_results": [{"unit_id": "assignment_1.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.0, "full_output_similarity": 70.0}, {"unit_id": "assignment_1.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.606, "full_output_similarity": 60.606}, {"unit_id": "assignment_1.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 50.0}, {"unit_id": "assignment_1.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 57.143, "full_output_similarity": 57.143}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2006-individual-p5", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 44.096, "full_output_similarity": 44.096}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2007-individual-p5", "score": 1.0, "max_score": 4.0, "score_fraction": 0.25, "verdict": "partial", "matched_units": ["full.4"], "missed_units": ["full.1", "full.2", "full.3"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.333, "full_output_similarity": 44.828}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 0.0, "full_output_similarity": 48.571}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.333, "full_output_similarity": 52.174}, {"unit_id": "full.4", "points": 1.0, "matched": true, "match_type": "fuzzy_final_partial_ratio", "final_similarity": 100.0, "full_output_similarity": 45.161}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2008-individual-p2-sub-b", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["b.1"], "unit_results": [{"unit_id": "b.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.538, "full_output_similarity": 48.538}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2008-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 47.931, "full_output_similarity": 47.931}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2009-individual-p4-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.37, "full_output_similarity": 48.691}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2010-individual-p2-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.327, "full_output_similarity": 51.414}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2010-team-p1", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 36.772, "full_output_similarity": 36.772}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2011-individual-p3-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.727, "full_output_similarity": 69.065}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2012-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 47.423, "full_output_similarity": 47.826}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2012-individual-p5-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 56.954, "full_output_similarity": 53.061}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2013-individual-p3", "score": 0.0, "max_score": 5.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 50.0}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 36.242, "full_output_similarity": 36.242}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 31.25, "full_output_similarity": 31.25}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 30.345, "full_output_similarity": 30.345}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 31.034, "full_output_similarity": 31.034}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2014-individual-p2", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 44.444, "full_output_similarity": 44.444}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2014-individual-p5-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 47.098, "full_output_similarity": 47.098}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2015-individual-p3-sub-a", "score": 0.0, "max_score": 5.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.0, "full_output_similarity": 60.0}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 56.962, "full_output_similarity": 56.962}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.857, "full_output_similarity": 52.857}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 54.054, "full_output_similarity": 54.054}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.75, "full_output_similarity": 48.75}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2016-individual-p1", "score": 0.0, "max_score": 15.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5", "full.6", "full.7", "full.8", "full.9", "full.10", "full.11", "full.12", "full.13", "full.14", "full.15"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 82.979, "full_output_similarity": 82.979}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 82.222, "full_output_similarity": 82.222}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 77.5, "full_output_similarity": 77.5}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 78.049, "full_output_similarity": 78.049}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 77.778, "full_output_similarity": 77.778}, {"unit_id": "full.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 82.927, "full_output_similarity": 82.927}, {"unit_id": "full.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 89.583, "full_output_similarity": 89.583}, {"unit_id": "full.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 82.051, "full_output_similarity": 82.051}, {"unit_id": "full.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 80.952, "full_output_similarity": 80.952}, {"unit_id": "full.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 90.0, "full_output_similarity": 90.0}, {"unit_id": "full.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 80.952, "full_output_similarity": 80.952}, {"unit_id": "full.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 84.091, "full_output_similarity": 84.091}, {"unit_id": "full.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 78.571, "full_output_similarity": 78.571}, {"unit_id": "full.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 81.25, "full_output_similarity": 81.25}, {"unit_id": "full.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 82.979, "full_output_similarity": 82.979}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2016-individual-p5-sub-a", "score": 0.0, "max_score": 2.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.87, "full_output_similarity": 60.87}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.125, "full_output_similarity": 53.125}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2017-individual-p2-sub-a", "score": 0.0, "max_score": 16.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12", "a.13", "a.14", "a.15", "a.16"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 59.016, "full_output_similarity": 59.016}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 58.491, "full_output_similarity": 58.491}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.833, "full_output_similarity": 70.833}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 58.491, "full_output_similarity": 57.143}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 58.824, "full_output_similarity": 56.098}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 64.286, "full_output_similarity": 64.286}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.0, "full_output_similarity": 52.0}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 63.158, "full_output_similarity": 73.684}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 74.286, "full_output_similarity": 74.286}, {"unit_id": "a.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 61.111, "full_output_similarity": 61.111}, {"unit_id": "a.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 88.0, "full_output_similarity": 88.0}, {"unit_id": "a.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 76.0, "full_output_similarity": 76.0}, {"unit_id": "a.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 80.488, "full_output_similarity": 80.488}, {"unit_id": "a.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.488, "full_output_similarity": 58.14}, {"unit_id": "a.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 59.091, "full_output_similarity": 59.091}, {"unit_id": "a.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2017-team-p1", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 39.761, "full_output_similarity": 39.761}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2018-individual-p4-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 36.111, "full_output_similarity": 36.111}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2019-individual-p2-sub-a", "score": 0.0, "max_score": 17.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12", "a.13", "a.14", "a.15", "a.16", "a.17"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 58.14, "full_output_similarity": 58.14}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 72.727, "full_output_similarity": 72.727}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 85.714, "full_output_similarity": 85.714}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.0, "full_output_similarity": 70.0}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 73.077, "full_output_similarity": 73.077}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 65.714, "full_output_similarity": 65.714}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 78.788, "full_output_similarity": 78.788}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 76.471, "full_output_similarity": 76.471}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 63.636, "full_output_similarity": 63.636}, {"unit_id": "a.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 65.854, "full_output_similarity": 65.854}, {"unit_id": "a.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 67.742, "full_output_similarity": 67.742}, {"unit_id": "a.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.0, "full_output_similarity": 70.0}, {"unit_id": "a.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}, {"unit_id": "a.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.61, "full_output_similarity": 75.61}, {"unit_id": "a.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.37, "full_output_similarity": 70.37}, {"unit_id": "a.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 87.5, "full_output_similarity": 87.5}, {"unit_id": "a.17", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 62.963, "full_output_similarity": 62.963}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2019-team-p1", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.166, "full_output_similarity": 51.166}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2021-individual-p3-sub-a", "score": 4.0, "max_score": 4.0, "score_fraction": 1.0, "verdict": "correct", "matched_units": ["a.1", "a.2", "a.3", "a.4"], "missed_units": [], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": true, "match_type": "normalized_final_substring", "final_similarity": 100.0, "full_output_similarity": 100.0}, {"unit_id": "a.2", "points": 1.0, "matched": true, "match_type": "normalized_final_substring", "final_similarity": 100.0, "full_output_similarity": 100.0}, {"unit_id": "a.3", "points": 1.0, "matched": true, "match_type": "normalized_final_substring", "final_similarity": 100.0, "full_output_similarity": 100.0}, {"unit_id": "a.4", "points": 1.0, "matched": true, "match_type": "normalized_final_substring", "final_similarity": 100.0, "full_output_similarity": 100.0}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2022-individual-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 37.5, "full_output_similarity": 83.784}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2022-individual-p5-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 33.333, "full_output_similarity": 41.667}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2023-individual-p3", "score": 0.0, "max_score": 13.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5", "full.6", "full.7", "full.8", "full.9", "full.10", "full.11", "full.12", "full.13"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 37.5, "full_output_similarity": 37.5}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.387, "full_output_similarity": 48.387}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 37.037, "full_output_similarity": 37.037}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 69.231, "full_output_similarity": 69.231}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.0, "full_output_similarity": 40.0}, {"unit_id": "full.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 62.963, "full_output_similarity": 62.963}, {"unit_id": "full.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 68.75, "full_output_similarity": 68.75}, {"unit_id": "full.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 50.0, "full_output_similarity": 50.0}, {"unit_id": "full.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.98, "full_output_similarity": 48.98}, {"unit_id": "full.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.588, "full_output_similarity": 70.588}, {"unit_id": "full.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 67.647, "full_output_similarity": 67.647}, {"unit_id": "full.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 75.676, "full_output_similarity": 75.676}, {"unit_id": "full.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 77.083, "full_output_similarity": 77.083}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2024-individual-p1", "score": 0.0, "max_score": 17.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["full.1", "full.2", "full.3", "full.4", "full.5", "full.6", "full.7", "full.8", "full.9", "full.10", "full.11", "full.12", "full.13", "full.14", "full.15", "full.16", "full.17"], "unit_results": [{"unit_id": "full.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 45.161, "full_output_similarity": 45.161}, {"unit_id": "full.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 43.75, "full_output_similarity": 43.75}, {"unit_id": "full.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 47.5, "full_output_similarity": 47.5}, {"unit_id": "full.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.667, "full_output_similarity": 46.667}, {"unit_id": "full.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 66.667, "full_output_similarity": 66.667}, {"unit_id": "full.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.429, "full_output_similarity": 46.429}, {"unit_id": "full.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.515, "full_output_similarity": 51.515}, {"unit_id": "full.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 43.75, "full_output_similarity": 43.75}, {"unit_id": "full.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.053, "full_output_similarity": 46.053}, {"unit_id": "full.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 56.25, "full_output_similarity": 56.25}, {"unit_id": "full.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 59.259, "full_output_similarity": 59.259}, {"unit_id": "full.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 62.162, "full_output_similarity": 62.162}, {"unit_id": "full.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.0, "full_output_similarity": 60.0}, {"unit_id": "full.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 68.0, "full_output_similarity": 68.0}, {"unit_id": "full.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 58.065, "full_output_similarity": 58.065}, {"unit_id": "full.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 64.516, "full_output_similarity": 64.516}, {"unit_id": "full.17", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 70.833, "full_output_similarity": 70.833}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2024-individual-p4-sub-a", "score": 0.0, "max_score": 19.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7", "a.8", "a.9", "a.10", "a.11", "a.12", "a.13", "a.14", "a.15", "a.16", "a.17", "a.18", "a.19"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 45.455, "full_output_similarity": 48.485}, {"unit_id": "a.2", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 46.154, "full_output_similarity": 52.941}, {"unit_id": "a.3", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 42.593, "full_output_similarity": 51.852}, {"unit_id": "a.4", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.387, "full_output_similarity": 56.098}, {"unit_id": "a.5", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 36.765, "full_output_similarity": 48.529}, {"unit_id": "a.6", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 45.455, "full_output_similarity": 51.515}, {"unit_id": "a.7", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.0, "full_output_similarity": 63.636}, {"unit_id": "a.8", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 40.625, "full_output_similarity": 46.875}, {"unit_id": "a.9", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 41.304, "full_output_similarity": 54.348}, {"unit_id": "a.10", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 48.649, "full_output_similarity": 48.649}, {"unit_id": "a.11", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 45.455, "full_output_similarity": 48.485}, {"unit_id": "a.12", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 42.857, "full_output_similarity": 52.381}, {"unit_id": "a.13", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 52.778, "full_output_similarity": 55.556}, {"unit_id": "a.14", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.351, "full_output_similarity": 54.054}, {"unit_id": "a.15", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 59.459, "full_output_similarity": 59.459}, {"unit_id": "a.16", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 60.417, "full_output_similarity": 61.818}, {"unit_id": "a.17", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 53.704, "full_output_similarity": 61.111}, {"unit_id": "a.18", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 69.565, "full_output_similarity": 68.966}, {"unit_id": "a.19", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 51.282, "full_output_similarity": 53.846}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2025-individual-p2-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 34.043, "full_output_similarity": 34.043}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} +{"record_id": "iol-2025-team-p1-sub-a", "score": 0.0, "max_score": 1.0, "score_fraction": 0.0, "verdict": "incorrect", "matched_units": [], "missed_units": ["a.1"], "unit_results": [{"unit_id": "a.1", "points": 1.0, "matched": false, "match_type": "none", "final_similarity": 34.524, "full_output_similarity": 34.524}], "method": "normalized_final_answer_unit_fuzzy_v3", "scoring_scope": "final_answer_only", "scorer_thresholds": {"final_partial_ratio": 92, "full_output_partial_ratio": null}, "needs_human_review": true, "model": "mistralai/Mistral-7B-Instruct-v0.3"} diff --git a/benchmark/IOL/ioling_hf/evals/results/model_attempts.jsonl b/benchmark/IOL/ioling_hf/evals/results/model_attempts.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3298ad287a41976a7a55a731bbe2d5c08e7f5a04 --- /dev/null +++ b/benchmark/IOL/ioling_hf/evals/results/model_attempts.jsonl @@ -0,0 +1,2 @@ +{"run":"Qwen__Qwen3-30B-A3B-Instruct-2507__diverse2","model":"Qwen/Qwen3-30B-A3B-Instruct-2507","status":"interrupted_during_startup","records_requested":2,"max_tokens":8192,"max_model_len":16384,"engine_args":"model,max_model_len only","notes":"Loaded the 56.87 GiB checkpoint and completed torch.compile, then remained in vLLM profile_run while FlashInfer CUTLASS MoE kernels were built during startup; interrupted after several quiet minutes with no generations written."} +{"run":"ibm-granite__granite-3.3-8b-instruct__diverse5","model":"ibm-granite/granite-3.3-8b-instruct","status":"interrupted_during_startup","records_requested":5,"max_tokens":8192,"max_model_len":16384,"engine_args":"model,max_model_len only","notes":"vLLM accepted GraniteForCausalLM and allocated about 16.8 GiB on the H200, then remained in engine initialization for several quiet minutes with no score file or generations written; interrupted cleanly."} diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/__init__.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..17cc20b615ac0f023e4aca540a75577313388274 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/__init__.py @@ -0,0 +1,9 @@ +# -*- coding: utf-8 -*- +__all__ = ["__version__"] + +try: + from ._version import version as __version__ +except ImportError: + # broken installation, we don't even try + # unknown only works because we do poor mans version compare + __version__ = "unknown" diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/_argcomplete.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/_argcomplete.py new file mode 100644 index 0000000000000000000000000000000000000000..c6cf1d8fddd1a0f1184afe79fdaf1a89c95c7b25 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/_argcomplete.py @@ -0,0 +1,110 @@ +# -*- coding: utf-8 -*- +"""allow bash-completion for argparse with argcomplete if installed +needs argcomplete>=0.5.6 for python 3.2/3.3 (older versions fail +to find the magic string, so _ARGCOMPLETE env. var is never set, and +this does not need special code. + +Function try_argcomplete(parser) should be called directly before +the call to ArgumentParser.parse_args(). + +The filescompleter is what you normally would use on the positional +arguments specification, in order to get "dirname/" after "dirn" +instead of the default "dirname ": + + optparser.add_argument(Config._file_or_dir, nargs='*' + ).completer=filescompleter + +Other, application specific, completers should go in the file +doing the add_argument calls as they need to be specified as .completer +attributes as well. (If argcomplete is not installed, the function the +attribute points to will not be used). + +SPEEDUP +======= +The generic argcomplete script for bash-completion +(/etc/bash_completion.d/python-argcomplete.sh ) +uses a python program to determine startup script generated by pip. +You can speed up completion somewhat by changing this script to include + # PYTHON_ARGCOMPLETE_OK +so the the python-argcomplete-check-easy-install-script does not +need to be called to find the entry point of the code and see if that is +marked with PYTHON_ARGCOMPLETE_OK + +INSTALL/DEBUGGING +================= +To include this support in another application that has setup.py generated +scripts: +- add the line: + # PYTHON_ARGCOMPLETE_OK + near the top of the main python entry point +- include in the file calling parse_args(): + from _argcomplete import try_argcomplete, filescompleter + , call try_argcomplete just before parse_args(), and optionally add + filescompleter to the positional arguments' add_argument() +If things do not work right away: +- switch on argcomplete debugging with (also helpful when doing custom + completers): + export _ARC_DEBUG=1 +- run: + python-argcomplete-check-easy-install-script $(which appname) + echo $? + will echo 0 if the magic line has been found, 1 if not +- sometimes it helps to find early on errors using: + _ARGCOMPLETE=1 _ARC_DEBUG=1 appname + which should throw a KeyError: 'COMPLINE' (which is properly set by the + global argcomplete script). +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import sys +from glob import glob + + +class FastFilesCompleter(object): + "Fast file completer class" + + def __init__(self, directories=True): + self.directories = directories + + def __call__(self, prefix, **kwargs): + """only called on non option completions""" + if os.path.sep in prefix[1:]: + prefix_dir = len(os.path.dirname(prefix) + os.path.sep) + else: + prefix_dir = 0 + completion = [] + globbed = [] + if "*" not in prefix and "?" not in prefix: + # we are on unix, otherwise no bash + if not prefix or prefix[-1] == os.path.sep: + globbed.extend(glob(prefix + ".*")) + prefix += "*" + globbed.extend(glob(prefix)) + for x in sorted(globbed): + if os.path.isdir(x): + x += "/" + # append stripping the prefix (like bash, not like compgen) + completion.append(x[prefix_dir:]) + return completion + + +if os.environ.get("_ARGCOMPLETE"): + try: + import argcomplete.completers + except ImportError: + sys.exit(-1) + filescompleter = FastFilesCompleter() + + def try_argcomplete(parser): + argcomplete.autocomplete(parser, always_complete_options=False) + + +else: + + def try_argcomplete(parser): + pass + + filescompleter = None diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/_code/_py2traceback.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/_code/_py2traceback.py new file mode 100644 index 0000000000000000000000000000000000000000..faacc02166e165842f56b15244bad0b8f93dc7bc --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/_code/_py2traceback.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +# copied from python-2.7.3's traceback.py +# CHANGES: +# - some_str is replaced, trying to create unicode strings +# +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import types + +from six import text_type + + +def format_exception_only(etype, value): + """Format the exception part of a traceback. + + The arguments are the exception type and value such as given by + sys.last_type and sys.last_value. The return value is a list of + strings, each ending in a newline. + + Normally, the list contains a single string; however, for + SyntaxError exceptions, it contains several lines that (when + printed) display detailed information about where the syntax + error occurred. + + The message indicating which exception occurred is always the last + string in the list. + + """ + + # An instance should not have a meaningful value parameter, but + # sometimes does, particularly for string exceptions, such as + # >>> raise string1, string2 # deprecated + # + # Clear these out first because issubtype(string1, SyntaxError) + # would throw another exception and mask the original problem. + if ( + isinstance(etype, BaseException) + or isinstance(etype, types.InstanceType) + or etype is None + or type(etype) is str + ): + return [_format_final_exc_line(etype, value)] + + stype = etype.__name__ + + if not issubclass(etype, SyntaxError): + return [_format_final_exc_line(stype, value)] + + # It was a syntax error; show exactly where the problem was found. + lines = [] + try: + msg, (filename, lineno, offset, badline) = value.args + except Exception: + pass + else: + filename = filename or "" + lines.append(' File "{}", line {}\n'.format(filename, lineno)) + if badline is not None: + if isinstance(badline, bytes): # python 2 only + badline = badline.decode("utf-8", "replace") + lines.append(" {}\n".format(badline.strip())) + if offset is not None: + caretspace = badline.rstrip("\n")[:offset].lstrip() + # non-space whitespace (likes tabs) must be kept for alignment + caretspace = ((c.isspace() and c or " ") for c in caretspace) + # only three spaces to account for offset1 == pos 0 + lines.append(" {}^\n".format("".join(caretspace))) + value = msg + + lines.append(_format_final_exc_line(stype, value)) + return lines + + +def _format_final_exc_line(etype, value): + """Return a list of a single line -- normal case for format_exception_only""" + valuestr = _some_str(value) + if value is None or not valuestr: + line = "{}\n".format(etype) + else: + line = "{}: {}\n".format(etype, valuestr) + return line + + +def _some_str(value): + try: + return text_type(value) + except Exception: + try: + return bytes(value).decode("UTF-8", "replace") + except Exception: + pass + return "".format(type(value).__name__) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/_code/code.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/_code/code.py new file mode 100644 index 0000000000000000000000000000000000000000..175d6fda01d40c700e402a6e292cd949d800aeb7 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/_code/code.py @@ -0,0 +1,1093 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import inspect +import re +import sys +import traceback +from inspect import CO_VARARGS +from inspect import CO_VARKEYWORDS +from weakref import ref + +import attr +import pluggy +import py +from six import text_type + +import _pytest +from _pytest._io.saferepr import safeformat +from _pytest._io.saferepr import saferepr +from _pytest.compat import _PY2 +from _pytest.compat import _PY3 +from _pytest.compat import PY35 +from _pytest.compat import safe_str + +if _PY3: + from traceback import format_exception_only +else: + from ._py2traceback import format_exception_only + + +class Code(object): + """ wrapper around Python code objects """ + + def __init__(self, rawcode): + if not hasattr(rawcode, "co_filename"): + rawcode = getrawcode(rawcode) + try: + self.filename = rawcode.co_filename + self.firstlineno = rawcode.co_firstlineno - 1 + self.name = rawcode.co_name + except AttributeError: + raise TypeError("not a code object: %r" % (rawcode,)) + self.raw = rawcode + + def __eq__(self, other): + return self.raw == other.raw + + __hash__ = None + + def __ne__(self, other): + return not self == other + + @property + def path(self): + """ return a path object pointing to source code (note that it + might not point to an actually existing file). """ + try: + p = py.path.local(self.raw.co_filename) + # maybe don't try this checking + if not p.check(): + raise OSError("py.path check failed.") + except OSError: + # XXX maybe try harder like the weird logic + # in the standard lib [linecache.updatecache] does? + p = self.raw.co_filename + + return p + + @property + def fullsource(self): + """ return a _pytest._code.Source object for the full source file of the code + """ + from _pytest._code import source + + full, _ = source.findsource(self.raw) + return full + + def source(self): + """ return a _pytest._code.Source object for the code object's source only + """ + # return source only for that part of code + import _pytest._code + + return _pytest._code.Source(self.raw) + + def getargs(self, var=False): + """ return a tuple with the argument names for the code object + + if 'var' is set True also return the names of the variable and + keyword arguments when present + """ + # handfull shortcut for getting args + raw = self.raw + argcount = raw.co_argcount + if var: + argcount += raw.co_flags & CO_VARARGS + argcount += raw.co_flags & CO_VARKEYWORDS + return raw.co_varnames[:argcount] + + +class Frame(object): + """Wrapper around a Python frame holding f_locals and f_globals + in which expressions can be evaluated.""" + + def __init__(self, frame): + self.lineno = frame.f_lineno - 1 + self.f_globals = frame.f_globals + self.f_locals = frame.f_locals + self.raw = frame + self.code = Code(frame.f_code) + + @property + def statement(self): + """ statement this frame is at """ + import _pytest._code + + if self.code.fullsource is None: + return _pytest._code.Source("") + return self.code.fullsource.getstatement(self.lineno) + + def eval(self, code, **vars): + """ evaluate 'code' in the frame + + 'vars' are optional additional local variables + + returns the result of the evaluation + """ + f_locals = self.f_locals.copy() + f_locals.update(vars) + return eval(code, self.f_globals, f_locals) + + def exec_(self, code, **vars): + """ exec 'code' in the frame + + 'vars' are optiona; additional local variables + """ + f_locals = self.f_locals.copy() + f_locals.update(vars) + exec(code, self.f_globals, f_locals) + + def repr(self, object): + """ return a 'safe' (non-recursive, one-line) string repr for 'object' + """ + return saferepr(object) + + def is_true(self, object): + return object + + def getargs(self, var=False): + """ return a list of tuples (name, value) for all arguments + + if 'var' is set True also include the variable and keyword + arguments when present + """ + retval = [] + for arg in self.code.getargs(var): + try: + retval.append((arg, self.f_locals[arg])) + except KeyError: + pass # this can occur when using Psyco + return retval + + +class TracebackEntry(object): + """ a single entry in a traceback """ + + _repr_style = None + exprinfo = None + + def __init__(self, rawentry, excinfo=None): + self._excinfo = excinfo + self._rawentry = rawentry + self.lineno = rawentry.tb_lineno - 1 + + def set_repr_style(self, mode): + assert mode in ("short", "long") + self._repr_style = mode + + @property + def frame(self): + import _pytest._code + + return _pytest._code.Frame(self._rawentry.tb_frame) + + @property + def relline(self): + return self.lineno - self.frame.code.firstlineno + + def __repr__(self): + return "" % (self.frame.code.path, self.lineno + 1) + + @property + def statement(self): + """ _pytest._code.Source object for the current statement """ + source = self.frame.code.fullsource + return source.getstatement(self.lineno) + + @property + def path(self): + """ path to the source code """ + return self.frame.code.path + + def getlocals(self): + return self.frame.f_locals + + locals = property(getlocals, None, None, "locals of underlaying frame") + + def getfirstlinesource(self): + # on Jython this firstlineno can be -1 apparently + return max(self.frame.code.firstlineno, 0) + + def getsource(self, astcache=None): + """ return failing source code. """ + # we use the passed in astcache to not reparse asttrees + # within exception info printing + from _pytest._code.source import getstatementrange_ast + + source = self.frame.code.fullsource + if source is None: + return None + key = astnode = None + if astcache is not None: + key = self.frame.code.path + if key is not None: + astnode = astcache.get(key, None) + start = self.getfirstlinesource() + try: + astnode, _, end = getstatementrange_ast( + self.lineno, source, astnode=astnode + ) + except SyntaxError: + end = self.lineno + 1 + else: + if key is not None: + astcache[key] = astnode + return source[start:end] + + source = property(getsource) + + def ishidden(self): + """ return True if the current frame has a var __tracebackhide__ + resolving to True. + + If __tracebackhide__ is a callable, it gets called with the + ExceptionInfo instance and can decide whether to hide the traceback. + + mostly for internal use + """ + f = self.frame + tbh = f.f_locals.get( + "__tracebackhide__", f.f_globals.get("__tracebackhide__", False) + ) + if tbh and callable(tbh): + return tbh(None if self._excinfo is None else self._excinfo()) + return tbh + + def __str__(self): + try: + fn = str(self.path) + except py.error.Error: + fn = "???" + name = self.frame.code.name + try: + line = str(self.statement).lstrip() + except KeyboardInterrupt: + raise + except: # noqa + line = "???" + return " File %r:%d in %s\n %s\n" % (fn, self.lineno + 1, name, line) + + def name(self): + return self.frame.code.raw.co_name + + name = property(name, None, None, "co_name of underlaying code") + + +class Traceback(list): + """ Traceback objects encapsulate and offer higher level + access to Traceback entries. + """ + + Entry = TracebackEntry + + def __init__(self, tb, excinfo=None): + """ initialize from given python traceback object and ExceptionInfo """ + self._excinfo = excinfo + if hasattr(tb, "tb_next"): + + def f(cur): + while cur is not None: + yield self.Entry(cur, excinfo=excinfo) + cur = cur.tb_next + + list.__init__(self, f(tb)) + else: + list.__init__(self, tb) + + def cut(self, path=None, lineno=None, firstlineno=None, excludepath=None): + """ return a Traceback instance wrapping part of this Traceback + + by provding any combination of path, lineno and firstlineno, the + first frame to start the to-be-returned traceback is determined + + this allows cutting the first part of a Traceback instance e.g. + for formatting reasons (removing some uninteresting bits that deal + with handling of the exception/traceback) + """ + for x in self: + code = x.frame.code + codepath = code.path + if ( + (path is None or codepath == path) + and ( + excludepath is None + or not hasattr(codepath, "relto") + or not codepath.relto(excludepath) + ) + and (lineno is None or x.lineno == lineno) + and (firstlineno is None or x.frame.code.firstlineno == firstlineno) + ): + return Traceback(x._rawentry, self._excinfo) + return self + + def __getitem__(self, key): + val = super(Traceback, self).__getitem__(key) + if isinstance(key, type(slice(0))): + val = self.__class__(val) + return val + + def filter(self, fn=lambda x: not x.ishidden()): + """ return a Traceback instance with certain items removed + + fn is a function that gets a single argument, a TracebackEntry + instance, and should return True when the item should be added + to the Traceback, False when not + + by default this removes all the TracebackEntries which are hidden + (see ishidden() above) + """ + return Traceback(filter(fn, self), self._excinfo) + + def getcrashentry(self): + """ return last non-hidden traceback entry that lead + to the exception of a traceback. + """ + for i in range(-1, -len(self) - 1, -1): + entry = self[i] + if not entry.ishidden(): + return entry + return self[-1] + + def recursionindex(self): + """ return the index of the frame/TracebackEntry where recursion + originates if appropriate, None if no recursion occurred + """ + cache = {} + for i, entry in enumerate(self): + # id for the code.raw is needed to work around + # the strange metaprogramming in the decorator lib from pypi + # which generates code objects that have hash/value equality + # XXX needs a test + key = entry.frame.code.path, id(entry.frame.code.raw), entry.lineno + # print "checking for recursion at", key + values = cache.setdefault(key, []) + if values: + f = entry.frame + loc = f.f_locals + for otherloc in values: + if f.is_true( + f.eval( + co_equal, + __recursioncache_locals_1=loc, + __recursioncache_locals_2=otherloc, + ) + ): + return i + values.append(entry.frame.f_locals) + return None + + +co_equal = compile( + "__recursioncache_locals_1 == __recursioncache_locals_2", "?", "eval" +) + + +@attr.s(repr=False) +class ExceptionInfo(object): + """ wraps sys.exc_info() objects and offers + help for navigating the traceback. + """ + + _assert_start_repr = ( + "AssertionError(u'assert " if _PY2 else "AssertionError('assert " + ) + + _excinfo = attr.ib() + _striptext = attr.ib(default="") + _traceback = attr.ib(default=None) + + @classmethod + def from_current(cls, exprinfo=None): + """returns an ExceptionInfo matching the current traceback + + .. warning:: + + Experimental API + + + :param exprinfo: a text string helping to determine if we should + strip ``AssertionError`` from the output, defaults + to the exception message/``__str__()`` + """ + tup = sys.exc_info() + assert tup[0] is not None, "no current exception" + _striptext = "" + if exprinfo is None and isinstance(tup[1], AssertionError): + exprinfo = getattr(tup[1], "msg", None) + if exprinfo is None: + exprinfo = saferepr(tup[1]) + if exprinfo and exprinfo.startswith(cls._assert_start_repr): + _striptext = "AssertionError: " + + return cls(tup, _striptext) + + @classmethod + def for_later(cls): + """return an unfilled ExceptionInfo + """ + return cls(None) + + @property + def type(self): + """the exception class""" + return self._excinfo[0] + + @property + def value(self): + """the exception value""" + return self._excinfo[1] + + @property + def tb(self): + """the exception raw traceback""" + return self._excinfo[2] + + @property + def typename(self): + """the type name of the exception""" + return self.type.__name__ + + @property + def traceback(self): + """the traceback""" + if self._traceback is None: + self._traceback = Traceback(self.tb, excinfo=ref(self)) + return self._traceback + + @traceback.setter + def traceback(self, value): + self._traceback = value + + def __repr__(self): + if self._excinfo is None: + return "" + return "" % (self.typename, len(self.traceback)) + + def exconly(self, tryshort=False): + """ return the exception as a string + + when 'tryshort' resolves to True, and the exception is a + _pytest._code._AssertionError, only the actual exception part of + the exception representation is returned (so 'AssertionError: ' is + removed from the beginning) + """ + lines = format_exception_only(self.type, self.value) + text = "".join(lines) + text = text.rstrip() + if tryshort: + if text.startswith(self._striptext): + text = text[len(self._striptext) :] + return text + + def errisinstance(self, exc): + """ return True if the exception is an instance of exc """ + return isinstance(self.value, exc) + + def _getreprcrash(self): + exconly = self.exconly(tryshort=True) + entry = self.traceback.getcrashentry() + path, lineno = entry.frame.code.raw.co_filename, entry.lineno + return ReprFileLocation(path, lineno + 1, exconly) + + def getrepr( + self, + showlocals=False, + style="long", + abspath=False, + tbfilter=True, + funcargs=False, + truncate_locals=True, + chain=True, + ): + """ + Return str()able representation of this exception info. + + :param bool showlocals: + Show locals per traceback entry. + Ignored if ``style=="native"``. + + :param str style: long|short|no|native traceback style + + :param bool abspath: + If paths should be changed to absolute or left unchanged. + + :param bool tbfilter: + Hide entries that contain a local variable ``__tracebackhide__==True``. + Ignored if ``style=="native"``. + + :param bool funcargs: + Show fixtures ("funcargs" for legacy purposes) per traceback entry. + + :param bool truncate_locals: + With ``showlocals==True``, make sure locals can be safely represented as strings. + + :param bool chain: if chained exceptions in Python 3 should be shown. + + .. versionchanged:: 3.9 + + Added the ``chain`` parameter. + """ + if style == "native": + return ReprExceptionInfo( + ReprTracebackNative( + traceback.format_exception( + self.type, self.value, self.traceback[0]._rawentry + ) + ), + self._getreprcrash(), + ) + + fmt = FormattedExcinfo( + showlocals=showlocals, + style=style, + abspath=abspath, + tbfilter=tbfilter, + funcargs=funcargs, + truncate_locals=truncate_locals, + chain=chain, + ) + return fmt.repr_excinfo(self) + + def __str__(self): + if self._excinfo is None: + return repr(self) + entry = self.traceback[-1] + loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly()) + return str(loc) + + def __unicode__(self): + entry = self.traceback[-1] + loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly()) + return text_type(loc) + + def match(self, regexp): + """ + Check whether the regular expression 'regexp' is found in the string + representation of the exception using ``re.search``. If it matches + then True is returned (so that it is possible to write + ``assert excinfo.match()``). If it doesn't match an AssertionError is + raised. + """ + __tracebackhide__ = True + value = ( + text_type(self.value) if isinstance(regexp, text_type) else str(self.value) + ) + if not re.search(regexp, value): + raise AssertionError( + u"Pattern {!r} not found in {!r}".format(regexp, value) + ) + return True + + +@attr.s +class FormattedExcinfo(object): + """ presenting information about failing Functions and Generators. """ + + # for traceback entries + flow_marker = ">" + fail_marker = "E" + + showlocals = attr.ib(default=False) + style = attr.ib(default="long") + abspath = attr.ib(default=True) + tbfilter = attr.ib(default=True) + funcargs = attr.ib(default=False) + truncate_locals = attr.ib(default=True) + chain = attr.ib(default=True) + astcache = attr.ib(default=attr.Factory(dict), init=False, repr=False) + + def _getindent(self, source): + # figure out indent for given source + try: + s = str(source.getstatement(len(source) - 1)) + except KeyboardInterrupt: + raise + except: # noqa + try: + s = str(source[-1]) + except KeyboardInterrupt: + raise + except: # noqa + return 0 + return 4 + (len(s) - len(s.lstrip())) + + def _getentrysource(self, entry): + source = entry.getsource(self.astcache) + if source is not None: + source = source.deindent() + return source + + def repr_args(self, entry): + if self.funcargs: + args = [] + for argname, argvalue in entry.frame.getargs(var=True): + args.append((argname, saferepr(argvalue))) + return ReprFuncArgs(args) + + def get_source(self, source, line_index=-1, excinfo=None, short=False): + """ return formatted and marked up source lines. """ + import _pytest._code + + lines = [] + if source is None or line_index >= len(source.lines): + source = _pytest._code.Source("???") + line_index = 0 + if line_index < 0: + line_index += len(source) + space_prefix = " " + if short: + lines.append(space_prefix + source.lines[line_index].strip()) + else: + for line in source.lines[:line_index]: + lines.append(space_prefix + line) + lines.append(self.flow_marker + " " + source.lines[line_index]) + for line in source.lines[line_index + 1 :]: + lines.append(space_prefix + line) + if excinfo is not None: + indent = 4 if short else self._getindent(source) + lines.extend(self.get_exconly(excinfo, indent=indent, markall=True)) + return lines + + def get_exconly(self, excinfo, indent=4, markall=False): + lines = [] + indent = " " * indent + # get the real exception information out + exlines = excinfo.exconly(tryshort=True).split("\n") + failindent = self.fail_marker + indent[1:] + for line in exlines: + lines.append(failindent + line) + if not markall: + failindent = indent + return lines + + def repr_locals(self, locals): + if self.showlocals: + lines = [] + keys = [loc for loc in locals if loc[0] != "@"] + keys.sort() + for name in keys: + value = locals[name] + if name == "__builtins__": + lines.append("__builtins__ = ") + else: + # This formatting could all be handled by the + # _repr() function, which is only reprlib.Repr in + # disguise, so is very configurable. + if self.truncate_locals: + str_repr = saferepr(value) + else: + str_repr = safeformat(value) + # if len(str_repr) < 70 or not isinstance(value, + # (list, tuple, dict)): + lines.append("%-10s = %s" % (name, str_repr)) + # else: + # self._line("%-10s =\\" % (name,)) + # # XXX + # pprint.pprint(value, stream=self.excinfowriter) + return ReprLocals(lines) + + def repr_traceback_entry(self, entry, excinfo=None): + import _pytest._code + + source = self._getentrysource(entry) + if source is None: + source = _pytest._code.Source("???") + line_index = 0 + else: + # entry.getfirstlinesource() can be -1, should be 0 on jython + line_index = entry.lineno - max(entry.getfirstlinesource(), 0) + + lines = [] + style = entry._repr_style + if style is None: + style = self.style + if style in ("short", "long"): + short = style == "short" + reprargs = self.repr_args(entry) if not short else None + s = self.get_source(source, line_index, excinfo, short=short) + lines.extend(s) + if short: + message = "in %s" % (entry.name) + else: + message = excinfo and excinfo.typename or "" + path = self._makepath(entry.path) + filelocrepr = ReprFileLocation(path, entry.lineno + 1, message) + localsrepr = None + if not short: + localsrepr = self.repr_locals(entry.locals) + return ReprEntry(lines, reprargs, localsrepr, filelocrepr, style) + if excinfo: + lines.extend(self.get_exconly(excinfo, indent=4)) + return ReprEntry(lines, None, None, None, style) + + def _makepath(self, path): + if not self.abspath: + try: + np = py.path.local().bestrelpath(path) + except OSError: + return path + if len(np) < len(str(path)): + path = np + return path + + def repr_traceback(self, excinfo): + traceback = excinfo.traceback + if self.tbfilter: + traceback = traceback.filter() + + if is_recursion_error(excinfo): + traceback, extraline = self._truncate_recursive_traceback(traceback) + else: + extraline = None + + last = traceback[-1] + entries = [] + for index, entry in enumerate(traceback): + einfo = (last == entry) and excinfo or None + reprentry = self.repr_traceback_entry(entry, einfo) + entries.append(reprentry) + return ReprTraceback(entries, extraline, style=self.style) + + def _truncate_recursive_traceback(self, traceback): + """ + Truncate the given recursive traceback trying to find the starting point + of the recursion. + + The detection is done by going through each traceback entry and finding the + point in which the locals of the frame are equal to the locals of a previous frame (see ``recursionindex()``. + + Handle the situation where the recursion process might raise an exception (for example + comparing numpy arrays using equality raises a TypeError), in which case we do our best to + warn the user of the error and show a limited traceback. + """ + try: + recursionindex = traceback.recursionindex() + except Exception as e: + max_frames = 10 + extraline = ( + "!!! Recursion error detected, but an error occurred locating the origin of recursion.\n" + " The following exception happened when comparing locals in the stack frame:\n" + " {exc_type}: {exc_msg}\n" + " Displaying first and last {max_frames} stack frames out of {total}." + ).format( + exc_type=type(e).__name__, + exc_msg=safe_str(e), + max_frames=max_frames, + total=len(traceback), + ) + traceback = traceback[:max_frames] + traceback[-max_frames:] + else: + if recursionindex is not None: + extraline = "!!! Recursion detected (same locals & position)" + traceback = traceback[: recursionindex + 1] + else: + extraline = None + + return traceback, extraline + + def repr_excinfo(self, excinfo): + if _PY2: + reprtraceback = self.repr_traceback(excinfo) + reprcrash = excinfo._getreprcrash() + + return ReprExceptionInfo(reprtraceback, reprcrash) + else: + repr_chain = [] + e = excinfo.value + descr = None + seen = set() + while e is not None and id(e) not in seen: + seen.add(id(e)) + if excinfo: + reprtraceback = self.repr_traceback(excinfo) + reprcrash = excinfo._getreprcrash() + else: + # fallback to native repr if the exception doesn't have a traceback: + # ExceptionInfo objects require a full traceback to work + reprtraceback = ReprTracebackNative( + traceback.format_exception(type(e), e, None) + ) + reprcrash = None + + repr_chain += [(reprtraceback, reprcrash, descr)] + if e.__cause__ is not None and self.chain: + e = e.__cause__ + excinfo = ( + ExceptionInfo((type(e), e, e.__traceback__)) + if e.__traceback__ + else None + ) + descr = "The above exception was the direct cause of the following exception:" + elif ( + e.__context__ is not None + and not e.__suppress_context__ + and self.chain + ): + e = e.__context__ + excinfo = ( + ExceptionInfo((type(e), e, e.__traceback__)) + if e.__traceback__ + else None + ) + descr = "During handling of the above exception, another exception occurred:" + else: + e = None + repr_chain.reverse() + return ExceptionChainRepr(repr_chain) + + +class TerminalRepr(object): + def __str__(self): + s = self.__unicode__() + if _PY2: + s = s.encode("utf-8") + return s + + def __unicode__(self): + # FYI this is called from pytest-xdist's serialization of exception + # information. + io = py.io.TextIO() + tw = py.io.TerminalWriter(file=io) + self.toterminal(tw) + return io.getvalue().strip() + + def __repr__(self): + return "<%s instance at %0x>" % (self.__class__, id(self)) + + +class ExceptionRepr(TerminalRepr): + def __init__(self): + self.sections = [] + + def addsection(self, name, content, sep="-"): + self.sections.append((name, content, sep)) + + def toterminal(self, tw): + for name, content, sep in self.sections: + tw.sep(sep, name) + tw.line(content) + + +class ExceptionChainRepr(ExceptionRepr): + def __init__(self, chain): + super(ExceptionChainRepr, self).__init__() + self.chain = chain + # reprcrash and reprtraceback of the outermost (the newest) exception + # in the chain + self.reprtraceback = chain[-1][0] + self.reprcrash = chain[-1][1] + + def toterminal(self, tw): + for element in self.chain: + element[0].toterminal(tw) + if element[2] is not None: + tw.line("") + tw.line(element[2], yellow=True) + super(ExceptionChainRepr, self).toterminal(tw) + + +class ReprExceptionInfo(ExceptionRepr): + def __init__(self, reprtraceback, reprcrash): + super(ReprExceptionInfo, self).__init__() + self.reprtraceback = reprtraceback + self.reprcrash = reprcrash + + def toterminal(self, tw): + self.reprtraceback.toterminal(tw) + super(ReprExceptionInfo, self).toterminal(tw) + + +class ReprTraceback(TerminalRepr): + entrysep = "_ " + + def __init__(self, reprentries, extraline, style): + self.reprentries = reprentries + self.extraline = extraline + self.style = style + + def toterminal(self, tw): + # the entries might have different styles + for i, entry in enumerate(self.reprentries): + if entry.style == "long": + tw.line("") + entry.toterminal(tw) + if i < len(self.reprentries) - 1: + next_entry = self.reprentries[i + 1] + if ( + entry.style == "long" + or entry.style == "short" + and next_entry.style == "long" + ): + tw.sep(self.entrysep) + + if self.extraline: + tw.line(self.extraline) + + +class ReprTracebackNative(ReprTraceback): + def __init__(self, tblines): + self.style = "native" + self.reprentries = [ReprEntryNative(tblines)] + self.extraline = None + + +class ReprEntryNative(TerminalRepr): + style = "native" + + def __init__(self, tblines): + self.lines = tblines + + def toterminal(self, tw): + tw.write("".join(self.lines)) + + +class ReprEntry(TerminalRepr): + def __init__(self, lines, reprfuncargs, reprlocals, filelocrepr, style): + self.lines = lines + self.reprfuncargs = reprfuncargs + self.reprlocals = reprlocals + self.reprfileloc = filelocrepr + self.style = style + + def toterminal(self, tw): + if self.style == "short": + self.reprfileloc.toterminal(tw) + for line in self.lines: + red = line.startswith("E ") + tw.line(line, bold=True, red=red) + # tw.line("") + return + if self.reprfuncargs: + self.reprfuncargs.toterminal(tw) + for line in self.lines: + red = line.startswith("E ") + tw.line(line, bold=True, red=red) + if self.reprlocals: + tw.line("") + self.reprlocals.toterminal(tw) + if self.reprfileloc: + if self.lines: + tw.line("") + self.reprfileloc.toterminal(tw) + + def __str__(self): + return "%s\n%s\n%s" % ("\n".join(self.lines), self.reprlocals, self.reprfileloc) + + +class ReprFileLocation(TerminalRepr): + def __init__(self, path, lineno, message): + self.path = str(path) + self.lineno = lineno + self.message = message + + def toterminal(self, tw): + # filename and lineno output for each entry, + # using an output format that most editors unterstand + msg = self.message + i = msg.find("\n") + if i != -1: + msg = msg[:i] + tw.write(self.path, bold=True, red=True) + tw.line(":%s: %s" % (self.lineno, msg)) + + +class ReprLocals(TerminalRepr): + def __init__(self, lines): + self.lines = lines + + def toterminal(self, tw): + for line in self.lines: + tw.line(line) + + +class ReprFuncArgs(TerminalRepr): + def __init__(self, args): + self.args = args + + def toterminal(self, tw): + if self.args: + linesofar = "" + for name, value in self.args: + ns = "%s = %s" % (safe_str(name), safe_str(value)) + if len(ns) + len(linesofar) + 2 > tw.fullwidth: + if linesofar: + tw.line(linesofar) + linesofar = ns + else: + if linesofar: + linesofar += ", " + ns + else: + linesofar = ns + if linesofar: + tw.line(linesofar) + tw.line("") + + +def getrawcode(obj, trycall=True): + """ return code object for given function. """ + try: + return obj.__code__ + except AttributeError: + obj = getattr(obj, "im_func", obj) + obj = getattr(obj, "func_code", obj) + obj = getattr(obj, "f_code", obj) + obj = getattr(obj, "__code__", obj) + if trycall and not hasattr(obj, "co_firstlineno"): + if hasattr(obj, "__call__") and not inspect.isclass(obj): + x = getrawcode(obj.__call__, trycall=False) + if hasattr(x, "co_firstlineno"): + return x + return obj + + +if PY35: # RecursionError introduced in 3.5 + + def is_recursion_error(excinfo): + return excinfo.errisinstance(RecursionError) # noqa + + +else: + + def is_recursion_error(excinfo): + if not excinfo.errisinstance(RuntimeError): + return False + try: + return "maximum recursion depth exceeded" in str(excinfo.value) + except UnicodeError: + return False + + +# relative paths that we use to filter traceback entries from appearing to the user; +# see filter_traceback +# note: if we need to add more paths than what we have now we should probably use a list +# for better maintenance + +_PLUGGY_DIR = py.path.local(pluggy.__file__.rstrip("oc")) +# pluggy is either a package or a single module depending on the version +if _PLUGGY_DIR.basename == "__init__.py": + _PLUGGY_DIR = _PLUGGY_DIR.dirpath() +_PYTEST_DIR = py.path.local(_pytest.__file__).dirpath() +_PY_DIR = py.path.local(py.__file__).dirpath() + + +def filter_traceback(entry): + """Return True if a TracebackEntry instance should be removed from tracebacks: + * dynamically generated code (no code to show up for it); + * internal traceback from pytest or its internal libraries, py and pluggy. + """ + # entry.path might sometimes return a str object when the entry + # points to dynamically generated code + # see https://bitbucket.org/pytest-dev/py/issues/71 + raw_filename = entry.frame.code.raw.co_filename + is_generated = "<" in raw_filename and ">" in raw_filename + if is_generated: + return False + # entry.path might point to a non-existing file, in which case it will + # also return a str object. see #1133 + p = py.path.local(entry.path) + return ( + not p.relto(_PLUGGY_DIR) and not p.relto(_PYTEST_DIR) and not p.relto(_PY_DIR) + ) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/_code/source.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/_code/source.py new file mode 100644 index 0000000000000000000000000000000000000000..c8a4b6adf3828d6b8a95f9a76b88ef03ed29e9c6 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/_code/source.py @@ -0,0 +1,329 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import ast +import inspect +import linecache +import sys +import textwrap +import tokenize +import warnings +from ast import PyCF_ONLY_AST as _AST_FLAG +from bisect import bisect_right + +import py +import six + + +class Source(object): + """ an immutable object holding a source code fragment, + possibly deindenting it. + """ + + _compilecounter = 0 + + def __init__(self, *parts, **kwargs): + self.lines = lines = [] + de = kwargs.get("deindent", True) + for part in parts: + if not part: + partlines = [] + elif isinstance(part, Source): + partlines = part.lines + elif isinstance(part, (tuple, list)): + partlines = [x.rstrip("\n") for x in part] + elif isinstance(part, six.string_types): + partlines = part.split("\n") + else: + partlines = getsource(part, deindent=de).lines + if de: + partlines = deindent(partlines) + lines.extend(partlines) + + def __eq__(self, other): + try: + return self.lines == other.lines + except AttributeError: + if isinstance(other, str): + return str(self) == other + return False + + __hash__ = None + + def __getitem__(self, key): + if isinstance(key, int): + return self.lines[key] + else: + if key.step not in (None, 1): + raise IndexError("cannot slice a Source with a step") + newsource = Source() + newsource.lines = self.lines[key.start : key.stop] + return newsource + + def __len__(self): + return len(self.lines) + + def strip(self): + """ return new source object with trailing + and leading blank lines removed. + """ + start, end = 0, len(self) + while start < end and not self.lines[start].strip(): + start += 1 + while end > start and not self.lines[end - 1].strip(): + end -= 1 + source = Source() + source.lines[:] = self.lines[start:end] + return source + + def putaround(self, before="", after="", indent=" " * 4): + """ return a copy of the source object with + 'before' and 'after' wrapped around it. + """ + before = Source(before) + after = Source(after) + newsource = Source() + lines = [(indent + line) for line in self.lines] + newsource.lines = before.lines + lines + after.lines + return newsource + + def indent(self, indent=" " * 4): + """ return a copy of the source object with + all lines indented by the given indent-string. + """ + newsource = Source() + newsource.lines = [(indent + line) for line in self.lines] + return newsource + + def getstatement(self, lineno): + """ return Source statement which contains the + given linenumber (counted from 0). + """ + start, end = self.getstatementrange(lineno) + return self[start:end] + + def getstatementrange(self, lineno): + """ return (start, end) tuple which spans the minimal + statement region which containing the given lineno. + """ + if not (0 <= lineno < len(self)): + raise IndexError("lineno out of range") + ast, start, end = getstatementrange_ast(lineno, self) + return start, end + + def deindent(self): + """return a new source object deindented.""" + newsource = Source() + newsource.lines[:] = deindent(self.lines) + return newsource + + def isparseable(self, deindent=True): + """ return True if source is parseable, heuristically + deindenting it by default. + """ + from parser import suite as syntax_checker + + if deindent: + source = str(self.deindent()) + else: + source = str(self) + try: + # compile(source+'\n', "x", "exec") + syntax_checker(source + "\n") + except KeyboardInterrupt: + raise + except Exception: + return False + else: + return True + + def __str__(self): + return "\n".join(self.lines) + + def compile( + self, filename=None, mode="exec", flag=0, dont_inherit=0, _genframe=None + ): + """ return compiled code object. if filename is None + invent an artificial filename which displays + the source/line position of the caller frame. + """ + if not filename or py.path.local(filename).check(file=0): + if _genframe is None: + _genframe = sys._getframe(1) # the caller + fn, lineno = _genframe.f_code.co_filename, _genframe.f_lineno + base = "<%d-codegen " % self._compilecounter + self.__class__._compilecounter += 1 + if not filename: + filename = base + "%s:%d>" % (fn, lineno) + else: + filename = base + "%r %s:%d>" % (filename, fn, lineno) + source = "\n".join(self.lines) + "\n" + try: + co = compile(source, filename, mode, flag) + except SyntaxError: + ex = sys.exc_info()[1] + # re-represent syntax errors from parsing python strings + msglines = self.lines[: ex.lineno] + if ex.offset: + msglines.append(" " * ex.offset + "^") + msglines.append("(code was compiled probably from here: %s)" % filename) + newex = SyntaxError("\n".join(msglines)) + newex.offset = ex.offset + newex.lineno = ex.lineno + newex.text = ex.text + raise newex + else: + if flag & _AST_FLAG: + return co + lines = [(x + "\n") for x in self.lines] + linecache.cache[filename] = (1, None, lines, filename) + return co + + +# +# public API shortcut functions +# + + +def compile_(source, filename=None, mode="exec", flags=0, dont_inherit=0): + """ compile the given source to a raw code object, + and maintain an internal cache which allows later + retrieval of the source code for the code object + and any recursively created code objects. + """ + if isinstance(source, ast.AST): + # XXX should Source support having AST? + return compile(source, filename, mode, flags, dont_inherit) + _genframe = sys._getframe(1) # the caller + s = Source(source) + co = s.compile(filename, mode, flags, _genframe=_genframe) + return co + + +def getfslineno(obj): + """ Return source location (path, lineno) for the given object. + If the source cannot be determined return ("", -1). + + The line number is 0-based. + """ + from .code import Code + + try: + code = Code(obj) + except TypeError: + try: + fn = inspect.getsourcefile(obj) or inspect.getfile(obj) + except TypeError: + return "", -1 + + fspath = fn and py.path.local(fn) or None + lineno = -1 + if fspath: + try: + _, lineno = findsource(obj) + except IOError: + pass + else: + fspath = code.path + lineno = code.firstlineno + assert isinstance(lineno, int) + return fspath, lineno + + +# +# helper functions +# + + +def findsource(obj): + try: + sourcelines, lineno = inspect.findsource(obj) + except Exception: + return None, -1 + source = Source() + source.lines = [line.rstrip() for line in sourcelines] + return source, lineno + + +def getsource(obj, **kwargs): + from .code import getrawcode + + obj = getrawcode(obj) + try: + strsrc = inspect.getsource(obj) + except IndentationError: + strsrc = '"Buggy python version consider upgrading, cannot get source"' + assert isinstance(strsrc, str) + return Source(strsrc, **kwargs) + + +def deindent(lines): + return textwrap.dedent("\n".join(lines)).splitlines() + + +def get_statement_startend2(lineno, node): + import ast + + # flatten all statements and except handlers into one lineno-list + # AST's line numbers start indexing at 1 + values = [] + for x in ast.walk(node): + if isinstance(x, (ast.stmt, ast.ExceptHandler)): + values.append(x.lineno - 1) + for name in ("finalbody", "orelse"): + val = getattr(x, name, None) + if val: + # treat the finally/orelse part as its own statement + values.append(val[0].lineno - 1 - 1) + values.sort() + insert_index = bisect_right(values, lineno) + start = values[insert_index - 1] + if insert_index >= len(values): + end = None + else: + end = values[insert_index] + return start, end + + +def getstatementrange_ast(lineno, source, assertion=False, astnode=None): + if astnode is None: + content = str(source) + # See #4260: + # don't produce duplicate warnings when compiling source to find ast + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + astnode = compile(content, "source", "exec", _AST_FLAG) + + start, end = get_statement_startend2(lineno, astnode) + # we need to correct the end: + # - ast-parsing strips comments + # - there might be empty lines + # - we might have lesser indented code blocks at the end + if end is None: + end = len(source.lines) + + if end > start + 1: + # make sure we don't span differently indented code blocks + # by using the BlockFinder helper used which inspect.getsource() uses itself + block_finder = inspect.BlockFinder() + # if we start with an indented line, put blockfinder to "started" mode + block_finder.started = source.lines[start][0].isspace() + it = ((x + "\n") for x in source.lines[start:end]) + try: + for tok in tokenize.generate_tokens(lambda: next(it)): + block_finder.tokeneater(*tok) + except (inspect.EndOfBlock, IndentationError): + end = block_finder.last + start + except Exception: + pass + + # the end might still point to a comment or empty line, correct it + while end: + line = source.lines[end - 1].lstrip() + if line.startswith("#") or not line: + end -= 1 + else: + break + return astnode, start, end diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/_version.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..e982d231ef1fe61c8cb799a2e9524f521d31ac67 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/_version.py @@ -0,0 +1,4 @@ +# coding: utf-8 +# file generated by setuptools_scm +# don't change, don't track in version control +version = '4.6.5' diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/assertion/__init__.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/assertion/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6b6abb863a3ff1bb27d4a43d5b109f5fb8a7b754 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/assertion/__init__.py @@ -0,0 +1,156 @@ +# -*- coding: utf-8 -*- +""" +support for presenting detailed information in failing assertions. +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import sys + +import six + +from _pytest.assertion import rewrite +from _pytest.assertion import truncate +from _pytest.assertion import util + + +def pytest_addoption(parser): + group = parser.getgroup("debugconfig") + group.addoption( + "--assert", + action="store", + dest="assertmode", + choices=("rewrite", "plain"), + default="rewrite", + metavar="MODE", + help="""Control assertion debugging tools. 'plain' + performs no assertion debugging. 'rewrite' + (the default) rewrites assert statements in + test modules on import to provide assert + expression information.""", + ) + + +def register_assert_rewrite(*names): + """Register one or more module names to be rewritten on import. + + This function will make sure that this module or all modules inside + the package will get their assert statements rewritten. + Thus you should make sure to call this before the module is + actually imported, usually in your __init__.py if you are a plugin + using a package. + + :raise TypeError: if the given module names are not strings. + """ + for name in names: + if not isinstance(name, str): + msg = "expected module names as *args, got {0} instead" + raise TypeError(msg.format(repr(names))) + for hook in sys.meta_path: + if isinstance(hook, rewrite.AssertionRewritingHook): + importhook = hook + break + else: + importhook = DummyRewriteHook() + importhook.mark_rewrite(*names) + + +class DummyRewriteHook(object): + """A no-op import hook for when rewriting is disabled.""" + + def mark_rewrite(self, *names): + pass + + +class AssertionState(object): + """State for the assertion plugin.""" + + def __init__(self, config, mode): + self.mode = mode + self.trace = config.trace.root.get("assertion") + self.hook = None + + +def install_importhook(config): + """Try to install the rewrite hook, raise SystemError if it fails.""" + # Jython has an AST bug that make the assertion rewriting hook malfunction. + if sys.platform.startswith("java"): + raise SystemError("rewrite not supported") + + config._assertstate = AssertionState(config, "rewrite") + config._assertstate.hook = hook = rewrite.AssertionRewritingHook(config) + sys.meta_path.insert(0, hook) + config._assertstate.trace("installed rewrite import hook") + + def undo(): + hook = config._assertstate.hook + if hook is not None and hook in sys.meta_path: + sys.meta_path.remove(hook) + + config.add_cleanup(undo) + return hook + + +def pytest_collection(session): + # this hook is only called when test modules are collected + # so for example not in the master process of pytest-xdist + # (which does not collect test modules) + assertstate = getattr(session.config, "_assertstate", None) + if assertstate: + if assertstate.hook is not None: + assertstate.hook.set_session(session) + + +def pytest_runtest_setup(item): + """Setup the pytest_assertrepr_compare hook + + The newinterpret and rewrite modules will use util._reprcompare if + it exists to use custom reporting via the + pytest_assertrepr_compare hook. This sets up this custom + comparison for the test. + """ + + def callbinrepr(op, left, right): + """Call the pytest_assertrepr_compare hook and prepare the result + + This uses the first result from the hook and then ensures the + following: + * Overly verbose explanations are truncated unless configured otherwise + (eg. if running in verbose mode). + * Embedded newlines are escaped to help util.format_explanation() + later. + * If the rewrite mode is used embedded %-characters are replaced + to protect later % formatting. + + The result can be formatted by util.format_explanation() for + pretty printing. + """ + hook_result = item.ihook.pytest_assertrepr_compare( + config=item.config, op=op, left=left, right=right + ) + for new_expl in hook_result: + if new_expl: + new_expl = truncate.truncate_if_required(new_expl, item) + new_expl = [line.replace("\n", "\\n") for line in new_expl] + res = six.text_type("\n~").join(new_expl) + if item.config.getvalue("assertmode") == "rewrite": + res = res.replace("%", "%%") + return res + + util._reprcompare = callbinrepr + + +def pytest_runtest_teardown(item): + util._reprcompare = None + + +def pytest_sessionfinish(session): + assertstate = getattr(session.config, "_assertstate", None) + if assertstate: + if assertstate.hook is not None: + assertstate.hook.set_session(None) + + +# Expose this plugin's implementation for the pytest_assertrepr_compare hook +pytest_assertrepr_compare = util.assertrepr_compare diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/assertion/rewrite.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/assertion/rewrite.py new file mode 100644 index 0000000000000000000000000000000000000000..1c6161b212da3bb514e88a42816ff3d420f6ffc9 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/assertion/rewrite.py @@ -0,0 +1,1069 @@ +# -*- coding: utf-8 -*- +"""Rewrite assertion AST to produce nice error messages""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import ast +import errno +import imp +import itertools +import marshal +import os +import re +import string +import struct +import sys +import types + +import atomicwrites +import py +import six + +from _pytest._io.saferepr import saferepr +from _pytest.assertion import util +from _pytest.assertion.util import ( # noqa: F401 + format_explanation as _format_explanation, +) +from _pytest.compat import spec_from_file_location +from _pytest.pathlib import fnmatch_ex +from _pytest.pathlib import PurePath + +# pytest caches rewritten pycs in __pycache__. +if hasattr(imp, "get_tag"): + PYTEST_TAG = imp.get_tag() + "-PYTEST" +else: + if hasattr(sys, "pypy_version_info"): + impl = "pypy" + elif sys.platform == "java": + impl = "jython" + else: + impl = "cpython" + ver = sys.version_info + PYTEST_TAG = "%s-%s%s-PYTEST" % (impl, ver[0], ver[1]) + del ver, impl + +PYC_EXT = ".py" + (__debug__ and "c" or "o") +PYC_TAIL = "." + PYTEST_TAG + PYC_EXT + +ASCII_IS_DEFAULT_ENCODING = sys.version_info[0] < 3 + +if sys.version_info >= (3, 5): + ast_Call = ast.Call +else: + + def ast_Call(a, b, c): + return ast.Call(a, b, c, None, None) + + +class AssertionRewritingHook(object): + """PEP302 Import hook which rewrites asserts.""" + + def __init__(self, config): + self.config = config + try: + self.fnpats = config.getini("python_files") + except ValueError: + self.fnpats = ["test_*.py", "*_test.py"] + self.session = None + self.modules = {} + self._rewritten_names = set() + self._must_rewrite = set() + # flag to guard against trying to rewrite a pyc file while we are already writing another pyc file, + # which might result in infinite recursion (#3506) + self._writing_pyc = False + self._basenames_to_check_rewrite = {"conftest"} + self._marked_for_rewrite_cache = {} + self._session_paths_checked = False + + def set_session(self, session): + self.session = session + self._session_paths_checked = False + + def _imp_find_module(self, name, path=None): + """Indirection so we can mock calls to find_module originated from the hook during testing""" + return imp.find_module(name, path) + + def find_module(self, name, path=None): + if self._writing_pyc: + return None + state = self.config._assertstate + if self._early_rewrite_bailout(name, state): + return None + state.trace("find_module called for: %s" % name) + names = name.rsplit(".", 1) + lastname = names[-1] + pth = None + if path is not None: + # Starting with Python 3.3, path is a _NamespacePath(), which + # causes problems if not converted to list. + path = list(path) + if len(path) == 1: + pth = path[0] + if pth is None: + try: + fd, fn, desc = self._imp_find_module(lastname, path) + except ImportError: + return None + if fd is not None: + fd.close() + tp = desc[2] + if tp == imp.PY_COMPILED: + if hasattr(imp, "source_from_cache"): + try: + fn = imp.source_from_cache(fn) + except ValueError: + # Python 3 doesn't like orphaned but still-importable + # .pyc files. + fn = fn[:-1] + else: + fn = fn[:-1] + elif tp != imp.PY_SOURCE: + # Don't know what this is. + return None + else: + fn = os.path.join(pth, name.rpartition(".")[2] + ".py") + + fn_pypath = py.path.local(fn) + if not self._should_rewrite(name, fn_pypath, state): + return None + + self._rewritten_names.add(name) + + # The requested module looks like a test file, so rewrite it. This is + # the most magical part of the process: load the source, rewrite the + # asserts, and load the rewritten source. We also cache the rewritten + # module code in a special pyc. We must be aware of the possibility of + # concurrent pytest processes rewriting and loading pycs. To avoid + # tricky race conditions, we maintain the following invariant: The + # cached pyc is always a complete, valid pyc. Operations on it must be + # atomic. POSIX's atomic rename comes in handy. + write = not sys.dont_write_bytecode + cache_dir = os.path.join(fn_pypath.dirname, "__pycache__") + if write: + try: + os.mkdir(cache_dir) + except OSError: + e = sys.exc_info()[1].errno + if e == errno.EEXIST: + # Either the __pycache__ directory already exists (the + # common case) or it's blocked by a non-dir node. In the + # latter case, we'll ignore it in _write_pyc. + pass + elif e in [errno.ENOENT, errno.ENOTDIR]: + # One of the path components was not a directory, likely + # because we're in a zip file. + write = False + elif e in [errno.EACCES, errno.EROFS, errno.EPERM]: + state.trace("read only directory: %r" % fn_pypath.dirname) + write = False + else: + raise + cache_name = fn_pypath.basename[:-3] + PYC_TAIL + pyc = os.path.join(cache_dir, cache_name) + # Notice that even if we're in a read-only directory, I'm going + # to check for a cached pyc. This may not be optimal... + co = _read_pyc(fn_pypath, pyc, state.trace) + if co is None: + state.trace("rewriting %r" % (fn,)) + source_stat, co = _rewrite_test(self.config, fn_pypath) + if co is None: + # Probably a SyntaxError in the test. + return None + if write: + self._writing_pyc = True + try: + _write_pyc(state, co, source_stat, pyc) + finally: + self._writing_pyc = False + else: + state.trace("found cached rewritten pyc for %r" % (fn,)) + self.modules[name] = co, pyc + return self + + def _early_rewrite_bailout(self, name, state): + """ + This is a fast way to get out of rewriting modules. Profiling has + shown that the call to imp.find_module (inside of the find_module + from this class) is a major slowdown, so, this method tries to + filter what we're sure won't be rewritten before getting to it. + """ + if self.session is not None and not self._session_paths_checked: + self._session_paths_checked = True + for path in self.session._initialpaths: + # Make something as c:/projects/my_project/path.py -> + # ['c:', 'projects', 'my_project', 'path.py'] + parts = str(path).split(os.path.sep) + # add 'path' to basenames to be checked. + self._basenames_to_check_rewrite.add(os.path.splitext(parts[-1])[0]) + + # Note: conftest already by default in _basenames_to_check_rewrite. + parts = name.split(".") + if parts[-1] in self._basenames_to_check_rewrite: + return False + + # For matching the name it must be as if it was a filename. + path = PurePath(os.path.sep.join(parts) + ".py") + + for pat in self.fnpats: + # if the pattern contains subdirectories ("tests/**.py" for example) we can't bail out based + # on the name alone because we need to match against the full path + if os.path.dirname(pat): + return False + if fnmatch_ex(pat, path): + return False + + if self._is_marked_for_rewrite(name, state): + return False + + state.trace("early skip of rewriting module: %s" % (name,)) + return True + + def _should_rewrite(self, name, fn_pypath, state): + # always rewrite conftest files + fn = str(fn_pypath) + if fn_pypath.basename == "conftest.py": + state.trace("rewriting conftest file: %r" % (fn,)) + return True + + if self.session is not None: + if self.session.isinitpath(fn): + state.trace("matched test file (was specified on cmdline): %r" % (fn,)) + return True + + # modules not passed explicitly on the command line are only + # rewritten if they match the naming convention for test files + for pat in self.fnpats: + if fn_pypath.fnmatch(pat): + state.trace("matched test file %r" % (fn,)) + return True + + return self._is_marked_for_rewrite(name, state) + + def _is_marked_for_rewrite(self, name, state): + try: + return self._marked_for_rewrite_cache[name] + except KeyError: + for marked in self._must_rewrite: + if name == marked or name.startswith(marked + "."): + state.trace("matched marked file %r (from %r)" % (name, marked)) + self._marked_for_rewrite_cache[name] = True + return True + + self._marked_for_rewrite_cache[name] = False + return False + + def mark_rewrite(self, *names): + """Mark import names as needing to be rewritten. + + The named module or package as well as any nested modules will + be rewritten on import. + """ + already_imported = ( + set(names).intersection(sys.modules).difference(self._rewritten_names) + ) + for name in already_imported: + if not AssertionRewriter.is_rewrite_disabled( + sys.modules[name].__doc__ or "" + ): + self._warn_already_imported(name) + self._must_rewrite.update(names) + self._marked_for_rewrite_cache.clear() + + def _warn_already_imported(self, name): + from _pytest.warning_types import PytestAssertRewriteWarning + from _pytest.warnings import _issue_warning_captured + + _issue_warning_captured( + PytestAssertRewriteWarning( + "Module already imported so cannot be rewritten: %s" % name + ), + self.config.hook, + stacklevel=5, + ) + + def load_module(self, name): + co, pyc = self.modules.pop(name) + if name in sys.modules: + # If there is an existing module object named 'fullname' in + # sys.modules, the loader must use that existing module. (Otherwise, + # the reload() builtin will not work correctly.) + mod = sys.modules[name] + else: + # I wish I could just call imp.load_compiled here, but __file__ has to + # be set properly. In Python 3.2+, this all would be handled correctly + # by load_compiled. + mod = sys.modules[name] = imp.new_module(name) + try: + mod.__file__ = co.co_filename + # Normally, this attribute is 3.2+. + mod.__cached__ = pyc + mod.__loader__ = self + # Normally, this attribute is 3.4+ + mod.__spec__ = spec_from_file_location(name, co.co_filename, loader=self) + exec(co, mod.__dict__) + except: # noqa + if name in sys.modules: + del sys.modules[name] + raise + return sys.modules[name] + + def is_package(self, name): + try: + fd, fn, desc = self._imp_find_module(name) + except ImportError: + return False + if fd is not None: + fd.close() + tp = desc[2] + return tp == imp.PKG_DIRECTORY + + def get_data(self, pathname): + """Optional PEP302 get_data API. + """ + with open(pathname, "rb") as f: + return f.read() + + +def _write_pyc(state, co, source_stat, pyc): + # Technically, we don't have to have the same pyc format as + # (C)Python, since these "pycs" should never be seen by builtin + # import. However, there's little reason deviate, and I hope + # sometime to be able to use imp.load_compiled to load them. (See + # the comment in load_module above.) + try: + with atomicwrites.atomic_write(pyc, mode="wb", overwrite=True) as fp: + fp.write(imp.get_magic()) + # as of now, bytecode header expects 32-bit numbers for size and mtime (#4903) + mtime = int(source_stat.mtime) & 0xFFFFFFFF + size = source_stat.size & 0xFFFFFFFF + # ">", + ast.Add: "+", + ast.Sub: "-", + ast.Mult: "*", + ast.Div: "/", + ast.FloorDiv: "//", + ast.Mod: "%%", # escaped for string formatting + ast.Eq: "==", + ast.NotEq: "!=", + ast.Lt: "<", + ast.LtE: "<=", + ast.Gt: ">", + ast.GtE: ">=", + ast.Pow: "**", + ast.Is: "is", + ast.IsNot: "is not", + ast.In: "in", + ast.NotIn: "not in", +} +# Python 3.5+ compatibility +try: + binop_map[ast.MatMult] = "@" +except AttributeError: + pass + +# Python 3.4+ compatibility +if hasattr(ast, "NameConstant"): + _NameConstant = ast.NameConstant +else: + + def _NameConstant(c): + return ast.Name(str(c), ast.Load()) + + +def set_location(node, lineno, col_offset): + """Set node location information recursively.""" + + def _fix(node, lineno, col_offset): + if "lineno" in node._attributes: + node.lineno = lineno + if "col_offset" in node._attributes: + node.col_offset = col_offset + for child in ast.iter_child_nodes(node): + _fix(child, lineno, col_offset) + + _fix(node, lineno, col_offset) + return node + + +class AssertionRewriter(ast.NodeVisitor): + """Assertion rewriting implementation. + + The main entrypoint is to call .run() with an ast.Module instance, + this will then find all the assert statements and rewrite them to + provide intermediate values and a detailed assertion error. See + http://pybites.blogspot.be/2011/07/behind-scenes-of-pytests-new-assertion.html + for an overview of how this works. + + The entry point here is .run() which will iterate over all the + statements in an ast.Module and for each ast.Assert statement it + finds call .visit() with it. Then .visit_Assert() takes over and + is responsible for creating new ast statements to replace the + original assert statement: it rewrites the test of an assertion + to provide intermediate values and replace it with an if statement + which raises an assertion error with a detailed explanation in + case the expression is false. + + For this .visit_Assert() uses the visitor pattern to visit all the + AST nodes of the ast.Assert.test field, each visit call returning + an AST node and the corresponding explanation string. During this + state is kept in several instance attributes: + + :statements: All the AST statements which will replace the assert + statement. + + :variables: This is populated by .variable() with each variable + used by the statements so that they can all be set to None at + the end of the statements. + + :variable_counter: Counter to create new unique variables needed + by statements. Variables are created using .variable() and + have the form of "@py_assert0". + + :on_failure: The AST statements which will be executed if the + assertion test fails. This is the code which will construct + the failure message and raises the AssertionError. + + :explanation_specifiers: A dict filled by .explanation_param() + with %-formatting placeholders and their corresponding + expressions to use in the building of an assertion message. + This is used by .pop_format_context() to build a message. + + :stack: A stack of the explanation_specifiers dicts maintained by + .push_format_context() and .pop_format_context() which allows + to build another %-formatted string while already building one. + + This state is reset on every new assert statement visited and used + by the other visitors. + + """ + + def __init__(self, module_path, config): + super(AssertionRewriter, self).__init__() + self.module_path = module_path + self.config = config + + def run(self, mod): + """Find all assert statements in *mod* and rewrite them.""" + if not mod.body: + # Nothing to do. + return + # Insert some special imports at the top of the module but after any + # docstrings and __future__ imports. + aliases = [ + ast.alias(six.moves.builtins.__name__, "@py_builtins"), + ast.alias("_pytest.assertion.rewrite", "@pytest_ar"), + ] + doc = getattr(mod, "docstring", None) + expect_docstring = doc is None + if doc is not None and self.is_rewrite_disabled(doc): + return + pos = 0 + lineno = 1 + for item in mod.body: + if ( + expect_docstring + and isinstance(item, ast.Expr) + and isinstance(item.value, ast.Str) + ): + doc = item.value.s + if self.is_rewrite_disabled(doc): + return + expect_docstring = False + elif ( + not isinstance(item, ast.ImportFrom) + or item.level > 0 + or item.module != "__future__" + ): + lineno = item.lineno + break + pos += 1 + else: + lineno = item.lineno + imports = [ + ast.Import([alias], lineno=lineno, col_offset=0) for alias in aliases + ] + mod.body[pos:pos] = imports + # Collect asserts. + nodes = [mod] + while nodes: + node = nodes.pop() + for name, field in ast.iter_fields(node): + if isinstance(field, list): + new = [] + for i, child in enumerate(field): + if isinstance(child, ast.Assert): + # Transform assert. + new.extend(self.visit(child)) + else: + new.append(child) + if isinstance(child, ast.AST): + nodes.append(child) + setattr(node, name, new) + elif ( + isinstance(field, ast.AST) + # Don't recurse into expressions as they can't contain + # asserts. + and not isinstance(field, ast.expr) + ): + nodes.append(field) + + @staticmethod + def is_rewrite_disabled(docstring): + return "PYTEST_DONT_REWRITE" in docstring + + def variable(self): + """Get a new variable.""" + # Use a character invalid in python identifiers to avoid clashing. + name = "@py_assert" + str(next(self.variable_counter)) + self.variables.append(name) + return name + + def assign(self, expr): + """Give *expr* a name.""" + name = self.variable() + self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr)) + return ast.Name(name, ast.Load()) + + def display(self, expr): + """Call saferepr on the expression.""" + return self.helper("_saferepr", expr) + + def helper(self, name, *args): + """Call a helper in this module.""" + py_name = ast.Name("@pytest_ar", ast.Load()) + attr = ast.Attribute(py_name, name, ast.Load()) + return ast_Call(attr, list(args), []) + + def builtin(self, name): + """Return the builtin called *name*.""" + builtin_name = ast.Name("@py_builtins", ast.Load()) + return ast.Attribute(builtin_name, name, ast.Load()) + + def explanation_param(self, expr): + """Return a new named %-formatting placeholder for expr. + + This creates a %-formatting placeholder for expr in the + current formatting context, e.g. ``%(py0)s``. The placeholder + and expr are placed in the current format context so that it + can be used on the next call to .pop_format_context(). + + """ + specifier = "py" + str(next(self.variable_counter)) + self.explanation_specifiers[specifier] = expr + return "%(" + specifier + ")s" + + def push_format_context(self): + """Create a new formatting context. + + The format context is used for when an explanation wants to + have a variable value formatted in the assertion message. In + this case the value required can be added using + .explanation_param(). Finally .pop_format_context() is used + to format a string of %-formatted values as added by + .explanation_param(). + + """ + self.explanation_specifiers = {} + self.stack.append(self.explanation_specifiers) + + def pop_format_context(self, expl_expr): + """Format the %-formatted string with current format context. + + The expl_expr should be an ast.Str instance constructed from + the %-placeholders created by .explanation_param(). This will + add the required code to format said string to .on_failure and + return the ast.Name instance of the formatted string. + + """ + current = self.stack.pop() + if self.stack: + self.explanation_specifiers = self.stack[-1] + keys = [ast.Str(key) for key in current.keys()] + format_dict = ast.Dict(keys, list(current.values())) + form = ast.BinOp(expl_expr, ast.Mod(), format_dict) + name = "@py_format" + str(next(self.variable_counter)) + self.on_failure.append(ast.Assign([ast.Name(name, ast.Store())], form)) + return ast.Name(name, ast.Load()) + + def generic_visit(self, node): + """Handle expressions we don't have custom code for.""" + assert isinstance(node, ast.expr) + res = self.assign(node) + return res, self.explanation_param(self.display(res)) + + def visit_Assert(self, assert_): + """Return the AST statements to replace the ast.Assert instance. + + This rewrites the test of an assertion to provide + intermediate values and replace it with an if statement which + raises an assertion error with a detailed explanation in case + the expression is false. + + """ + if isinstance(assert_.test, ast.Tuple) and len(assert_.test.elts) >= 1: + from _pytest.warning_types import PytestAssertRewriteWarning + import warnings + + warnings.warn_explicit( + PytestAssertRewriteWarning( + "assertion is always true, perhaps remove parentheses?" + ), + category=None, + filename=str(self.module_path), + lineno=assert_.lineno, + ) + + self.statements = [] + self.variables = [] + self.variable_counter = itertools.count() + self.stack = [] + self.on_failure = [] + self.push_format_context() + # Rewrite assert into a bunch of statements. + top_condition, explanation = self.visit(assert_.test) + # If in a test module, check if directly asserting None, in order to warn [Issue #3191] + if self.module_path is not None: + self.statements.append( + self.warn_about_none_ast( + top_condition, module_path=self.module_path, lineno=assert_.lineno + ) + ) + # Create failure message. + body = self.on_failure + negation = ast.UnaryOp(ast.Not(), top_condition) + self.statements.append(ast.If(negation, body, [])) + if assert_.msg: + assertmsg = self.helper("_format_assertmsg", assert_.msg) + explanation = "\n>assert " + explanation + else: + assertmsg = ast.Str("") + explanation = "assert " + explanation + template = ast.BinOp(assertmsg, ast.Add(), ast.Str(explanation)) + msg = self.pop_format_context(template) + fmt = self.helper("_format_explanation", msg) + err_name = ast.Name("AssertionError", ast.Load()) + exc = ast_Call(err_name, [fmt], []) + if sys.version_info[0] >= 3: + raise_ = ast.Raise(exc, None) + else: + raise_ = ast.Raise(exc, None, None) + body.append(raise_) + # Clear temporary variables by setting them to None. + if self.variables: + variables = [ast.Name(name, ast.Store()) for name in self.variables] + clear = ast.Assign(variables, _NameConstant(None)) + self.statements.append(clear) + # Fix line numbers. + for stmt in self.statements: + set_location(stmt, assert_.lineno, assert_.col_offset) + return self.statements + + def warn_about_none_ast(self, node, module_path, lineno): + """ + Returns an AST issuing a warning if the value of node is `None`. + This is used to warn the user when asserting a function that asserts + internally already. + See issue #3191 for more details. + """ + + # Using parse because it is different between py2 and py3. + AST_NONE = ast.parse("None").body[0].value + val_is_none = ast.Compare(node, [ast.Is()], [AST_NONE]) + send_warning = ast.parse( + """ +from _pytest.warning_types import PytestAssertRewriteWarning +from warnings import warn_explicit +warn_explicit( + PytestAssertRewriteWarning('asserting the value None, please use "assert is None"'), + category=None, + filename={filename!r}, + lineno={lineno}, +) + """.format( + filename=module_path.strpath, lineno=lineno + ) + ).body + return ast.If(val_is_none, send_warning, []) + + def visit_Name(self, name): + # Display the repr of the name if it's a local variable or + # _should_repr_global_name() thinks it's acceptable. + locs = ast_Call(self.builtin("locals"), [], []) + inlocs = ast.Compare(ast.Str(name.id), [ast.In()], [locs]) + dorepr = self.helper("_should_repr_global_name", name) + test = ast.BoolOp(ast.Or(), [inlocs, dorepr]) + expr = ast.IfExp(test, self.display(name), ast.Str(name.id)) + return name, self.explanation_param(expr) + + def visit_BoolOp(self, boolop): + res_var = self.variable() + expl_list = self.assign(ast.List([], ast.Load())) + app = ast.Attribute(expl_list, "append", ast.Load()) + is_or = int(isinstance(boolop.op, ast.Or)) + body = save = self.statements + fail_save = self.on_failure + levels = len(boolop.values) - 1 + self.push_format_context() + # Process each operand, short-circuting if needed. + for i, v in enumerate(boolop.values): + if i: + fail_inner = [] + # cond is set in a prior loop iteration below + self.on_failure.append(ast.If(cond, fail_inner, [])) # noqa + self.on_failure = fail_inner + self.push_format_context() + res, expl = self.visit(v) + body.append(ast.Assign([ast.Name(res_var, ast.Store())], res)) + expl_format = self.pop_format_context(ast.Str(expl)) + call = ast_Call(app, [expl_format], []) + self.on_failure.append(ast.Expr(call)) + if i < levels: + cond = res + if is_or: + cond = ast.UnaryOp(ast.Not(), cond) + inner = [] + self.statements.append(ast.If(cond, inner, [])) + self.statements = body = inner + self.statements = save + self.on_failure = fail_save + expl_template = self.helper("_format_boolop", expl_list, ast.Num(is_or)) + expl = self.pop_format_context(expl_template) + return ast.Name(res_var, ast.Load()), self.explanation_param(expl) + + def visit_UnaryOp(self, unary): + pattern = unary_map[unary.op.__class__] + operand_res, operand_expl = self.visit(unary.operand) + res = self.assign(ast.UnaryOp(unary.op, operand_res)) + return res, pattern % (operand_expl,) + + def visit_BinOp(self, binop): + symbol = binop_map[binop.op.__class__] + left_expr, left_expl = self.visit(binop.left) + right_expr, right_expl = self.visit(binop.right) + explanation = "(%s %s %s)" % (left_expl, symbol, right_expl) + res = self.assign(ast.BinOp(left_expr, binop.op, right_expr)) + return res, explanation + + def visit_Call_35(self, call): + """ + visit `ast.Call` nodes on Python3.5 and after + """ + new_func, func_expl = self.visit(call.func) + arg_expls = [] + new_args = [] + new_kwargs = [] + for arg in call.args: + res, expl = self.visit(arg) + arg_expls.append(expl) + new_args.append(res) + for keyword in call.keywords: + res, expl = self.visit(keyword.value) + new_kwargs.append(ast.keyword(keyword.arg, res)) + if keyword.arg: + arg_expls.append(keyword.arg + "=" + expl) + else: # **args have `arg` keywords with an .arg of None + arg_expls.append("**" + expl) + + expl = "%s(%s)" % (func_expl, ", ".join(arg_expls)) + new_call = ast.Call(new_func, new_args, new_kwargs) + res = self.assign(new_call) + res_expl = self.explanation_param(self.display(res)) + outer_expl = "%s\n{%s = %s\n}" % (res_expl, res_expl, expl) + return res, outer_expl + + def visit_Starred(self, starred): + # From Python 3.5, a Starred node can appear in a function call + res, expl = self.visit(starred.value) + new_starred = ast.Starred(res, starred.ctx) + return new_starred, "*" + expl + + def visit_Call_legacy(self, call): + """ + visit `ast.Call nodes on 3.4 and below` + """ + new_func, func_expl = self.visit(call.func) + arg_expls = [] + new_args = [] + new_kwargs = [] + new_star = new_kwarg = None + for arg in call.args: + res, expl = self.visit(arg) + new_args.append(res) + arg_expls.append(expl) + for keyword in call.keywords: + res, expl = self.visit(keyword.value) + new_kwargs.append(ast.keyword(keyword.arg, res)) + arg_expls.append(keyword.arg + "=" + expl) + if call.starargs: + new_star, expl = self.visit(call.starargs) + arg_expls.append("*" + expl) + if call.kwargs: + new_kwarg, expl = self.visit(call.kwargs) + arg_expls.append("**" + expl) + expl = "%s(%s)" % (func_expl, ", ".join(arg_expls)) + new_call = ast.Call(new_func, new_args, new_kwargs, new_star, new_kwarg) + res = self.assign(new_call) + res_expl = self.explanation_param(self.display(res)) + outer_expl = "%s\n{%s = %s\n}" % (res_expl, res_expl, expl) + return res, outer_expl + + # ast.Call signature changed on 3.5, + # conditionally change which methods is named + # visit_Call depending on Python version + if sys.version_info >= (3, 5): + visit_Call = visit_Call_35 + else: + visit_Call = visit_Call_legacy + + def visit_Attribute(self, attr): + if not isinstance(attr.ctx, ast.Load): + return self.generic_visit(attr) + value, value_expl = self.visit(attr.value) + res = self.assign(ast.Attribute(value, attr.attr, ast.Load())) + res_expl = self.explanation_param(self.display(res)) + pat = "%s\n{%s = %s.%s\n}" + expl = pat % (res_expl, res_expl, value_expl, attr.attr) + return res, expl + + def visit_Compare(self, comp): + self.push_format_context() + left_res, left_expl = self.visit(comp.left) + if isinstance(comp.left, (ast.Compare, ast.BoolOp)): + left_expl = "({})".format(left_expl) + res_variables = [self.variable() for i in range(len(comp.ops))] + load_names = [ast.Name(v, ast.Load()) for v in res_variables] + store_names = [ast.Name(v, ast.Store()) for v in res_variables] + it = zip(range(len(comp.ops)), comp.ops, comp.comparators) + expls = [] + syms = [] + results = [left_res] + for i, op, next_operand in it: + next_res, next_expl = self.visit(next_operand) + if isinstance(next_operand, (ast.Compare, ast.BoolOp)): + next_expl = "({})".format(next_expl) + results.append(next_res) + sym = binop_map[op.__class__] + syms.append(ast.Str(sym)) + expl = "%s %s %s" % (left_expl, sym, next_expl) + expls.append(ast.Str(expl)) + res_expr = ast.Compare(left_res, [op], [next_res]) + self.statements.append(ast.Assign([store_names[i]], res_expr)) + left_res, left_expl = next_res, next_expl + # Use pytest.assertion.util._reprcompare if that's available. + expl_call = self.helper( + "_call_reprcompare", + ast.Tuple(syms, ast.Load()), + ast.Tuple(load_names, ast.Load()), + ast.Tuple(expls, ast.Load()), + ast.Tuple(results, ast.Load()), + ) + if len(comp.ops) > 1: + res = ast.BoolOp(ast.And(), load_names) + else: + res = load_names[0] + return res, self.explanation_param(self.pop_format_context(expl_call)) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/assertion/truncate.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/assertion/truncate.py new file mode 100644 index 0000000000000000000000000000000000000000..525896ea9add214dd4a424c77a6a2bb065d72017 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/assertion/truncate.py @@ -0,0 +1,102 @@ +# -*- coding: utf-8 -*- +""" +Utilities for truncating assertion output. + +Current default behaviour is to truncate assertion explanations at +~8 terminal lines, unless running in "-vv" mode or running on CI. +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os + +import six + +DEFAULT_MAX_LINES = 8 +DEFAULT_MAX_CHARS = 8 * 80 +USAGE_MSG = "use '-vv' to show" + + +def truncate_if_required(explanation, item, max_length=None): + """ + Truncate this assertion explanation if the given test item is eligible. + """ + if _should_truncate_item(item): + return _truncate_explanation(explanation) + return explanation + + +def _should_truncate_item(item): + """ + Whether or not this test item is eligible for truncation. + """ + verbose = item.config.option.verbose + return verbose < 2 and not _running_on_ci() + + +def _running_on_ci(): + """Check if we're currently running on a CI system.""" + env_vars = ["CI", "BUILD_NUMBER"] + return any(var in os.environ for var in env_vars) + + +def _truncate_explanation(input_lines, max_lines=None, max_chars=None): + """ + Truncate given list of strings that makes up the assertion explanation. + + Truncates to either 8 lines, or 640 characters - whichever the input reaches + first. The remaining lines will be replaced by a usage message. + """ + + if max_lines is None: + max_lines = DEFAULT_MAX_LINES + if max_chars is None: + max_chars = DEFAULT_MAX_CHARS + + # Check if truncation required + input_char_count = len("".join(input_lines)) + if len(input_lines) <= max_lines and input_char_count <= max_chars: + return input_lines + + # Truncate first to max_lines, and then truncate to max_chars if max_chars + # is exceeded. + truncated_explanation = input_lines[:max_lines] + truncated_explanation = _truncate_by_char_count(truncated_explanation, max_chars) + + # Add ellipsis to final line + truncated_explanation[-1] = truncated_explanation[-1] + "..." + + # Append useful message to explanation + truncated_line_count = len(input_lines) - len(truncated_explanation) + truncated_line_count += 1 # Account for the part-truncated final line + msg = "...Full output truncated" + if truncated_line_count == 1: + msg += " ({} line hidden)".format(truncated_line_count) + else: + msg += " ({} lines hidden)".format(truncated_line_count) + msg += ", {}".format(USAGE_MSG) + truncated_explanation.extend([six.text_type(""), six.text_type(msg)]) + return truncated_explanation + + +def _truncate_by_char_count(input_lines, max_chars): + # Check if truncation required + if len("".join(input_lines)) <= max_chars: + return input_lines + + # Find point at which input length exceeds total allowed length + iterated_char_count = 0 + for iterated_index, input_line in enumerate(input_lines): + if iterated_char_count + len(input_line) > max_chars: + break + iterated_char_count += len(input_line) + + # Create truncated explanation with modified final line + truncated_result = input_lines[:iterated_index] + final_line = input_lines[iterated_index] + if final_line: + final_line_truncate_point = max_chars - iterated_char_count + final_line = final_line[:final_line_truncate_point] + truncated_result.append(final_line) + return truncated_result diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/assertion/util.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/assertion/util.py new file mode 100644 index 0000000000000000000000000000000000000000..1fee64ce08d056fb63d12b80f87cd0f2b9ed4ebd --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/assertion/util.py @@ -0,0 +1,418 @@ +# -*- coding: utf-8 -*- +"""Utilities for assertion debugging""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import pprint + +import six + +import _pytest._code +from ..compat import Sequence +from _pytest import outcomes +from _pytest._io.saferepr import saferepr + +# The _reprcompare attribute on the util module is used by the new assertion +# interpretation code and assertion rewriter to detect this plugin was +# loaded and in turn call the hooks defined here as part of the +# DebugInterpreter. +_reprcompare = None + + +# the re-encoding is needed for python2 repr +# with non-ascii characters (see issue 877 and 1379) +def ecu(s): + if isinstance(s, bytes): + return s.decode("UTF-8", "replace") + else: + return s + + +def format_explanation(explanation): + """This formats an explanation + + Normally all embedded newlines are escaped, however there are + three exceptions: \n{, \n} and \n~. The first two are intended + cover nested explanations, see function and attribute explanations + for examples (.visit_Call(), visit_Attribute()). The last one is + for when one explanation needs to span multiple lines, e.g. when + displaying diffs. + """ + explanation = ecu(explanation) + lines = _split_explanation(explanation) + result = _format_lines(lines) + return u"\n".join(result) + + +def _split_explanation(explanation): + """Return a list of individual lines in the explanation + + This will return a list of lines split on '\n{', '\n}' and '\n~'. + Any other newlines will be escaped and appear in the line as the + literal '\n' characters. + """ + raw_lines = (explanation or u"").split("\n") + lines = [raw_lines[0]] + for values in raw_lines[1:]: + if values and values[0] in ["{", "}", "~", ">"]: + lines.append(values) + else: + lines[-1] += "\\n" + values + return lines + + +def _format_lines(lines): + """Format the individual lines + + This will replace the '{', '}' and '~' characters of our mini + formatting language with the proper 'where ...', 'and ...' and ' + + ...' text, taking care of indentation along the way. + + Return a list of formatted lines. + """ + result = lines[:1] + stack = [0] + stackcnt = [0] + for line in lines[1:]: + if line.startswith("{"): + if stackcnt[-1]: + s = u"and " + else: + s = u"where " + stack.append(len(result)) + stackcnt[-1] += 1 + stackcnt.append(0) + result.append(u" +" + u" " * (len(stack) - 1) + s + line[1:]) + elif line.startswith("}"): + stack.pop() + stackcnt.pop() + result[stack[-1]] += line[1:] + else: + assert line[0] in ["~", ">"] + stack[-1] += 1 + indent = len(stack) if line.startswith("~") else len(stack) - 1 + result.append(u" " * indent + line[1:]) + assert len(stack) == 1 + return result + + +# Provide basestring in python3 +try: + basestring = basestring +except NameError: + basestring = str + + +def issequence(x): + return isinstance(x, Sequence) and not isinstance(x, basestring) + + +def istext(x): + return isinstance(x, basestring) + + +def isdict(x): + return isinstance(x, dict) + + +def isset(x): + return isinstance(x, (set, frozenset)) + + +def isdatacls(obj): + return getattr(obj, "__dataclass_fields__", None) is not None + + +def isattrs(obj): + return getattr(obj, "__attrs_attrs__", None) is not None + + +def isiterable(obj): + try: + iter(obj) + return not istext(obj) + except TypeError: + return False + + +def assertrepr_compare(config, op, left, right): + """Return specialised explanations for some operators/operands""" + width = 80 - 15 - len(op) - 2 # 15 chars indentation, 1 space around op + left_repr = saferepr(left, maxsize=int(width // 2)) + right_repr = saferepr(right, maxsize=width - len(left_repr)) + + summary = u"%s %s %s" % (ecu(left_repr), op, ecu(right_repr)) + + verbose = config.getoption("verbose") + explanation = None + try: + if op == "==": + if istext(left) and istext(right): + explanation = _diff_text(left, right, verbose) + else: + if issequence(left) and issequence(right): + explanation = _compare_eq_sequence(left, right, verbose) + elif isset(left) and isset(right): + explanation = _compare_eq_set(left, right, verbose) + elif isdict(left) and isdict(right): + explanation = _compare_eq_dict(left, right, verbose) + elif type(left) == type(right) and (isdatacls(left) or isattrs(left)): + type_fn = (isdatacls, isattrs) + explanation = _compare_eq_cls(left, right, verbose, type_fn) + elif verbose > 0: + explanation = _compare_eq_verbose(left, right) + if isiterable(left) and isiterable(right): + expl = _compare_eq_iterable(left, right, verbose) + if explanation is not None: + explanation.extend(expl) + else: + explanation = expl + elif op == "not in": + if istext(left) and istext(right): + explanation = _notin_text(left, right, verbose) + except outcomes.Exit: + raise + except Exception: + explanation = [ + u"(pytest_assertion plugin: representation of details failed. " + u"Probably an object has a faulty __repr__.)", + six.text_type(_pytest._code.ExceptionInfo.from_current()), + ] + + if not explanation: + return None + + return [summary] + explanation + + +def _diff_text(left, right, verbose=0): + """Return the explanation for the diff between text or bytes. + + Unless --verbose is used this will skip leading and trailing + characters which are identical to keep the diff minimal. + + If the input are bytes they will be safely converted to text. + """ + from difflib import ndiff + + explanation = [] + + def escape_for_readable_diff(binary_text): + """ + Ensures that the internal string is always valid unicode, converting any bytes safely to valid unicode. + This is done using repr() which then needs post-processing to fix the encompassing quotes and un-escape + newlines and carriage returns (#429). + """ + r = six.text_type(repr(binary_text)[1:-1]) + r = r.replace(r"\n", "\n") + r = r.replace(r"\r", "\r") + return r + + if isinstance(left, bytes): + left = escape_for_readable_diff(left) + if isinstance(right, bytes): + right = escape_for_readable_diff(right) + if verbose < 1: + i = 0 # just in case left or right has zero length + for i in range(min(len(left), len(right))): + if left[i] != right[i]: + break + if i > 42: + i -= 10 # Provide some context + explanation = [ + u"Skipping %s identical leading characters in diff, use -v to show" % i + ] + left = left[i:] + right = right[i:] + if len(left) == len(right): + for i in range(len(left)): + if left[-i] != right[-i]: + break + if i > 42: + i -= 10 # Provide some context + explanation += [ + u"Skipping {} identical trailing " + u"characters in diff, use -v to show".format(i) + ] + left = left[:-i] + right = right[:-i] + keepends = True + if left.isspace() or right.isspace(): + left = repr(str(left)) + right = repr(str(right)) + explanation += [u"Strings contain only whitespace, escaping them using repr()"] + explanation += [ + line.strip("\n") + for line in ndiff(left.splitlines(keepends), right.splitlines(keepends)) + ] + return explanation + + +def _compare_eq_verbose(left, right): + keepends = True + left_lines = repr(left).splitlines(keepends) + right_lines = repr(right).splitlines(keepends) + + explanation = [] + explanation += [u"-" + line for line in left_lines] + explanation += [u"+" + line for line in right_lines] + + return explanation + + +def _compare_eq_iterable(left, right, verbose=0): + if not verbose: + return [u"Use -v to get the full diff"] + # dynamic import to speedup pytest + import difflib + + try: + left_formatting = pprint.pformat(left).splitlines() + right_formatting = pprint.pformat(right).splitlines() + explanation = [u"Full diff:"] + except Exception: + # hack: PrettyPrinter.pformat() in python 2 fails when formatting items that can't be sorted(), ie, calling + # sorted() on a list would raise. See issue #718. + # As a workaround, the full diff is generated by using the repr() string of each item of each container. + left_formatting = sorted(repr(x) for x in left) + right_formatting = sorted(repr(x) for x in right) + explanation = [u"Full diff (fallback to calling repr on each item):"] + explanation.extend( + line.strip() for line in difflib.ndiff(left_formatting, right_formatting) + ) + return explanation + + +def _compare_eq_sequence(left, right, verbose=0): + explanation = [] + len_left = len(left) + len_right = len(right) + for i in range(min(len_left, len_right)): + if left[i] != right[i]: + explanation += [u"At index %s diff: %r != %r" % (i, left[i], right[i])] + break + len_diff = len_left - len_right + + if len_diff: + if len_diff > 0: + dir_with_more = "Left" + extra = saferepr(left[len_right]) + else: + len_diff = 0 - len_diff + dir_with_more = "Right" + extra = saferepr(right[len_left]) + + if len_diff == 1: + explanation += [u"%s contains one more item: %s" % (dir_with_more, extra)] + else: + explanation += [ + u"%s contains %d more items, first extra item: %s" + % (dir_with_more, len_diff, extra) + ] + return explanation + + +def _compare_eq_set(left, right, verbose=0): + explanation = [] + diff_left = left - right + diff_right = right - left + if diff_left: + explanation.append(u"Extra items in the left set:") + for item in diff_left: + explanation.append(saferepr(item)) + if diff_right: + explanation.append(u"Extra items in the right set:") + for item in diff_right: + explanation.append(saferepr(item)) + return explanation + + +def _compare_eq_dict(left, right, verbose=0): + explanation = [] + set_left = set(left) + set_right = set(right) + common = set_left.intersection(set_right) + same = {k: left[k] for k in common if left[k] == right[k]} + if same and verbose < 2: + explanation += [u"Omitting %s identical items, use -vv to show" % len(same)] + elif same: + explanation += [u"Common items:"] + explanation += pprint.pformat(same).splitlines() + diff = {k for k in common if left[k] != right[k]} + if diff: + explanation += [u"Differing items:"] + for k in diff: + explanation += [saferepr({k: left[k]}) + " != " + saferepr({k: right[k]})] + extra_left = set_left - set_right + len_extra_left = len(extra_left) + if len_extra_left: + explanation.append( + u"Left contains %d more item%s:" + % (len_extra_left, "" if len_extra_left == 1 else "s") + ) + explanation.extend( + pprint.pformat({k: left[k] for k in extra_left}).splitlines() + ) + extra_right = set_right - set_left + len_extra_right = len(extra_right) + if len_extra_right: + explanation.append( + u"Right contains %d more item%s:" + % (len_extra_right, "" if len_extra_right == 1 else "s") + ) + explanation.extend( + pprint.pformat({k: right[k] for k in extra_right}).splitlines() + ) + return explanation + + +def _compare_eq_cls(left, right, verbose, type_fns): + isdatacls, isattrs = type_fns + if isdatacls(left): + all_fields = left.__dataclass_fields__ + fields_to_check = [field for field, info in all_fields.items() if info.compare] + elif isattrs(left): + all_fields = left.__attrs_attrs__ + fields_to_check = [field.name for field in all_fields if field.cmp] + + same = [] + diff = [] + for field in fields_to_check: + if getattr(left, field) == getattr(right, field): + same.append(field) + else: + diff.append(field) + + explanation = [] + if same and verbose < 2: + explanation.append(u"Omitting %s identical items, use -vv to show" % len(same)) + elif same: + explanation += [u"Matching attributes:"] + explanation += pprint.pformat(same).splitlines() + if diff: + explanation += [u"Differing attributes:"] + for field in diff: + explanation += [ + (u"%s: %r != %r") % (field, getattr(left, field), getattr(right, field)) + ] + return explanation + + +def _notin_text(term, text, verbose=0): + index = text.find(term) + head = text[:index] + tail = text[index + len(term) :] + correct_text = head + tail + diff = _diff_text(correct_text, text, verbose) + newdiff = [u"%s is contained here:" % saferepr(term, maxsize=42)] + for line in diff: + if line.startswith(u"Skipping"): + continue + if line.startswith(u"- "): + continue + if line.startswith(u"+ "): + newdiff.append(u" " + line[2:]) + else: + newdiff.append(line) + return newdiff diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/config/__init__.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6d44bf3d773cef8ba8b776417d095da0c1153cec --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/config/__init__.py @@ -0,0 +1,1101 @@ +# -*- coding: utf-8 -*- +""" command line options, ini-file and conftest.py processing. """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import argparse +import copy +import inspect +import os +import shlex +import sys +import types +import warnings + +import importlib_metadata +import py +import six +from packaging.version import Version +from pluggy import HookimplMarker +from pluggy import HookspecMarker +from pluggy import PluginManager + +import _pytest._code +import _pytest.assertion +import _pytest.hookspec # the extension point definitions +from .exceptions import PrintHelp +from .exceptions import UsageError +from .findpaths import determine_setup +from .findpaths import exists +from _pytest import deprecated +from _pytest._code import ExceptionInfo +from _pytest._code import filter_traceback +from _pytest.compat import lru_cache +from _pytest.compat import safe_str +from _pytest.outcomes import fail +from _pytest.outcomes import Skipped +from _pytest.warning_types import PytestConfigWarning + +hookimpl = HookimplMarker("pytest") +hookspec = HookspecMarker("pytest") + + +class ConftestImportFailure(Exception): + def __init__(self, path, excinfo): + Exception.__init__(self, path, excinfo) + self.path = path + self.excinfo = excinfo + + +def main(args=None, plugins=None): + """ return exit code, after performing an in-process test run. + + :arg args: list of command line arguments. + + :arg plugins: list of plugin objects to be auto-registered during + initialization. + """ + from _pytest.main import EXIT_USAGEERROR + + try: + try: + config = _prepareconfig(args, plugins) + except ConftestImportFailure as e: + exc_info = ExceptionInfo(e.excinfo) + tw = py.io.TerminalWriter(sys.stderr) + tw.line( + "ImportError while loading conftest '{e.path}'.".format(e=e), red=True + ) + exc_info.traceback = exc_info.traceback.filter(filter_traceback) + exc_repr = ( + exc_info.getrepr(style="short", chain=False) + if exc_info.traceback + else exc_info.exconly() + ) + formatted_tb = safe_str(exc_repr) + for line in formatted_tb.splitlines(): + tw.line(line.rstrip(), red=True) + return 4 + else: + try: + return config.hook.pytest_cmdline_main(config=config) + finally: + config._ensure_unconfigure() + except UsageError as e: + tw = py.io.TerminalWriter(sys.stderr) + for msg in e.args: + tw.line("ERROR: {}\n".format(msg), red=True) + return EXIT_USAGEERROR + + +class cmdline(object): # compatibility namespace + main = staticmethod(main) + + +def filename_arg(path, optname): + """ Argparse type validator for filename arguments. + + :path: path of filename + :optname: name of the option + """ + if os.path.isdir(path): + raise UsageError("{} must be a filename, given: {}".format(optname, path)) + return path + + +def directory_arg(path, optname): + """Argparse type validator for directory arguments. + + :path: path of directory + :optname: name of the option + """ + if not os.path.isdir(path): + raise UsageError("{} must be a directory, given: {}".format(optname, path)) + return path + + +# Plugins that cannot be disabled via "-p no:X" currently. +essential_plugins = ( # fmt: off + "mark", + "main", + "runner", + "fixtures", + "helpconfig", # Provides -p. +) # fmt: on + +default_plugins = essential_plugins + ( + "python", + "terminal", + "debugging", + "unittest", + "capture", + "skipping", + "tmpdir", + "monkeypatch", + "recwarn", + "pastebin", + "nose", + "assertion", + "junitxml", + "resultlog", + "doctest", + "cacheprovider", + "freeze_support", + "setuponly", + "setupplan", + "stepwise", + "warnings", + "logging", + "reports", +) + +builtin_plugins = set(default_plugins) +builtin_plugins.add("pytester") + + +def get_config(args=None): + # subsequent calls to main will create a fresh instance + pluginmanager = PytestPluginManager() + config = Config(pluginmanager) + + if args is not None: + # Handle any "-p no:plugin" args. + pluginmanager.consider_preparse(args) + + for spec in default_plugins: + pluginmanager.import_plugin(spec) + return config + + +def get_plugin_manager(): + """ + Obtain a new instance of the + :py:class:`_pytest.config.PytestPluginManager`, with default plugins + already loaded. + + This function can be used by integration with other tools, like hooking + into pytest to run tests into an IDE. + """ + return get_config().pluginmanager + + +def _prepareconfig(args=None, plugins=None): + warning = None + if args is None: + args = sys.argv[1:] + elif isinstance(args, py.path.local): + args = [str(args)] + elif not isinstance(args, (tuple, list)): + msg = "`args` parameter expected to be a list or tuple of strings, got: {!r} (type: {})" + raise TypeError(msg.format(args, type(args))) + + config = get_config(args) + pluginmanager = config.pluginmanager + try: + if plugins: + for plugin in plugins: + if isinstance(plugin, six.string_types): + pluginmanager.consider_pluginarg(plugin) + else: + pluginmanager.register(plugin) + if warning: + from _pytest.warnings import _issue_warning_captured + + _issue_warning_captured(warning, hook=config.hook, stacklevel=4) + return pluginmanager.hook.pytest_cmdline_parse( + pluginmanager=pluginmanager, args=args + ) + except BaseException: + config._ensure_unconfigure() + raise + + +class PytestPluginManager(PluginManager): + """ + Overwrites :py:class:`pluggy.PluginManager ` to add pytest-specific + functionality: + + * loading plugins from the command line, ``PYTEST_PLUGINS`` env variable and + ``pytest_plugins`` global variables found in plugins being loaded; + * ``conftest.py`` loading during start-up; + """ + + def __init__(self): + super(PytestPluginManager, self).__init__("pytest") + self._conftest_plugins = set() + + # state related to local conftest plugins + self._dirpath2confmods = {} + self._conftestpath2mod = {} + self._confcutdir = None + self._noconftest = False + self._duplicatepaths = set() + + self.add_hookspecs(_pytest.hookspec) + self.register(self) + if os.environ.get("PYTEST_DEBUG"): + err = sys.stderr + encoding = getattr(err, "encoding", "utf8") + try: + err = py.io.dupfile(err, encoding=encoding) + except Exception: + pass + self.trace.root.setwriter(err.write) + self.enable_tracing() + + # Config._consider_importhook will set a real object if required. + self.rewrite_hook = _pytest.assertion.DummyRewriteHook() + # Used to know when we are importing conftests after the pytest_configure stage + self._configured = False + + def addhooks(self, module_or_class): + """ + .. deprecated:: 2.8 + + Use :py:meth:`pluggy.PluginManager.add_hookspecs ` + instead. + """ + warnings.warn(deprecated.PLUGIN_MANAGER_ADDHOOKS, stacklevel=2) + return self.add_hookspecs(module_or_class) + + def parse_hookimpl_opts(self, plugin, name): + # pytest hooks are always prefixed with pytest_ + # so we avoid accessing possibly non-readable attributes + # (see issue #1073) + if not name.startswith("pytest_"): + return + # ignore names which can not be hooks + if name == "pytest_plugins": + return + + method = getattr(plugin, name) + opts = super(PytestPluginManager, self).parse_hookimpl_opts(plugin, name) + + # consider only actual functions for hooks (#3775) + if not inspect.isroutine(method): + return + + # collect unmarked hooks as long as they have the `pytest_' prefix + if opts is None and name.startswith("pytest_"): + opts = {} + if opts is not None: + # TODO: DeprecationWarning, people should use hookimpl + # https://github.com/pytest-dev/pytest/issues/4562 + known_marks = {m.name for m in getattr(method, "pytestmark", [])} + + for name in ("tryfirst", "trylast", "optionalhook", "hookwrapper"): + opts.setdefault(name, hasattr(method, name) or name in known_marks) + return opts + + def parse_hookspec_opts(self, module_or_class, name): + opts = super(PytestPluginManager, self).parse_hookspec_opts( + module_or_class, name + ) + if opts is None: + method = getattr(module_or_class, name) + + if name.startswith("pytest_"): + # todo: deprecate hookspec hacks + # https://github.com/pytest-dev/pytest/issues/4562 + known_marks = {m.name for m in getattr(method, "pytestmark", [])} + opts = { + "firstresult": hasattr(method, "firstresult") + or "firstresult" in known_marks, + "historic": hasattr(method, "historic") + or "historic" in known_marks, + } + return opts + + def register(self, plugin, name=None): + if name in ["pytest_catchlog", "pytest_capturelog"]: + warnings.warn( + PytestConfigWarning( + "{} plugin has been merged into the core, " + "please remove it from your requirements.".format( + name.replace("_", "-") + ) + ) + ) + return + ret = super(PytestPluginManager, self).register(plugin, name) + if ret: + self.hook.pytest_plugin_registered.call_historic( + kwargs=dict(plugin=plugin, manager=self) + ) + + if isinstance(plugin, types.ModuleType): + self.consider_module(plugin) + return ret + + def getplugin(self, name): + # support deprecated naming because plugins (xdist e.g.) use it + return self.get_plugin(name) + + def hasplugin(self, name): + """Return True if the plugin with the given name is registered.""" + return bool(self.get_plugin(name)) + + def pytest_configure(self, config): + # XXX now that the pluginmanager exposes hookimpl(tryfirst...) + # we should remove tryfirst/trylast as markers + config.addinivalue_line( + "markers", + "tryfirst: mark a hook implementation function such that the " + "plugin machinery will try to call it first/as early as possible.", + ) + config.addinivalue_line( + "markers", + "trylast: mark a hook implementation function such that the " + "plugin machinery will try to call it last/as late as possible.", + ) + self._configured = True + + # + # internal API for local conftest plugin handling + # + def _set_initial_conftests(self, namespace): + """ load initial conftest files given a preparsed "namespace". + As conftest files may add their own command line options + which have arguments ('--my-opt somepath') we might get some + false positives. All builtin and 3rd party plugins will have + been loaded, however, so common options will not confuse our logic + here. + """ + current = py.path.local() + self._confcutdir = ( + current.join(namespace.confcutdir, abs=True) + if namespace.confcutdir + else None + ) + self._noconftest = namespace.noconftest + self._using_pyargs = namespace.pyargs + testpaths = namespace.file_or_dir + foundanchor = False + for path in testpaths: + path = str(path) + # remove node-id syntax + i = path.find("::") + if i != -1: + path = path[:i] + anchor = current.join(path, abs=1) + if exists(anchor): # we found some file object + self._try_load_conftest(anchor) + foundanchor = True + if not foundanchor: + self._try_load_conftest(current) + + def _try_load_conftest(self, anchor): + self._getconftestmodules(anchor) + # let's also consider test* subdirs + if anchor.check(dir=1): + for x in anchor.listdir("test*"): + if x.check(dir=1): + self._getconftestmodules(x) + + @lru_cache(maxsize=128) + def _getconftestmodules(self, path): + if self._noconftest: + return [] + + if path.isfile(): + directory = path.dirpath() + else: + directory = path + + if six.PY2: # py2 is not using lru_cache. + try: + return self._dirpath2confmods[directory] + except KeyError: + pass + + # XXX these days we may rather want to use config.rootdir + # and allow users to opt into looking into the rootdir parent + # directories instead of requiring to specify confcutdir + clist = [] + for parent in directory.realpath().parts(): + if self._confcutdir and self._confcutdir.relto(parent): + continue + conftestpath = parent.join("conftest.py") + if conftestpath.isfile(): + # Use realpath to avoid loading the same conftest twice + # with build systems that create build directories containing + # symlinks to actual files. + mod = self._importconftest(conftestpath.realpath()) + clist.append(mod) + self._dirpath2confmods[directory] = clist + return clist + + def _rget_with_confmod(self, name, path): + modules = self._getconftestmodules(path) + for mod in reversed(modules): + try: + return mod, getattr(mod, name) + except AttributeError: + continue + raise KeyError(name) + + def _importconftest(self, conftestpath): + try: + return self._conftestpath2mod[conftestpath] + except KeyError: + pkgpath = conftestpath.pypkgpath() + if pkgpath is None: + _ensure_removed_sysmodule(conftestpath.purebasename) + try: + mod = conftestpath.pyimport() + if ( + hasattr(mod, "pytest_plugins") + and self._configured + and not self._using_pyargs + ): + from _pytest.deprecated import ( + PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST, + ) + + fail( + PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST.format( + conftestpath, self._confcutdir + ), + pytrace=False, + ) + except Exception: + raise ConftestImportFailure(conftestpath, sys.exc_info()) + + self._conftest_plugins.add(mod) + self._conftestpath2mod[conftestpath] = mod + dirpath = conftestpath.dirpath() + if dirpath in self._dirpath2confmods: + for path, mods in self._dirpath2confmods.items(): + if path and path.relto(dirpath) or path == dirpath: + assert mod not in mods + mods.append(mod) + self.trace("loaded conftestmodule %r" % (mod)) + self.consider_conftest(mod) + return mod + + # + # API for bootstrapping plugin loading + # + # + + def consider_preparse(self, args): + i = 0 + n = len(args) + while i < n: + opt = args[i] + i += 1 + if isinstance(opt, six.string_types): + if opt == "-p": + try: + parg = args[i] + except IndexError: + return + i += 1 + elif opt.startswith("-p"): + parg = opt[2:] + else: + continue + self.consider_pluginarg(parg) + + def consider_pluginarg(self, arg): + if arg.startswith("no:"): + name = arg[3:] + if name in essential_plugins: + raise UsageError("plugin %s cannot be disabled" % name) + + # PR #4304 : remove stepwise if cacheprovider is blocked + if name == "cacheprovider": + self.set_blocked("stepwise") + self.set_blocked("pytest_stepwise") + + self.set_blocked(name) + if not name.startswith("pytest_"): + self.set_blocked("pytest_" + name) + else: + name = arg + # Unblock the plugin. None indicates that it has been blocked. + # There is no interface with pluggy for this. + if self._name2plugin.get(name, -1) is None: + del self._name2plugin[name] + if not name.startswith("pytest_"): + if self._name2plugin.get("pytest_" + name, -1) is None: + del self._name2plugin["pytest_" + name] + self.import_plugin(arg, consider_entry_points=True) + + def consider_conftest(self, conftestmodule): + self.register(conftestmodule, name=conftestmodule.__file__) + + def consider_env(self): + self._import_plugin_specs(os.environ.get("PYTEST_PLUGINS")) + + def consider_module(self, mod): + self._import_plugin_specs(getattr(mod, "pytest_plugins", [])) + + def _import_plugin_specs(self, spec): + plugins = _get_plugin_specs_as_list(spec) + for import_spec in plugins: + self.import_plugin(import_spec) + + def import_plugin(self, modname, consider_entry_points=False): + """ + Imports a plugin with ``modname``. If ``consider_entry_points`` is True, entry point + names are also considered to find a plugin. + """ + # most often modname refers to builtin modules, e.g. "pytester", + # "terminal" or "capture". Those plugins are registered under their + # basename for historic purposes but must be imported with the + # _pytest prefix. + assert isinstance(modname, six.string_types), ( + "module name as text required, got %r" % modname + ) + modname = str(modname) + if self.is_blocked(modname) or self.get_plugin(modname) is not None: + return + + importspec = "_pytest." + modname if modname in builtin_plugins else modname + self.rewrite_hook.mark_rewrite(importspec) + + if consider_entry_points: + loaded = self.load_setuptools_entrypoints("pytest11", name=modname) + if loaded: + return + + try: + __import__(importspec) + except ImportError as e: + new_exc_message = 'Error importing plugin "%s": %s' % ( + modname, + safe_str(e.args[0]), + ) + new_exc = ImportError(new_exc_message) + tb = sys.exc_info()[2] + + six.reraise(ImportError, new_exc, tb) + + except Skipped as e: + from _pytest.warnings import _issue_warning_captured + + _issue_warning_captured( + PytestConfigWarning("skipped plugin %r: %s" % (modname, e.msg)), + self.hook, + stacklevel=1, + ) + else: + mod = sys.modules[importspec] + self.register(mod, modname) + + +def _get_plugin_specs_as_list(specs): + """ + Parses a list of "plugin specs" and returns a list of plugin names. + + Plugin specs can be given as a list of strings separated by "," or already as a list/tuple in + which case it is returned as a list. Specs can also be `None` in which case an + empty list is returned. + """ + if specs is not None and not isinstance(specs, types.ModuleType): + if isinstance(specs, six.string_types): + specs = specs.split(",") if specs else [] + if not isinstance(specs, (list, tuple)): + raise UsageError( + "Plugin specs must be a ','-separated string or a " + "list/tuple of strings for plugin names. Given: %r" % specs + ) + return list(specs) + return [] + + +def _ensure_removed_sysmodule(modname): + try: + del sys.modules[modname] + except KeyError: + pass + + +class Notset(object): + def __repr__(self): + return "" + + +notset = Notset() + + +def _iter_rewritable_modules(package_files): + for fn in package_files: + is_simple_module = "/" not in fn and fn.endswith(".py") + is_package = fn.count("/") == 1 and fn.endswith("__init__.py") + if is_simple_module: + module_name, _ = os.path.splitext(fn) + yield module_name + elif is_package: + package_name = os.path.dirname(fn) + yield package_name + + +class Config(object): + """ access to configuration values, pluginmanager and plugin hooks. """ + + def __init__(self, pluginmanager): + #: access to command line option as attributes. + #: (deprecated), use :py:func:`getoption() <_pytest.config.Config.getoption>` instead + self.option = argparse.Namespace() + from .argparsing import Parser, FILE_OR_DIR + + _a = FILE_OR_DIR + self._parser = Parser( + usage="%%(prog)s [options] [%s] [%s] [...]" % (_a, _a), + processopt=self._processopt, + ) + #: a pluginmanager instance + self.pluginmanager = pluginmanager + self.trace = self.pluginmanager.trace.root.get("config") + self.hook = self.pluginmanager.hook + self._inicache = {} + self._override_ini = () + self._opt2dest = {} + self._cleanup = [] + self.pluginmanager.register(self, "pytestconfig") + self._configured = False + self.invocation_dir = py.path.local() + self.hook.pytest_addoption.call_historic(kwargs=dict(parser=self._parser)) + + def add_cleanup(self, func): + """ Add a function to be called when the config object gets out of + use (usually coninciding with pytest_unconfigure).""" + self._cleanup.append(func) + + def _do_configure(self): + assert not self._configured + self._configured = True + self.hook.pytest_configure.call_historic(kwargs=dict(config=self)) + + def _ensure_unconfigure(self): + if self._configured: + self._configured = False + self.hook.pytest_unconfigure(config=self) + self.hook.pytest_configure._call_history = [] + while self._cleanup: + fin = self._cleanup.pop() + fin() + + def get_terminal_writer(self): + return self.pluginmanager.get_plugin("terminalreporter")._tw + + def pytest_cmdline_parse(self, pluginmanager, args): + try: + self.parse(args) + except UsageError: + + # Handle --version and --help here in a minimal fashion. + # This gets done via helpconfig normally, but its + # pytest_cmdline_main is not called in case of errors. + if getattr(self.option, "version", False) or "--version" in args: + from _pytest.helpconfig import showversion + + showversion(self) + elif ( + getattr(self.option, "help", False) or "--help" in args or "-h" in args + ): + self._parser._getparser().print_help() + sys.stdout.write( + "\nNOTE: displaying only minimal help due to UsageError.\n\n" + ) + + raise + + return self + + def notify_exception(self, excinfo, option=None): + if option and getattr(option, "fulltrace", False): + style = "long" + else: + style = "native" + excrepr = excinfo.getrepr( + funcargs=True, showlocals=getattr(option, "showlocals", False), style=style + ) + res = self.hook.pytest_internalerror(excrepr=excrepr, excinfo=excinfo) + if not any(res): + for line in str(excrepr).split("\n"): + sys.stderr.write("INTERNALERROR> %s\n" % line) + sys.stderr.flush() + + def cwd_relative_nodeid(self, nodeid): + # nodeid's are relative to the rootpath, compute relative to cwd + if self.invocation_dir != self.rootdir: + fullpath = self.rootdir.join(nodeid) + nodeid = self.invocation_dir.bestrelpath(fullpath) + return nodeid + + @classmethod + def fromdictargs(cls, option_dict, args): + """ constructor useable for subprocesses. """ + config = get_config(args) + config.option.__dict__.update(option_dict) + config.parse(args, addopts=False) + for x in config.option.plugins: + config.pluginmanager.consider_pluginarg(x) + return config + + def _processopt(self, opt): + for name in opt._short_opts + opt._long_opts: + self._opt2dest[name] = opt.dest + + if hasattr(opt, "default") and opt.dest: + if not hasattr(self.option, opt.dest): + setattr(self.option, opt.dest, opt.default) + + @hookimpl(trylast=True) + def pytest_load_initial_conftests(self, early_config): + self.pluginmanager._set_initial_conftests(early_config.known_args_namespace) + + def _initini(self, args): + ns, unknown_args = self._parser.parse_known_and_unknown_args( + args, namespace=copy.copy(self.option) + ) + r = determine_setup( + ns.inifilename, + ns.file_or_dir + unknown_args, + rootdir_cmd_arg=ns.rootdir or None, + config=self, + ) + self.rootdir, self.inifile, self.inicfg = r + self._parser.extra_info["rootdir"] = self.rootdir + self._parser.extra_info["inifile"] = self.inifile + self._parser.addini("addopts", "extra command line options", "args") + self._parser.addini("minversion", "minimally required pytest version") + self._override_ini = ns.override_ini or () + + def _consider_importhook(self, args): + """Install the PEP 302 import hook if using assertion rewriting. + + Needs to parse the --assert= option from the commandline + and find all the installed plugins to mark them for rewriting + by the importhook. + """ + ns, unknown_args = self._parser.parse_known_and_unknown_args(args) + mode = getattr(ns, "assertmode", "plain") + if mode == "rewrite": + try: + hook = _pytest.assertion.install_importhook(self) + except SystemError: + mode = "plain" + else: + self._mark_plugins_for_rewrite(hook) + _warn_about_missing_assertion(mode) + + def _mark_plugins_for_rewrite(self, hook): + """ + Given an importhook, mark for rewrite any top-level + modules or packages in the distribution package for + all pytest plugins. + """ + self.pluginmanager.rewrite_hook = hook + + if os.environ.get("PYTEST_DISABLE_PLUGIN_AUTOLOAD"): + # We don't autoload from setuptools entry points, no need to continue. + return + + package_files = ( + str(file) + for dist in importlib_metadata.distributions() + if any(ep.group == "pytest11" for ep in dist.entry_points) + for file in dist.files or [] + ) + + for name in _iter_rewritable_modules(package_files): + hook.mark_rewrite(name) + + def _validate_args(self, args, via): + """Validate known args.""" + self._parser._config_source_hint = via + try: + self._parser.parse_known_and_unknown_args( + args, namespace=copy.copy(self.option) + ) + finally: + del self._parser._config_source_hint + + return args + + def _preparse(self, args, addopts=True): + if addopts: + env_addopts = os.environ.get("PYTEST_ADDOPTS", "") + if len(env_addopts): + args[:] = ( + self._validate_args(shlex.split(env_addopts), "via PYTEST_ADDOPTS") + + args + ) + self._initini(args) + if addopts: + args[:] = ( + self._validate_args(self.getini("addopts"), "via addopts config") + args + ) + + self._checkversion() + self._consider_importhook(args) + self.pluginmanager.consider_preparse(args) + if not os.environ.get("PYTEST_DISABLE_PLUGIN_AUTOLOAD"): + # Don't autoload from setuptools entry point. Only explicitly specified + # plugins are going to be loaded. + self.pluginmanager.load_setuptools_entrypoints("pytest11") + self.pluginmanager.consider_env() + self.known_args_namespace = ns = self._parser.parse_known_args( + args, namespace=copy.copy(self.option) + ) + if self.known_args_namespace.confcutdir is None and self.inifile: + confcutdir = py.path.local(self.inifile).dirname + self.known_args_namespace.confcutdir = confcutdir + try: + self.hook.pytest_load_initial_conftests( + early_config=self, args=args, parser=self._parser + ) + except ConftestImportFailure: + e = sys.exc_info()[1] + if ns.help or ns.version: + # we don't want to prevent --help/--version to work + # so just let is pass and print a warning at the end + from _pytest.warnings import _issue_warning_captured + + _issue_warning_captured( + PytestConfigWarning( + "could not load initial conftests: {}".format(e.path) + ), + self.hook, + stacklevel=2, + ) + else: + raise + + def _checkversion(self): + import pytest + + minver = self.inicfg.get("minversion", None) + if minver: + if Version(minver) > Version(pytest.__version__): + raise pytest.UsageError( + "%s:%d: requires pytest-%s, actual pytest-%s'" + % ( + self.inicfg.config.path, + self.inicfg.lineof("minversion"), + minver, + pytest.__version__, + ) + ) + + def parse(self, args, addopts=True): + # parse given cmdline arguments into this config object. + assert not hasattr( + self, "args" + ), "can only parse cmdline args at most once per Config object" + self._origargs = args + self.hook.pytest_addhooks.call_historic( + kwargs=dict(pluginmanager=self.pluginmanager) + ) + self._preparse(args, addopts=addopts) + # XXX deprecated hook: + self.hook.pytest_cmdline_preparse(config=self, args=args) + self._parser.after_preparse = True + try: + args = self._parser.parse_setoption( + args, self.option, namespace=self.option + ) + if not args: + if self.invocation_dir == self.rootdir: + args = self.getini("testpaths") + if not args: + args = [str(self.invocation_dir)] + self.args = args + except PrintHelp: + pass + + def addinivalue_line(self, name, line): + """ add a line to an ini-file option. The option must have been + declared but might not yet be set in which case the line becomes the + the first line in its value. """ + x = self.getini(name) + assert isinstance(x, list) + x.append(line) # modifies the cached list inline + + def getini(self, name): + """ return configuration value from an :ref:`ini file `. If the + specified name hasn't been registered through a prior + :py:func:`parser.addini <_pytest.config.Parser.addini>` + call (usually from a plugin), a ValueError is raised. """ + try: + return self._inicache[name] + except KeyError: + self._inicache[name] = val = self._getini(name) + return val + + def _getini(self, name): + try: + description, type, default = self._parser._inidict[name] + except KeyError: + raise ValueError("unknown configuration value: %r" % (name,)) + value = self._get_override_ini_value(name) + if value is None: + try: + value = self.inicfg[name] + except KeyError: + if default is not None: + return default + if type is None: + return "" + return [] + if type == "pathlist": + dp = py.path.local(self.inicfg.config.path).dirpath() + values = [] + for relpath in shlex.split(value): + values.append(dp.join(relpath, abs=True)) + return values + elif type == "args": + return shlex.split(value) + elif type == "linelist": + return [t for t in map(lambda x: x.strip(), value.split("\n")) if t] + elif type == "bool": + return bool(_strtobool(value.strip())) + else: + assert type is None + return value + + def _getconftest_pathlist(self, name, path): + try: + mod, relroots = self.pluginmanager._rget_with_confmod(name, path) + except KeyError: + return None + modpath = py.path.local(mod.__file__).dirpath() + values = [] + for relroot in relroots: + if not isinstance(relroot, py.path.local): + relroot = relroot.replace("/", py.path.local.sep) + relroot = modpath.join(relroot, abs=True) + values.append(relroot) + return values + + def _get_override_ini_value(self, name): + value = None + # override_ini is a list of "ini=value" options + # always use the last item if multiple values are set for same ini-name, + # e.g. -o foo=bar1 -o foo=bar2 will set foo to bar2 + for ini_config in self._override_ini: + try: + key, user_ini_value = ini_config.split("=", 1) + except ValueError: + raise UsageError("-o/--override-ini expects option=value style.") + else: + if key == name: + value = user_ini_value + return value + + def getoption(self, name, default=notset, skip=False): + """ return command line option value. + + :arg name: name of the option. You may also specify + the literal ``--OPT`` option instead of the "dest" option name. + :arg default: default value if no option of that name exists. + :arg skip: if True raise pytest.skip if option does not exists + or has a None value. + """ + name = self._opt2dest.get(name, name) + try: + val = getattr(self.option, name) + if val is None and skip: + raise AttributeError(name) + return val + except AttributeError: + if default is not notset: + return default + if skip: + import pytest + + pytest.skip("no %r option found" % (name,)) + raise ValueError("no option named %r" % (name,)) + + def getvalue(self, name, path=None): + """ (deprecated, use getoption()) """ + return self.getoption(name) + + def getvalueorskip(self, name, path=None): + """ (deprecated, use getoption(skip=True)) """ + return self.getoption(name, skip=True) + + +def _assertion_supported(): + try: + assert False + except AssertionError: + return True + else: + return False + + +def _warn_about_missing_assertion(mode): + if not _assertion_supported(): + if mode == "plain": + sys.stderr.write( + "WARNING: ASSERTIONS ARE NOT EXECUTED" + " and FAILING TESTS WILL PASS. Are you" + " using python -O?" + ) + else: + sys.stderr.write( + "WARNING: assertions not in test modules or" + " plugins will be ignored" + " because assert statements are not executed " + "by the underlying Python interpreter " + "(are you using python -O?)\n" + ) + + +def setns(obj, dic): + import pytest + + for name, value in dic.items(): + if isinstance(value, dict): + mod = getattr(obj, name, None) + if mod is None: + modname = "pytest.%s" % name + mod = types.ModuleType(modname) + sys.modules[modname] = mod + mod.__all__ = [] + setattr(obj, name, mod) + obj.__all__.append(name) + setns(mod, value) + else: + setattr(obj, name, value) + obj.__all__.append(name) + # if obj != pytest: + # pytest.__all__.append(name) + setattr(pytest, name, value) + + +def create_terminal_writer(config, *args, **kwargs): + """Create a TerminalWriter instance configured according to the options + in the config object. Every code which requires a TerminalWriter object + and has access to a config object should use this function. + """ + tw = py.io.TerminalWriter(*args, **kwargs) + if config.option.color == "yes": + tw.hasmarkup = True + if config.option.color == "no": + tw.hasmarkup = False + return tw + + +def _strtobool(val): + """Convert a string representation of truth to true (1) or false (0). + + True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values + are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if + 'val' is anything else. + + .. note:: copied from distutils.util + """ + val = val.lower() + if val in ("y", "yes", "t", "true", "on", "1"): + return 1 + elif val in ("n", "no", "f", "false", "off", "0"): + return 0 + else: + raise ValueError("invalid truth value %r" % (val,)) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/config/argparsing.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/config/argparsing.py new file mode 100644 index 0000000000000000000000000000000000000000..37fb772db997ec8821ece63f904f9381cf3cf036 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/config/argparsing.py @@ -0,0 +1,410 @@ +# -*- coding: utf-8 -*- +import argparse +import warnings + +import py +import six + +from _pytest.config.exceptions import UsageError + +FILE_OR_DIR = "file_or_dir" + + +class Parser(object): + """ Parser for command line arguments and ini-file values. + + :ivar extra_info: dict of generic param -> value to display in case + there's an error processing the command line arguments. + """ + + prog = None + + def __init__(self, usage=None, processopt=None): + self._anonymous = OptionGroup("custom options", parser=self) + self._groups = [] + self._processopt = processopt + self._usage = usage + self._inidict = {} + self._ininames = [] + self.extra_info = {} + + def processoption(self, option): + if self._processopt: + if option.dest: + self._processopt(option) + + def getgroup(self, name, description="", after=None): + """ get (or create) a named option Group. + + :name: name of the option group. + :description: long description for --help output. + :after: name of other group, used for ordering --help output. + + The returned group object has an ``addoption`` method with the same + signature as :py:func:`parser.addoption + <_pytest.config.Parser.addoption>` but will be shown in the + respective group in the output of ``pytest. --help``. + """ + for group in self._groups: + if group.name == name: + return group + group = OptionGroup(name, description, parser=self) + i = 0 + for i, grp in enumerate(self._groups): + if grp.name == after: + break + self._groups.insert(i + 1, group) + return group + + def addoption(self, *opts, **attrs): + """ register a command line option. + + :opts: option names, can be short or long options. + :attrs: same attributes which the ``add_option()`` function of the + `argparse library + `_ + accepts. + + After command line parsing options are available on the pytest config + object via ``config.option.NAME`` where ``NAME`` is usually set + by passing a ``dest`` attribute, for example + ``addoption("--long", dest="NAME", ...)``. + """ + self._anonymous.addoption(*opts, **attrs) + + def parse(self, args, namespace=None): + from _pytest._argcomplete import try_argcomplete + + self.optparser = self._getparser() + try_argcomplete(self.optparser) + args = [str(x) if isinstance(x, py.path.local) else x for x in args] + return self.optparser.parse_args(args, namespace=namespace) + + def _getparser(self): + from _pytest._argcomplete import filescompleter + + optparser = MyOptionParser(self, self.extra_info, prog=self.prog) + groups = self._groups + [self._anonymous] + for group in groups: + if group.options: + desc = group.description or group.name + arggroup = optparser.add_argument_group(desc) + for option in group.options: + n = option.names() + a = option.attrs() + arggroup.add_argument(*n, **a) + # bash like autocompletion for dirs (appending '/') + optparser.add_argument(FILE_OR_DIR, nargs="*").completer = filescompleter + return optparser + + def parse_setoption(self, args, option, namespace=None): + parsedoption = self.parse(args, namespace=namespace) + for name, value in parsedoption.__dict__.items(): + setattr(option, name, value) + return getattr(parsedoption, FILE_OR_DIR) + + def parse_known_args(self, args, namespace=None): + """parses and returns a namespace object with known arguments at this + point. + """ + return self.parse_known_and_unknown_args(args, namespace=namespace)[0] + + def parse_known_and_unknown_args(self, args, namespace=None): + """parses and returns a namespace object with known arguments, and + the remaining arguments unknown at this point. + """ + optparser = self._getparser() + args = [str(x) if isinstance(x, py.path.local) else x for x in args] + return optparser.parse_known_args(args, namespace=namespace) + + def addini(self, name, help, type=None, default=None): + """ register an ini-file option. + + :name: name of the ini-variable + :type: type of the variable, can be ``pathlist``, ``args``, ``linelist`` + or ``bool``. + :default: default value if no ini-file option exists but is queried. + + The value of ini-variables can be retrieved via a call to + :py:func:`config.getini(name) <_pytest.config.Config.getini>`. + """ + assert type in (None, "pathlist", "args", "linelist", "bool") + self._inidict[name] = (help, type, default) + self._ininames.append(name) + + +class ArgumentError(Exception): + """ + Raised if an Argument instance is created with invalid or + inconsistent arguments. + """ + + def __init__(self, msg, option): + self.msg = msg + self.option_id = str(option) + + def __str__(self): + if self.option_id: + return "option %s: %s" % (self.option_id, self.msg) + else: + return self.msg + + +class Argument(object): + """class that mimics the necessary behaviour of optparse.Option + + it's currently a least effort implementation + and ignoring choices and integer prefixes + https://docs.python.org/3/library/optparse.html#optparse-standard-option-types + """ + + _typ_map = {"int": int, "string": str, "float": float, "complex": complex} + + def __init__(self, *names, **attrs): + """store parms in private vars for use in add_argument""" + self._attrs = attrs + self._short_opts = [] + self._long_opts = [] + self.dest = attrs.get("dest") + if "%default" in (attrs.get("help") or ""): + warnings.warn( + 'pytest now uses argparse. "%default" should be' + ' changed to "%(default)s" ', + DeprecationWarning, + stacklevel=3, + ) + try: + typ = attrs["type"] + except KeyError: + pass + else: + # this might raise a keyerror as well, don't want to catch that + if isinstance(typ, six.string_types): + if typ == "choice": + warnings.warn( + "`type` argument to addoption() is the string %r." + " For choices this is optional and can be omitted, " + " but when supplied should be a type (for example `str` or `int`)." + " (options: %s)" % (typ, names), + DeprecationWarning, + stacklevel=4, + ) + # argparse expects a type here take it from + # the type of the first element + attrs["type"] = type(attrs["choices"][0]) + else: + warnings.warn( + "`type` argument to addoption() is the string %r, " + " but when supplied should be a type (for example `str` or `int`)." + " (options: %s)" % (typ, names), + DeprecationWarning, + stacklevel=4, + ) + attrs["type"] = Argument._typ_map[typ] + # used in test_parseopt -> test_parse_defaultgetter + self.type = attrs["type"] + else: + self.type = typ + try: + # attribute existence is tested in Config._processopt + self.default = attrs["default"] + except KeyError: + pass + self._set_opt_strings(names) + if not self.dest: + if self._long_opts: + self.dest = self._long_opts[0][2:].replace("-", "_") + else: + try: + self.dest = self._short_opts[0][1:] + except IndexError: + raise ArgumentError("need a long or short option", self) + + def names(self): + return self._short_opts + self._long_opts + + def attrs(self): + # update any attributes set by processopt + attrs = "default dest help".split() + if self.dest: + attrs.append(self.dest) + for attr in attrs: + try: + self._attrs[attr] = getattr(self, attr) + except AttributeError: + pass + if self._attrs.get("help"): + a = self._attrs["help"] + a = a.replace("%default", "%(default)s") + # a = a.replace('%prog', '%(prog)s') + self._attrs["help"] = a + return self._attrs + + def _set_opt_strings(self, opts): + """directly from optparse + + might not be necessary as this is passed to argparse later on""" + for opt in opts: + if len(opt) < 2: + raise ArgumentError( + "invalid option string %r: " + "must be at least two characters long" % opt, + self, + ) + elif len(opt) == 2: + if not (opt[0] == "-" and opt[1] != "-"): + raise ArgumentError( + "invalid short option string %r: " + "must be of the form -x, (x any non-dash char)" % opt, + self, + ) + self._short_opts.append(opt) + else: + if not (opt[0:2] == "--" and opt[2] != "-"): + raise ArgumentError( + "invalid long option string %r: " + "must start with --, followed by non-dash" % opt, + self, + ) + self._long_opts.append(opt) + + def __repr__(self): + args = [] + if self._short_opts: + args += ["_short_opts: " + repr(self._short_opts)] + if self._long_opts: + args += ["_long_opts: " + repr(self._long_opts)] + args += ["dest: " + repr(self.dest)] + if hasattr(self, "type"): + args += ["type: " + repr(self.type)] + if hasattr(self, "default"): + args += ["default: " + repr(self.default)] + return "Argument({})".format(", ".join(args)) + + +class OptionGroup(object): + def __init__(self, name, description="", parser=None): + self.name = name + self.description = description + self.options = [] + self.parser = parser + + def addoption(self, *optnames, **attrs): + """ add an option to this group. + + if a shortened version of a long option is specified it will + be suppressed in the help. addoption('--twowords', '--two-words') + results in help showing '--two-words' only, but --twowords gets + accepted **and** the automatic destination is in args.twowords + """ + conflict = set(optnames).intersection( + name for opt in self.options for name in opt.names() + ) + if conflict: + raise ValueError("option names %s already added" % conflict) + option = Argument(*optnames, **attrs) + self._addoption_instance(option, shortupper=False) + + def _addoption(self, *optnames, **attrs): + option = Argument(*optnames, **attrs) + self._addoption_instance(option, shortupper=True) + + def _addoption_instance(self, option, shortupper=False): + if not shortupper: + for opt in option._short_opts: + if opt[0] == "-" and opt[1].islower(): + raise ValueError("lowercase shortoptions reserved") + if self.parser: + self.parser.processoption(option) + self.options.append(option) + + +class MyOptionParser(argparse.ArgumentParser): + def __init__(self, parser, extra_info=None, prog=None): + if not extra_info: + extra_info = {} + self._parser = parser + argparse.ArgumentParser.__init__( + self, + prog=prog, + usage=parser._usage, + add_help=False, + formatter_class=DropShorterLongHelpFormatter, + ) + # extra_info is a dict of (param -> value) to display if there's + # an usage error to provide more contextual information to the user + self.extra_info = extra_info + + def error(self, message): + """Transform argparse error message into UsageError.""" + msg = "%s: error: %s" % (self.prog, message) + + if hasattr(self._parser, "_config_source_hint"): + msg = "%s (%s)" % (msg, self._parser._config_source_hint) + + raise UsageError(self.format_usage() + msg) + + def parse_args(self, args=None, namespace=None): + """allow splitting of positional arguments""" + args, argv = self.parse_known_args(args, namespace) + if argv: + for arg in argv: + if arg and arg[0] == "-": + lines = ["unrecognized arguments: %s" % (" ".join(argv))] + for k, v in sorted(self.extra_info.items()): + lines.append(" %s: %s" % (k, v)) + self.error("\n".join(lines)) + getattr(args, FILE_OR_DIR).extend(argv) + return args + + +class DropShorterLongHelpFormatter(argparse.HelpFormatter): + """shorten help for long options that differ only in extra hyphens + + - collapse **long** options that are the same except for extra hyphens + - special action attribute map_long_option allows surpressing additional + long options + - shortcut if there are only two options and one of them is a short one + - cache result on action object as this is called at least 2 times + """ + + def _format_action_invocation(self, action): + orgstr = argparse.HelpFormatter._format_action_invocation(self, action) + if orgstr and orgstr[0] != "-": # only optional arguments + return orgstr + res = getattr(action, "_formatted_action_invocation", None) + if res: + return res + options = orgstr.split(", ") + if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2): + # a shortcut for '-h, --help' or '--abc', '-a' + action._formatted_action_invocation = orgstr + return orgstr + return_list = [] + option_map = getattr(action, "map_long_option", {}) + if option_map is None: + option_map = {} + short_long = {} + for option in options: + if len(option) == 2 or option[2] == " ": + continue + if not option.startswith("--"): + raise ArgumentError( + 'long optional argument without "--": [%s]' % (option), self + ) + xxoption = option[2:] + if xxoption.split()[0] not in option_map: + shortened = xxoption.replace("-", "") + if shortened not in short_long or len(short_long[shortened]) < len( + xxoption + ): + short_long[shortened] = xxoption + # now short_long has been filled out to the longest with dashes + # **and** we keep the right option ordering from add_argument + for option in options: + if len(option) == 2 or option[2] == " ": + return_list.append(option) + if option[2:] == short_long.get(option.replace("-", "")): + return_list.append(option.replace(" ", "=", 1)) + action._formatted_action_invocation = ", ".join(return_list) + return action._formatted_action_invocation diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/config/exceptions.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/config/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..bf58fde5dbf837d8e21eb3b424eca3aadd06cc28 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/config/exceptions.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +class UsageError(Exception): + """ error in pytest usage or invocation""" + + +class PrintHelp(Exception): + """Raised when pytest should print it's help to skip the rest of the + argument parsing and validation.""" + + pass diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/config/findpaths.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/config/findpaths.py new file mode 100644 index 0000000000000000000000000000000000000000..e6779b289bcfa05591f1214f6c09a1aae2612d72 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/config/findpaths.py @@ -0,0 +1,153 @@ +# -*- coding: utf-8 -*- +import os + +import py + +from .exceptions import UsageError +from _pytest.outcomes import fail + + +def exists(path, ignore=EnvironmentError): + try: + return path.check() + except ignore: + return False + + +def getcfg(args, config=None): + """ + Search the list of arguments for a valid ini-file for pytest, + and return a tuple of (rootdir, inifile, cfg-dict). + + note: config is optional and used only to issue warnings explicitly (#2891). + """ + from _pytest.deprecated import CFG_PYTEST_SECTION + + inibasenames = ["pytest.ini", "tox.ini", "setup.cfg"] + args = [x for x in args if not str(x).startswith("-")] + if not args: + args = [py.path.local()] + for arg in args: + arg = py.path.local(arg) + for base in arg.parts(reverse=True): + for inibasename in inibasenames: + p = base.join(inibasename) + if exists(p): + try: + iniconfig = py.iniconfig.IniConfig(p) + except py.iniconfig.ParseError as exc: + raise UsageError(str(exc)) + + if ( + inibasename == "setup.cfg" + and "tool:pytest" in iniconfig.sections + ): + return base, p, iniconfig["tool:pytest"] + elif "pytest" in iniconfig.sections: + if inibasename == "setup.cfg" and config is not None: + + fail( + CFG_PYTEST_SECTION.format(filename=inibasename), + pytrace=False, + ) + return base, p, iniconfig["pytest"] + elif inibasename == "pytest.ini": + # allowed to be empty + return base, p, {} + return None, None, None + + +def get_common_ancestor(paths): + common_ancestor = None + for path in paths: + if not path.exists(): + continue + if common_ancestor is None: + common_ancestor = path + else: + if path.relto(common_ancestor) or path == common_ancestor: + continue + elif common_ancestor.relto(path): + common_ancestor = path + else: + shared = path.common(common_ancestor) + if shared is not None: + common_ancestor = shared + if common_ancestor is None: + common_ancestor = py.path.local() + elif common_ancestor.isfile(): + common_ancestor = common_ancestor.dirpath() + return common_ancestor + + +def get_dirs_from_args(args): + def is_option(x): + return str(x).startswith("-") + + def get_file_part_from_node_id(x): + return str(x).split("::")[0] + + def get_dir_from_path(path): + if path.isdir(): + return path + return py.path.local(path.dirname) + + # These look like paths but may not exist + possible_paths = ( + py.path.local(get_file_part_from_node_id(arg)) + for arg in args + if not is_option(arg) + ) + + return [get_dir_from_path(path) for path in possible_paths if path.exists()] + + +def determine_setup(inifile, args, rootdir_cmd_arg=None, config=None): + dirs = get_dirs_from_args(args) + if inifile: + iniconfig = py.iniconfig.IniConfig(inifile) + is_cfg_file = str(inifile).endswith(".cfg") + sections = ["tool:pytest", "pytest"] if is_cfg_file else ["pytest"] + for section in sections: + try: + inicfg = iniconfig[section] + if is_cfg_file and section == "pytest" and config is not None: + from _pytest.deprecated import CFG_PYTEST_SECTION + + fail( + CFG_PYTEST_SECTION.format(filename=str(inifile)), pytrace=False + ) + break + except KeyError: + inicfg = None + if rootdir_cmd_arg is None: + rootdir = get_common_ancestor(dirs) + else: + ancestor = get_common_ancestor(dirs) + rootdir, inifile, inicfg = getcfg([ancestor], config=config) + if rootdir is None and rootdir_cmd_arg is None: + for possible_rootdir in ancestor.parts(reverse=True): + if possible_rootdir.join("setup.py").exists(): + rootdir = possible_rootdir + break + else: + if dirs != [ancestor]: + rootdir, inifile, inicfg = getcfg(dirs, config=config) + if rootdir is None: + if config is not None: + cwd = config.invocation_dir + else: + cwd = py.path.local() + rootdir = get_common_ancestor([cwd, ancestor]) + is_fs_root = os.path.splitdrive(str(rootdir))[1] == "/" + if is_fs_root: + rootdir = ancestor + if rootdir_cmd_arg: + rootdir = py.path.local(os.path.expandvars(rootdir_cmd_arg)) + if not rootdir.isdir(): + raise UsageError( + "Directory '{}' not found. Check your '--rootdir' option.".format( + rootdir + ) + ) + return rootdir, inifile, inicfg or {} diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/deprecated.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..12394aca3f522f337093ead47c23d0f9706a3f20 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/deprecated.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +""" +This module contains deprecation messages and bits of code used elsewhere in the codebase +that is planned to be removed in the next pytest release. + +Keeping it in a central location makes it easy to track what is deprecated and should +be removed when the time comes. + +All constants defined in this module should be either PytestWarning instances or UnformattedWarning +in case of warnings which need to format their messages. +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from _pytest.warning_types import PytestDeprecationWarning +from _pytest.warning_types import RemovedInPytest4Warning +from _pytest.warning_types import UnformattedWarning + +YIELD_TESTS = "yield tests were removed in pytest 4.0 - {name} will be ignored" + + +FIXTURE_FUNCTION_CALL = ( + 'Fixture "{name}" called directly. Fixtures are not meant to be called directly,\n' + "but are created automatically when test functions request them as parameters.\n" + "See https://docs.pytest.org/en/latest/fixture.html for more information about fixtures, and\n" + "https://docs.pytest.org/en/latest/deprecations.html#calling-fixtures-directly about how to update your code." +) + +FIXTURE_NAMED_REQUEST = PytestDeprecationWarning( + "'request' is a reserved name for fixtures and will raise an error in future versions" +) + +CFG_PYTEST_SECTION = "[pytest] section in {filename} files is no longer supported, change to [tool:pytest] instead." + +GETFUNCARGVALUE = RemovedInPytest4Warning( + "getfuncargvalue is deprecated, use getfixturevalue" +) + +RAISES_MESSAGE_PARAMETER = PytestDeprecationWarning( + "The 'message' parameter is deprecated.\n" + "(did you mean to use `match='some regex'` to check the exception message?)\n" + "Please see:\n" + " https://docs.pytest.org/en/4.6-maintenance/deprecations.html#message-parameter-of-pytest-raises" +) + +RESULT_LOG = PytestDeprecationWarning( + "--result-log is deprecated and scheduled for removal in pytest 5.0.\n" + "See https://docs.pytest.org/en/latest/deprecations.html#result-log-result-log for more information." +) + +RAISES_EXEC = PytestDeprecationWarning( + "raises(..., 'code(as_a_string)') is deprecated, use the context manager form or use `exec()` directly\n\n" + "See https://docs.pytest.org/en/latest/deprecations.html#raises-warns-exec" +) +WARNS_EXEC = PytestDeprecationWarning( + "warns(..., 'code(as_a_string)') is deprecated, use the context manager form or use `exec()` directly.\n\n" + "See https://docs.pytest.org/en/latest/deprecations.html#raises-warns-exec" +) + +PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST = ( + "Defining 'pytest_plugins' in a non-top-level conftest is no longer supported " + "because it affects the entire directory tree in a non-explicit way.\n" + " {}\n" + "Please move it to a top level conftest file at the rootdir:\n" + " {}\n" + "For more information, visit:\n" + " https://docs.pytest.org/en/latest/deprecations.html#pytest-plugins-in-non-top-level-conftest-files" +) + +PYTEST_CONFIG_GLOBAL = PytestDeprecationWarning( + "the `pytest.config` global is deprecated. Please use `request.config` " + "or `pytest_configure` (if you're a pytest plugin) instead." +) + +PYTEST_ENSURETEMP = RemovedInPytest4Warning( + "pytest/tmpdir_factory.ensuretemp is deprecated, \n" + "please use the tmp_path fixture or tmp_path_factory.mktemp" +) + +PYTEST_LOGWARNING = PytestDeprecationWarning( + "pytest_logwarning is deprecated, no longer being called, and will be removed soon\n" + "please use pytest_warning_captured instead" +) + +PYTEST_WARNS_UNKNOWN_KWARGS = UnformattedWarning( + PytestDeprecationWarning, + "pytest.warns() got unexpected keyword arguments: {args!r}.\n" + "This will be an error in future versions.", +) + +PYTEST_PARAM_UNKNOWN_KWARGS = UnformattedWarning( + PytestDeprecationWarning, + "pytest.param() got unexpected keyword arguments: {args!r}.\n" + "This will be an error in future versions.", +) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/doctest.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/doctest.py new file mode 100644 index 0000000000000000000000000000000000000000..659d24aeebcee9333635ed7c06f33fcd299bcb0c --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/doctest.py @@ -0,0 +1,583 @@ +# -*- coding: utf-8 -*- +""" discover and run doctests in modules and test files.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import inspect +import platform +import sys +import traceback +import warnings +from contextlib import contextmanager + +import pytest +from _pytest._code.code import ExceptionInfo +from _pytest._code.code import ReprFileLocation +from _pytest._code.code import TerminalRepr +from _pytest.compat import safe_getattr +from _pytest.fixtures import FixtureRequest +from _pytest.outcomes import Skipped +from _pytest.warning_types import PytestWarning + +DOCTEST_REPORT_CHOICE_NONE = "none" +DOCTEST_REPORT_CHOICE_CDIFF = "cdiff" +DOCTEST_REPORT_CHOICE_NDIFF = "ndiff" +DOCTEST_REPORT_CHOICE_UDIFF = "udiff" +DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE = "only_first_failure" + +DOCTEST_REPORT_CHOICES = ( + DOCTEST_REPORT_CHOICE_NONE, + DOCTEST_REPORT_CHOICE_CDIFF, + DOCTEST_REPORT_CHOICE_NDIFF, + DOCTEST_REPORT_CHOICE_UDIFF, + DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE, +) + +# Lazy definition of runner class +RUNNER_CLASS = None + + +def pytest_addoption(parser): + parser.addini( + "doctest_optionflags", + "option flags for doctests", + type="args", + default=["ELLIPSIS"], + ) + parser.addini( + "doctest_encoding", "encoding used for doctest files", default="utf-8" + ) + group = parser.getgroup("collect") + group.addoption( + "--doctest-modules", + action="store_true", + default=False, + help="run doctests in all .py modules", + dest="doctestmodules", + ) + group.addoption( + "--doctest-report", + type=str.lower, + default="udiff", + help="choose another output format for diffs on doctest failure", + choices=DOCTEST_REPORT_CHOICES, + dest="doctestreport", + ) + group.addoption( + "--doctest-glob", + action="append", + default=[], + metavar="pat", + help="doctests file matching pattern, default: test*.txt", + dest="doctestglob", + ) + group.addoption( + "--doctest-ignore-import-errors", + action="store_true", + default=False, + help="ignore doctest ImportErrors", + dest="doctest_ignore_import_errors", + ) + group.addoption( + "--doctest-continue-on-failure", + action="store_true", + default=False, + help="for a given doctest, continue to run after the first failure", + dest="doctest_continue_on_failure", + ) + + +def pytest_collect_file(path, parent): + config = parent.config + if path.ext == ".py": + if config.option.doctestmodules and not _is_setup_py(config, path, parent): + return DoctestModule(path, parent) + elif _is_doctest(config, path, parent): + return DoctestTextfile(path, parent) + + +def _is_setup_py(config, path, parent): + if path.basename != "setup.py": + return False + contents = path.read() + return "setuptools" in contents or "distutils" in contents + + +def _is_doctest(config, path, parent): + if path.ext in (".txt", ".rst") and parent.session.isinitpath(path): + return True + globs = config.getoption("doctestglob") or ["test*.txt"] + for glob in globs: + if path.check(fnmatch=glob): + return True + return False + + +class ReprFailDoctest(TerminalRepr): + def __init__(self, reprlocation_lines): + # List of (reprlocation, lines) tuples + self.reprlocation_lines = reprlocation_lines + + def toterminal(self, tw): + for reprlocation, lines in self.reprlocation_lines: + for line in lines: + tw.line(line) + reprlocation.toterminal(tw) + + +class MultipleDoctestFailures(Exception): + def __init__(self, failures): + super(MultipleDoctestFailures, self).__init__() + self.failures = failures + + +def _init_runner_class(): + import doctest + + class PytestDoctestRunner(doctest.DebugRunner): + """ + Runner to collect failures. Note that the out variable in this case is + a list instead of a stdout-like object + """ + + def __init__( + self, checker=None, verbose=None, optionflags=0, continue_on_failure=True + ): + doctest.DebugRunner.__init__( + self, checker=checker, verbose=verbose, optionflags=optionflags + ) + self.continue_on_failure = continue_on_failure + + def report_failure(self, out, test, example, got): + failure = doctest.DocTestFailure(test, example, got) + if self.continue_on_failure: + out.append(failure) + else: + raise failure + + def report_unexpected_exception(self, out, test, example, exc_info): + if isinstance(exc_info[1], Skipped): + raise exc_info[1] + failure = doctest.UnexpectedException(test, example, exc_info) + if self.continue_on_failure: + out.append(failure) + else: + raise failure + + return PytestDoctestRunner + + +def _get_runner(checker=None, verbose=None, optionflags=0, continue_on_failure=True): + # We need this in order to do a lazy import on doctest + global RUNNER_CLASS + if RUNNER_CLASS is None: + RUNNER_CLASS = _init_runner_class() + return RUNNER_CLASS( + checker=checker, + verbose=verbose, + optionflags=optionflags, + continue_on_failure=continue_on_failure, + ) + + +class DoctestItem(pytest.Item): + def __init__(self, name, parent, runner=None, dtest=None): + super(DoctestItem, self).__init__(name, parent) + self.runner = runner + self.dtest = dtest + self.obj = None + self.fixture_request = None + + def setup(self): + if self.dtest is not None: + self.fixture_request = _setup_fixtures(self) + globs = dict(getfixture=self.fixture_request.getfixturevalue) + for name, value in self.fixture_request.getfixturevalue( + "doctest_namespace" + ).items(): + globs[name] = value + self.dtest.globs.update(globs) + + def runtest(self): + _check_all_skipped(self.dtest) + self._disable_output_capturing_for_darwin() + failures = [] + self.runner.run(self.dtest, out=failures) + if failures: + raise MultipleDoctestFailures(failures) + + def _disable_output_capturing_for_darwin(self): + """ + Disable output capturing. Otherwise, stdout is lost to doctest (#985) + """ + if platform.system() != "Darwin": + return + capman = self.config.pluginmanager.getplugin("capturemanager") + if capman: + capman.suspend_global_capture(in_=True) + out, err = capman.read_global_capture() + sys.stdout.write(out) + sys.stderr.write(err) + + def repr_failure(self, excinfo): + import doctest + + failures = None + if excinfo.errisinstance((doctest.DocTestFailure, doctest.UnexpectedException)): + failures = [excinfo.value] + elif excinfo.errisinstance(MultipleDoctestFailures): + failures = excinfo.value.failures + + if failures is not None: + reprlocation_lines = [] + for failure in failures: + example = failure.example + test = failure.test + filename = test.filename + if test.lineno is None: + lineno = None + else: + lineno = test.lineno + example.lineno + 1 + message = type(failure).__name__ + reprlocation = ReprFileLocation(filename, lineno, message) + checker = _get_checker() + report_choice = _get_report_choice( + self.config.getoption("doctestreport") + ) + if lineno is not None: + lines = failure.test.docstring.splitlines(False) + # add line numbers to the left of the error message + lines = [ + "%03d %s" % (i + test.lineno + 1, x) + for (i, x) in enumerate(lines) + ] + # trim docstring error lines to 10 + lines = lines[max(example.lineno - 9, 0) : example.lineno + 1] + else: + lines = [ + "EXAMPLE LOCATION UNKNOWN, not showing all tests of that example" + ] + indent = ">>>" + for line in example.source.splitlines(): + lines.append("??? %s %s" % (indent, line)) + indent = "..." + if isinstance(failure, doctest.DocTestFailure): + lines += checker.output_difference( + example, failure.got, report_choice + ).split("\n") + else: + inner_excinfo = ExceptionInfo(failure.exc_info) + lines += ["UNEXPECTED EXCEPTION: %s" % repr(inner_excinfo.value)] + lines += traceback.format_exception(*failure.exc_info) + reprlocation_lines.append((reprlocation, lines)) + return ReprFailDoctest(reprlocation_lines) + else: + return super(DoctestItem, self).repr_failure(excinfo) + + def reportinfo(self): + return self.fspath, self.dtest.lineno, "[doctest] %s" % self.name + + +def _get_flag_lookup(): + import doctest + + return dict( + DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1, + DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE, + NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE, + ELLIPSIS=doctest.ELLIPSIS, + IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL, + COMPARISON_FLAGS=doctest.COMPARISON_FLAGS, + ALLOW_UNICODE=_get_allow_unicode_flag(), + ALLOW_BYTES=_get_allow_bytes_flag(), + ) + + +def get_optionflags(parent): + optionflags_str = parent.config.getini("doctest_optionflags") + flag_lookup_table = _get_flag_lookup() + flag_acc = 0 + for flag in optionflags_str: + flag_acc |= flag_lookup_table[flag] + return flag_acc + + +def _get_continue_on_failure(config): + continue_on_failure = config.getvalue("doctest_continue_on_failure") + if continue_on_failure: + # We need to turn off this if we use pdb since we should stop at + # the first failure + if config.getvalue("usepdb"): + continue_on_failure = False + return continue_on_failure + + +class DoctestTextfile(pytest.Module): + obj = None + + def collect(self): + import doctest + + # inspired by doctest.testfile; ideally we would use it directly, + # but it doesn't support passing a custom checker + encoding = self.config.getini("doctest_encoding") + text = self.fspath.read_text(encoding) + filename = str(self.fspath) + name = self.fspath.basename + globs = {"__name__": "__main__"} + + optionflags = get_optionflags(self) + + runner = _get_runner( + verbose=0, + optionflags=optionflags, + checker=_get_checker(), + continue_on_failure=_get_continue_on_failure(self.config), + ) + _fix_spoof_python2(runner, encoding) + + parser = doctest.DocTestParser() + test = parser.get_doctest(text, globs, name, filename, 0) + if test.examples: + yield DoctestItem(test.name, self, runner, test) + + +def _check_all_skipped(test): + """raises pytest.skip() if all examples in the given DocTest have the SKIP + option set. + """ + import doctest + + all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples) + if all_skipped: + pytest.skip("all tests skipped by +SKIP option") + + +def _is_mocked(obj): + """ + returns if a object is possibly a mock object by checking the existence of a highly improbable attribute + """ + return ( + safe_getattr(obj, "pytest_mock_example_attribute_that_shouldnt_exist", None) + is not None + ) + + +@contextmanager +def _patch_unwrap_mock_aware(): + """ + contextmanager which replaces ``inspect.unwrap`` with a version + that's aware of mock objects and doesn't recurse on them + """ + real_unwrap = getattr(inspect, "unwrap", None) + if real_unwrap is None: + yield + else: + + def _mock_aware_unwrap(obj, stop=None): + try: + if stop is None or stop is _is_mocked: + return real_unwrap(obj, stop=_is_mocked) + return real_unwrap(obj, stop=lambda obj: _is_mocked(obj) or stop(obj)) + except Exception as e: + warnings.warn( + "Got %r when unwrapping %r. This is usually caused " + "by a violation of Python's object protocol; see e.g. " + "https://github.com/pytest-dev/pytest/issues/5080" % (e, obj), + PytestWarning, + ) + raise + + inspect.unwrap = _mock_aware_unwrap + try: + yield + finally: + inspect.unwrap = real_unwrap + + +class DoctestModule(pytest.Module): + def collect(self): + import doctest + + class MockAwareDocTestFinder(doctest.DocTestFinder): + """ + a hackish doctest finder that overrides stdlib internals to fix a stdlib bug + + https://github.com/pytest-dev/pytest/issues/3456 + https://bugs.python.org/issue25532 + """ + + def _find(self, tests, obj, name, module, source_lines, globs, seen): + if _is_mocked(obj): + return + with _patch_unwrap_mock_aware(): + + doctest.DocTestFinder._find( + self, tests, obj, name, module, source_lines, globs, seen + ) + + if self.fspath.basename == "conftest.py": + module = self.config.pluginmanager._importconftest(self.fspath) + else: + try: + module = self.fspath.pyimport() + except ImportError: + if self.config.getvalue("doctest_ignore_import_errors"): + pytest.skip("unable to import module %r" % self.fspath) + else: + raise + # uses internal doctest module parsing mechanism + finder = MockAwareDocTestFinder() + optionflags = get_optionflags(self) + runner = _get_runner( + verbose=0, + optionflags=optionflags, + checker=_get_checker(), + continue_on_failure=_get_continue_on_failure(self.config), + ) + + for test in finder.find(module, module.__name__): + if test.examples: # skip empty doctests + yield DoctestItem(test.name, self, runner, test) + + +def _setup_fixtures(doctest_item): + """ + Used by DoctestTextfile and DoctestItem to setup fixture information. + """ + + def func(): + pass + + doctest_item.funcargs = {} + fm = doctest_item.session._fixturemanager + doctest_item._fixtureinfo = fm.getfixtureinfo( + node=doctest_item, func=func, cls=None, funcargs=False + ) + fixture_request = FixtureRequest(doctest_item) + fixture_request._fillfixtures() + return fixture_request + + +def _get_checker(): + """ + Returns a doctest.OutputChecker subclass that takes in account the + ALLOW_UNICODE option to ignore u'' prefixes in strings and ALLOW_BYTES + to strip b'' prefixes. + Useful when the same doctest should run in Python 2 and Python 3. + + An inner class is used to avoid importing "doctest" at the module + level. + """ + if hasattr(_get_checker, "LiteralsOutputChecker"): + return _get_checker.LiteralsOutputChecker() + + import doctest + import re + + class LiteralsOutputChecker(doctest.OutputChecker): + """ + Copied from doctest_nose_plugin.py from the nltk project: + https://github.com/nltk/nltk + + Further extended to also support byte literals. + """ + + _unicode_literal_re = re.compile(r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE) + _bytes_literal_re = re.compile(r"(\W|^)[bB]([rR]?[\'\"])", re.UNICODE) + + def check_output(self, want, got, optionflags): + res = doctest.OutputChecker.check_output(self, want, got, optionflags) + if res: + return True + + allow_unicode = optionflags & _get_allow_unicode_flag() + allow_bytes = optionflags & _get_allow_bytes_flag() + if not allow_unicode and not allow_bytes: + return False + + else: # pragma: no cover + + def remove_prefixes(regex, txt): + return re.sub(regex, r"\1\2", txt) + + if allow_unicode: + want = remove_prefixes(self._unicode_literal_re, want) + got = remove_prefixes(self._unicode_literal_re, got) + if allow_bytes: + want = remove_prefixes(self._bytes_literal_re, want) + got = remove_prefixes(self._bytes_literal_re, got) + res = doctest.OutputChecker.check_output(self, want, got, optionflags) + return res + + _get_checker.LiteralsOutputChecker = LiteralsOutputChecker + return _get_checker.LiteralsOutputChecker() + + +def _get_allow_unicode_flag(): + """ + Registers and returns the ALLOW_UNICODE flag. + """ + import doctest + + return doctest.register_optionflag("ALLOW_UNICODE") + + +def _get_allow_bytes_flag(): + """ + Registers and returns the ALLOW_BYTES flag. + """ + import doctest + + return doctest.register_optionflag("ALLOW_BYTES") + + +def _get_report_choice(key): + """ + This function returns the actual `doctest` module flag value, we want to do it as late as possible to avoid + importing `doctest` and all its dependencies when parsing options, as it adds overhead and breaks tests. + """ + import doctest + + return { + DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF, + DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF, + DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF, + DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE, + DOCTEST_REPORT_CHOICE_NONE: 0, + }[key] + + +def _fix_spoof_python2(runner, encoding): + """ + Installs a "SpoofOut" into the given DebugRunner so it properly deals with unicode output. This + should patch only doctests for text files because they don't have a way to declare their + encoding. Doctests in docstrings from Python modules don't have the same problem given that + Python already decoded the strings. + + This fixes the problem related in issue #2434. + """ + from _pytest.compat import _PY2 + + if not _PY2: + return + + from doctest import _SpoofOut + + class UnicodeSpoof(_SpoofOut): + def getvalue(self): + result = _SpoofOut.getvalue(self) + if encoding and isinstance(result, bytes): + result = result.decode(encoding) + return result + + runner._fakeout = UnicodeSpoof() + + +@pytest.fixture(scope="session") +def doctest_namespace(): + """ + Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests. + """ + return dict() diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/fixtures.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..280a48608b683a2cf95f6fd62a98ff587373782e --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/fixtures.py @@ -0,0 +1,1356 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import functools +import inspect +import itertools +import sys +import warnings +from collections import defaultdict +from collections import deque +from collections import OrderedDict + +import attr +import py +import six + +import _pytest +from _pytest import nodes +from _pytest._code.code import FormattedExcinfo +from _pytest._code.code import TerminalRepr +from _pytest.compat import _format_args +from _pytest.compat import _PytestWrapper +from _pytest.compat import exc_clear +from _pytest.compat import FuncargnamesCompatAttr +from _pytest.compat import get_real_func +from _pytest.compat import get_real_method +from _pytest.compat import getfslineno +from _pytest.compat import getfuncargnames +from _pytest.compat import getimfunc +from _pytest.compat import getlocation +from _pytest.compat import is_generator +from _pytest.compat import isclass +from _pytest.compat import NOTSET +from _pytest.compat import safe_getattr +from _pytest.deprecated import FIXTURE_FUNCTION_CALL +from _pytest.deprecated import FIXTURE_NAMED_REQUEST +from _pytest.outcomes import fail +from _pytest.outcomes import TEST_OUTCOME + + +@attr.s(frozen=True) +class PseudoFixtureDef(object): + cached_result = attr.ib() + scope = attr.ib() + + +def pytest_sessionstart(session): + import _pytest.python + import _pytest.nodes + + scopename2class.update( + { + "package": _pytest.python.Package, + "class": _pytest.python.Class, + "module": _pytest.python.Module, + "function": _pytest.nodes.Item, + "session": _pytest.main.Session, + } + ) + session._fixturemanager = FixtureManager(session) + + +scopename2class = {} + + +scope2props = dict(session=()) +scope2props["package"] = ("fspath",) +scope2props["module"] = ("fspath", "module") +scope2props["class"] = scope2props["module"] + ("cls",) +scope2props["instance"] = scope2props["class"] + ("instance",) +scope2props["function"] = scope2props["instance"] + ("function", "keywords") + + +def scopeproperty(name=None, doc=None): + def decoratescope(func): + scopename = name or func.__name__ + + def provide(self): + if func.__name__ in scope2props[self.scope]: + return func(self) + raise AttributeError( + "%s not available in %s-scoped context" % (scopename, self.scope) + ) + + return property(provide, None, None, func.__doc__) + + return decoratescope + + +def get_scope_package(node, fixturedef): + import pytest + + cls = pytest.Package + current = node + fixture_package_name = "%s/%s" % (fixturedef.baseid, "__init__.py") + while current and ( + type(current) is not cls or fixture_package_name != current.nodeid + ): + current = current.parent + if current is None: + return node.session + return current + + +def get_scope_node(node, scope): + cls = scopename2class.get(scope) + if cls is None: + raise ValueError("unknown scope") + return node.getparent(cls) + + +def add_funcarg_pseudo_fixture_def(collector, metafunc, fixturemanager): + # this function will transform all collected calls to a functions + # if they use direct funcargs (i.e. direct parametrization) + # because we want later test execution to be able to rely on + # an existing FixtureDef structure for all arguments. + # XXX we can probably avoid this algorithm if we modify CallSpec2 + # to directly care for creating the fixturedefs within its methods. + if not metafunc._calls[0].funcargs: + return # this function call does not have direct parametrization + # collect funcargs of all callspecs into a list of values + arg2params = {} + arg2scope = {} + for callspec in metafunc._calls: + for argname, argvalue in callspec.funcargs.items(): + assert argname not in callspec.params + callspec.params[argname] = argvalue + arg2params_list = arg2params.setdefault(argname, []) + callspec.indices[argname] = len(arg2params_list) + arg2params_list.append(argvalue) + if argname not in arg2scope: + scopenum = callspec._arg2scopenum.get(argname, scopenum_function) + arg2scope[argname] = scopes[scopenum] + callspec.funcargs.clear() + + # register artificial FixtureDef's so that later at test execution + # time we can rely on a proper FixtureDef to exist for fixture setup. + arg2fixturedefs = metafunc._arg2fixturedefs + for argname, valuelist in arg2params.items(): + # if we have a scope that is higher than function we need + # to make sure we only ever create an according fixturedef on + # a per-scope basis. We thus store and cache the fixturedef on the + # node related to the scope. + scope = arg2scope[argname] + node = None + if scope != "function": + node = get_scope_node(collector, scope) + if node is None: + assert scope == "class" and isinstance(collector, _pytest.python.Module) + # use module-level collector for class-scope (for now) + node = collector + if node and argname in node._name2pseudofixturedef: + arg2fixturedefs[argname] = [node._name2pseudofixturedef[argname]] + else: + fixturedef = FixtureDef( + fixturemanager, + "", + argname, + get_direct_param_fixture_func, + arg2scope[argname], + valuelist, + False, + False, + ) + arg2fixturedefs[argname] = [fixturedef] + if node is not None: + node._name2pseudofixturedef[argname] = fixturedef + + +def getfixturemarker(obj): + """ return fixturemarker or None if it doesn't exist or raised + exceptions.""" + try: + return getattr(obj, "_pytestfixturefunction", None) + except TEST_OUTCOME: + # some objects raise errors like request (from flask import request) + # we don't expect them to be fixture functions + return None + + +def get_parametrized_fixture_keys(item, scopenum): + """ return list of keys for all parametrized arguments which match + the specified scope. """ + assert scopenum < scopenum_function # function + try: + cs = item.callspec + except AttributeError: + pass + else: + # cs.indices.items() is random order of argnames. Need to + # sort this so that different calls to + # get_parametrized_fixture_keys will be deterministic. + for argname, param_index in sorted(cs.indices.items()): + if cs._arg2scopenum[argname] != scopenum: + continue + if scopenum == 0: # session + key = (argname, param_index) + elif scopenum == 1: # package + key = (argname, param_index, item.fspath.dirpath()) + elif scopenum == 2: # module + key = (argname, param_index, item.fspath) + elif scopenum == 3: # class + key = (argname, param_index, item.fspath, item.cls) + yield key + + +# algorithm for sorting on a per-parametrized resource setup basis +# it is called for scopenum==0 (session) first and performs sorting +# down to the lower scopes such as to minimize number of "high scope" +# setups and teardowns + + +def reorder_items(items): + argkeys_cache = {} + items_by_argkey = {} + for scopenum in range(0, scopenum_function): + argkeys_cache[scopenum] = d = {} + items_by_argkey[scopenum] = item_d = defaultdict(deque) + for item in items: + keys = OrderedDict.fromkeys(get_parametrized_fixture_keys(item, scopenum)) + if keys: + d[item] = keys + for key in keys: + item_d[key].append(item) + items = OrderedDict.fromkeys(items) + return list(reorder_items_atscope(items, argkeys_cache, items_by_argkey, 0)) + + +def fix_cache_order(item, argkeys_cache, items_by_argkey): + for scopenum in range(0, scopenum_function): + for key in argkeys_cache[scopenum].get(item, []): + items_by_argkey[scopenum][key].appendleft(item) + + +def reorder_items_atscope(items, argkeys_cache, items_by_argkey, scopenum): + if scopenum >= scopenum_function or len(items) < 3: + return items + ignore = set() + items_deque = deque(items) + items_done = OrderedDict() + scoped_items_by_argkey = items_by_argkey[scopenum] + scoped_argkeys_cache = argkeys_cache[scopenum] + while items_deque: + no_argkey_group = OrderedDict() + slicing_argkey = None + while items_deque: + item = items_deque.popleft() + if item in items_done or item in no_argkey_group: + continue + argkeys = OrderedDict.fromkeys( + k for k in scoped_argkeys_cache.get(item, []) if k not in ignore + ) + if not argkeys: + no_argkey_group[item] = None + else: + slicing_argkey, _ = argkeys.popitem() + # we don't have to remove relevant items from later in the deque because they'll just be ignored + matching_items = [ + i for i in scoped_items_by_argkey[slicing_argkey] if i in items + ] + for i in reversed(matching_items): + fix_cache_order(i, argkeys_cache, items_by_argkey) + items_deque.appendleft(i) + break + if no_argkey_group: + no_argkey_group = reorder_items_atscope( + no_argkey_group, argkeys_cache, items_by_argkey, scopenum + 1 + ) + for item in no_argkey_group: + items_done[item] = None + ignore.add(slicing_argkey) + return items_done + + +def fillfixtures(function): + """ fill missing funcargs for a test function. """ + try: + request = function._request + except AttributeError: + # XXX this special code path is only expected to execute + # with the oejskit plugin. It uses classes with funcargs + # and we thus have to work a bit to allow this. + fm = function.session._fixturemanager + fi = fm.getfixtureinfo(function.parent, function.obj, None) + function._fixtureinfo = fi + request = function._request = FixtureRequest(function) + request._fillfixtures() + # prune out funcargs for jstests + newfuncargs = {} + for name in fi.argnames: + newfuncargs[name] = function.funcargs[name] + function.funcargs = newfuncargs + else: + request._fillfixtures() + + +def get_direct_param_fixture_func(request): + return request.param + + +@attr.s(slots=True) +class FuncFixtureInfo(object): + # original function argument names + argnames = attr.ib(type=tuple) + # argnames that function immediately requires. These include argnames + + # fixture names specified via usefixtures and via autouse=True in fixture + # definitions. + initialnames = attr.ib(type=tuple) + names_closure = attr.ib() # List[str] + name2fixturedefs = attr.ib() # List[str, List[FixtureDef]] + + def prune_dependency_tree(self): + """Recompute names_closure from initialnames and name2fixturedefs + + Can only reduce names_closure, which means that the new closure will + always be a subset of the old one. The order is preserved. + + This method is needed because direct parametrization may shadow some + of the fixtures that were included in the originally built dependency + tree. In this way the dependency tree can get pruned, and the closure + of argnames may get reduced. + """ + closure = set() + working_set = set(self.initialnames) + while working_set: + argname = working_set.pop() + # argname may be smth not included in the original names_closure, + # in which case we ignore it. This currently happens with pseudo + # FixtureDefs which wrap 'get_direct_param_fixture_func(request)'. + # So they introduce the new dependency 'request' which might have + # been missing in the original tree (closure). + if argname not in closure and argname in self.names_closure: + closure.add(argname) + if argname in self.name2fixturedefs: + working_set.update(self.name2fixturedefs[argname][-1].argnames) + + self.names_closure[:] = sorted(closure, key=self.names_closure.index) + + +class FixtureRequest(FuncargnamesCompatAttr): + """ A request for a fixture from a test or fixture function. + + A request object gives access to the requesting test context + and has an optional ``param`` attribute in case + the fixture is parametrized indirectly. + """ + + def __init__(self, pyfuncitem): + self._pyfuncitem = pyfuncitem + #: fixture for which this request is being performed + self.fixturename = None + #: Scope string, one of "function", "class", "module", "session" + self.scope = "function" + self._fixture_defs = {} # argname -> FixtureDef + fixtureinfo = pyfuncitem._fixtureinfo + self._arg2fixturedefs = fixtureinfo.name2fixturedefs.copy() + self._arg2index = {} + self._fixturemanager = pyfuncitem.session._fixturemanager + + @property + def fixturenames(self): + """names of all active fixtures in this request""" + result = list(self._pyfuncitem._fixtureinfo.names_closure) + result.extend(set(self._fixture_defs).difference(result)) + return result + + @property + def node(self): + """ underlying collection node (depends on current request scope)""" + return self._getscopeitem(self.scope) + + def _getnextfixturedef(self, argname): + fixturedefs = self._arg2fixturedefs.get(argname, None) + if fixturedefs is None: + # we arrive here because of a dynamic call to + # getfixturevalue(argname) usage which was naturally + # not known at parsing/collection time + parentid = self._pyfuncitem.parent.nodeid + fixturedefs = self._fixturemanager.getfixturedefs(argname, parentid) + self._arg2fixturedefs[argname] = fixturedefs + # fixturedefs list is immutable so we maintain a decreasing index + index = self._arg2index.get(argname, 0) - 1 + if fixturedefs is None or (-index > len(fixturedefs)): + raise FixtureLookupError(argname, self) + self._arg2index[argname] = index + return fixturedefs[index] + + @property + def config(self): + """ the pytest config object associated with this request. """ + return self._pyfuncitem.config + + @scopeproperty() + def function(self): + """ test function object if the request has a per-function scope. """ + return self._pyfuncitem.obj + + @scopeproperty("class") + def cls(self): + """ class (can be None) where the test function was collected. """ + clscol = self._pyfuncitem.getparent(_pytest.python.Class) + if clscol: + return clscol.obj + + @property + def instance(self): + """ instance (can be None) on which test function was collected. """ + # unittest support hack, see _pytest.unittest.TestCaseFunction + try: + return self._pyfuncitem._testcase + except AttributeError: + function = getattr(self, "function", None) + return getattr(function, "__self__", None) + + @scopeproperty() + def module(self): + """ python module object where the test function was collected. """ + return self._pyfuncitem.getparent(_pytest.python.Module).obj + + @scopeproperty() + def fspath(self): + """ the file system path of the test module which collected this test. """ + return self._pyfuncitem.fspath + + @property + def keywords(self): + """ keywords/markers dictionary for the underlying node. """ + return self.node.keywords + + @property + def session(self): + """ pytest session object. """ + return self._pyfuncitem.session + + def addfinalizer(self, finalizer): + """ add finalizer/teardown function to be called after the + last test within the requesting test context finished + execution. """ + # XXX usually this method is shadowed by fixturedef specific ones + self._addfinalizer(finalizer, scope=self.scope) + + def _addfinalizer(self, finalizer, scope): + colitem = self._getscopeitem(scope) + self._pyfuncitem.session._setupstate.addfinalizer( + finalizer=finalizer, colitem=colitem + ) + + def applymarker(self, marker): + """ Apply a marker to a single test function invocation. + This method is useful if you don't want to have a keyword/marker + on all function invocations. + + :arg marker: a :py:class:`_pytest.mark.MarkDecorator` object + created by a call to ``pytest.mark.NAME(...)``. + """ + self.node.add_marker(marker) + + def raiseerror(self, msg): + """ raise a FixtureLookupError with the given message. """ + raise self._fixturemanager.FixtureLookupError(None, self, msg) + + def _fillfixtures(self): + item = self._pyfuncitem + fixturenames = getattr(item, "fixturenames", self.fixturenames) + for argname in fixturenames: + if argname not in item.funcargs: + item.funcargs[argname] = self.getfixturevalue(argname) + + def getfixturevalue(self, argname): + """ Dynamically run a named fixture function. + + Declaring fixtures via function argument is recommended where possible. + But if you can only decide whether to use another fixture at test + setup time, you may use this function to retrieve it inside a fixture + or test function body. + """ + return self._get_active_fixturedef(argname).cached_result[0] + + def getfuncargvalue(self, argname): + """ Deprecated, use getfixturevalue. """ + from _pytest import deprecated + + warnings.warn(deprecated.GETFUNCARGVALUE, stacklevel=2) + return self.getfixturevalue(argname) + + def _get_active_fixturedef(self, argname): + try: + return self._fixture_defs[argname] + except KeyError: + try: + fixturedef = self._getnextfixturedef(argname) + except FixtureLookupError: + if argname == "request": + cached_result = (self, [0], None) + scope = "function" + return PseudoFixtureDef(cached_result, scope) + raise + # remove indent to prevent the python3 exception + # from leaking into the call + self._compute_fixture_value(fixturedef) + self._fixture_defs[argname] = fixturedef + return fixturedef + + def _get_fixturestack(self): + current = self + values = [] + while 1: + fixturedef = getattr(current, "_fixturedef", None) + if fixturedef is None: + values.reverse() + return values + values.append(fixturedef) + current = current._parent_request + + def _compute_fixture_value(self, fixturedef): + """ + Creates a SubRequest based on "self" and calls the execute method of the given fixturedef object. This will + force the FixtureDef object to throw away any previous results and compute a new fixture value, which + will be stored into the FixtureDef object itself. + + :param FixtureDef fixturedef: + """ + # prepare a subrequest object before calling fixture function + # (latter managed by fixturedef) + argname = fixturedef.argname + funcitem = self._pyfuncitem + scope = fixturedef.scope + try: + param = funcitem.callspec.getparam(argname) + except (AttributeError, ValueError): + param = NOTSET + param_index = 0 + has_params = fixturedef.params is not None + fixtures_not_supported = getattr(funcitem, "nofuncargs", False) + if has_params and fixtures_not_supported: + msg = ( + "{name} does not support fixtures, maybe unittest.TestCase subclass?\n" + "Node id: {nodeid}\n" + "Function type: {typename}" + ).format( + name=funcitem.name, + nodeid=funcitem.nodeid, + typename=type(funcitem).__name__, + ) + fail(msg, pytrace=False) + if has_params: + frame = inspect.stack()[3] + frameinfo = inspect.getframeinfo(frame[0]) + source_path = frameinfo.filename + source_lineno = frameinfo.lineno + source_path = py.path.local(source_path) + if source_path.relto(funcitem.config.rootdir): + source_path = source_path.relto(funcitem.config.rootdir) + msg = ( + "The requested fixture has no parameter defined for test:\n" + " {}\n\n" + "Requested fixture '{}' defined in:\n{}" + "\n\nRequested here:\n{}:{}".format( + funcitem.nodeid, + fixturedef.argname, + getlocation(fixturedef.func, funcitem.config.rootdir), + source_path, + source_lineno, + ) + ) + fail(msg, pytrace=False) + else: + param_index = funcitem.callspec.indices[argname] + # if a parametrize invocation set a scope it will override + # the static scope defined with the fixture function + paramscopenum = funcitem.callspec._arg2scopenum.get(argname) + if paramscopenum is not None: + scope = scopes[paramscopenum] + + subrequest = SubRequest(self, scope, param, param_index, fixturedef) + + # check if a higher-level scoped fixture accesses a lower level one + subrequest._check_scope(argname, self.scope, scope) + + # clear sys.exc_info before invoking the fixture (python bug?) + # if it's not explicitly cleared it will leak into the call + exc_clear() + try: + # call the fixture function + fixturedef.execute(request=subrequest) + finally: + self._schedule_finalizers(fixturedef, subrequest) + + def _schedule_finalizers(self, fixturedef, subrequest): + # if fixture function failed it might have registered finalizers + self.session._setupstate.addfinalizer( + functools.partial(fixturedef.finish, request=subrequest), subrequest.node + ) + + def _check_scope(self, argname, invoking_scope, requested_scope): + if argname == "request": + return + if scopemismatch(invoking_scope, requested_scope): + # try to report something helpful + lines = self._factorytraceback() + fail( + "ScopeMismatch: You tried to access the %r scoped " + "fixture %r with a %r scoped request object, " + "involved factories\n%s" + % ((requested_scope, argname, invoking_scope, "\n".join(lines))), + pytrace=False, + ) + + def _factorytraceback(self): + lines = [] + for fixturedef in self._get_fixturestack(): + factory = fixturedef.func + fs, lineno = getfslineno(factory) + p = self._pyfuncitem.session.fspath.bestrelpath(fs) + args = _format_args(factory) + lines.append("%s:%d: def %s%s" % (p, lineno + 1, factory.__name__, args)) + return lines + + def _getscopeitem(self, scope): + if scope == "function": + # this might also be a non-function Item despite its attribute name + return self._pyfuncitem + if scope == "package": + node = get_scope_package(self._pyfuncitem, self._fixturedef) + else: + node = get_scope_node(self._pyfuncitem, scope) + if node is None and scope == "class": + # fallback to function item itself + node = self._pyfuncitem + assert node, 'Could not obtain a node for scope "{}" for function {!r}'.format( + scope, self._pyfuncitem + ) + return node + + def __repr__(self): + return "" % (self.node) + + +class SubRequest(FixtureRequest): + """ a sub request for handling getting a fixture from a + test function/fixture. """ + + def __init__(self, request, scope, param, param_index, fixturedef): + self._parent_request = request + self.fixturename = fixturedef.argname + if param is not NOTSET: + self.param = param + self.param_index = param_index + self.scope = scope + self._fixturedef = fixturedef + self._pyfuncitem = request._pyfuncitem + self._fixture_defs = request._fixture_defs + self._arg2fixturedefs = request._arg2fixturedefs + self._arg2index = request._arg2index + self._fixturemanager = request._fixturemanager + + def __repr__(self): + return "" % (self.fixturename, self._pyfuncitem) + + def addfinalizer(self, finalizer): + self._fixturedef.addfinalizer(finalizer) + + def _schedule_finalizers(self, fixturedef, subrequest): + # if the executing fixturedef was not explicitly requested in the argument list (via + # getfixturevalue inside the fixture call) then ensure this fixture def will be finished + # first + if fixturedef.argname not in self.funcargnames: + fixturedef.addfinalizer( + functools.partial(self._fixturedef.finish, request=self) + ) + super(SubRequest, self)._schedule_finalizers(fixturedef, subrequest) + + +scopes = "session package module class function".split() +scopenum_function = scopes.index("function") + + +def scopemismatch(currentscope, newscope): + return scopes.index(newscope) > scopes.index(currentscope) + + +def scope2index(scope, descr, where=None): + """Look up the index of ``scope`` and raise a descriptive value error + if not defined. + """ + try: + return scopes.index(scope) + except ValueError: + fail( + "{} {}got an unexpected scope value '{}'".format( + descr, "from {} ".format(where) if where else "", scope + ), + pytrace=False, + ) + + +class FixtureLookupError(LookupError): + """ could not return a requested Fixture (missing or invalid). """ + + def __init__(self, argname, request, msg=None): + self.argname = argname + self.request = request + self.fixturestack = request._get_fixturestack() + self.msg = msg + + def formatrepr(self): + tblines = [] + addline = tblines.append + stack = [self.request._pyfuncitem.obj] + stack.extend(map(lambda x: x.func, self.fixturestack)) + msg = self.msg + if msg is not None: + # the last fixture raise an error, let's present + # it at the requesting side + stack = stack[:-1] + for function in stack: + fspath, lineno = getfslineno(function) + try: + lines, _ = inspect.getsourcelines(get_real_func(function)) + except (IOError, IndexError, TypeError): + error_msg = "file %s, line %s: source code not available" + addline(error_msg % (fspath, lineno + 1)) + else: + addline("file %s, line %s" % (fspath, lineno + 1)) + for i, line in enumerate(lines): + line = line.rstrip() + addline(" " + line) + if line.lstrip().startswith("def"): + break + + if msg is None: + fm = self.request._fixturemanager + available = set() + parentid = self.request._pyfuncitem.parent.nodeid + for name, fixturedefs in fm._arg2fixturedefs.items(): + faclist = list(fm._matchfactories(fixturedefs, parentid)) + if faclist: + available.add(name) + if self.argname in available: + msg = " recursive dependency involving fixture '{}' detected".format( + self.argname + ) + else: + msg = "fixture '{}' not found".format(self.argname) + msg += "\n available fixtures: {}".format(", ".join(sorted(available))) + msg += "\n use 'pytest --fixtures [testpath]' for help on them." + + return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname) + + +class FixtureLookupErrorRepr(TerminalRepr): + def __init__(self, filename, firstlineno, tblines, errorstring, argname): + self.tblines = tblines + self.errorstring = errorstring + self.filename = filename + self.firstlineno = firstlineno + self.argname = argname + + def toterminal(self, tw): + # tw.line("FixtureLookupError: %s" %(self.argname), red=True) + for tbline in self.tblines: + tw.line(tbline.rstrip()) + lines = self.errorstring.split("\n") + if lines: + tw.line( + "{} {}".format(FormattedExcinfo.fail_marker, lines[0].strip()), + red=True, + ) + for line in lines[1:]: + tw.line( + "{} {}".format(FormattedExcinfo.flow_marker, line.strip()), + red=True, + ) + tw.line() + tw.line("%s:%d" % (self.filename, self.firstlineno + 1)) + + +def fail_fixturefunc(fixturefunc, msg): + fs, lineno = getfslineno(fixturefunc) + location = "%s:%s" % (fs, lineno + 1) + source = _pytest._code.Source(fixturefunc) + fail(msg + ":\n\n" + str(source.indent()) + "\n" + location, pytrace=False) + + +def call_fixture_func(fixturefunc, request, kwargs): + yieldctx = is_generator(fixturefunc) + if yieldctx: + it = fixturefunc(**kwargs) + res = next(it) + finalizer = functools.partial(_teardown_yield_fixture, fixturefunc, it) + request.addfinalizer(finalizer) + else: + res = fixturefunc(**kwargs) + return res + + +def _teardown_yield_fixture(fixturefunc, it): + """Executes the teardown of a fixture function by advancing the iterator after the + yield and ensure the iteration ends (if not it means there is more than one yield in the function)""" + try: + next(it) + except StopIteration: + pass + else: + fail_fixturefunc( + fixturefunc, "yield_fixture function has more than one 'yield'" + ) + + +class FixtureDef(object): + """ A container for a factory definition. """ + + def __init__( + self, + fixturemanager, + baseid, + argname, + func, + scope, + params, + unittest=False, + ids=None, + ): + self._fixturemanager = fixturemanager + self.baseid = baseid or "" + self.has_location = baseid is not None + self.func = func + self.argname = argname + self.scope = scope + self.scopenum = scope2index( + scope or "function", + descr="Fixture '{}'".format(func.__name__), + where=baseid, + ) + self.params = params + self.argnames = getfuncargnames(func, is_method=unittest) + self.unittest = unittest + self.ids = ids + self._finalizers = [] + + def addfinalizer(self, finalizer): + self._finalizers.append(finalizer) + + def finish(self, request): + exceptions = [] + try: + while self._finalizers: + try: + func = self._finalizers.pop() + func() + except: # noqa + exceptions.append(sys.exc_info()) + if exceptions: + e = exceptions[0] + # Ensure to not keep frame references through traceback. + del exceptions + six.reraise(*e) + finally: + hook = self._fixturemanager.session.gethookproxy(request.node.fspath) + hook.pytest_fixture_post_finalizer(fixturedef=self, request=request) + # even if finalization fails, we invalidate + # the cached fixture value and remove + # all finalizers because they may be bound methods which will + # keep instances alive + if hasattr(self, "cached_result"): + del self.cached_result + self._finalizers = [] + + def execute(self, request): + # get required arguments and register our own finish() + # with their finalization + for argname in self.argnames: + fixturedef = request._get_active_fixturedef(argname) + if argname != "request": + fixturedef.addfinalizer(functools.partial(self.finish, request=request)) + + my_cache_key = request.param_index + cached_result = getattr(self, "cached_result", None) + if cached_result is not None: + result, cache_key, err = cached_result + if my_cache_key == cache_key: + if err is not None: + six.reraise(*err) + else: + return result + # we have a previous but differently parametrized fixture instance + # so we need to tear it down before creating a new one + self.finish(request) + assert not hasattr(self, "cached_result") + + hook = self._fixturemanager.session.gethookproxy(request.node.fspath) + return hook.pytest_fixture_setup(fixturedef=self, request=request) + + def __repr__(self): + return "" % ( + self.argname, + self.scope, + self.baseid, + ) + + +def resolve_fixture_function(fixturedef, request): + """Gets the actual callable that can be called to obtain the fixture value, dealing with unittest-specific + instances and bound methods. + """ + fixturefunc = fixturedef.func + if fixturedef.unittest: + if request.instance is not None: + # bind the unbound method to the TestCase instance + fixturefunc = fixturedef.func.__get__(request.instance) + else: + # the fixture function needs to be bound to the actual + # request.instance so that code working with "fixturedef" behaves + # as expected. + if request.instance is not None: + fixturefunc = getimfunc(fixturedef.func) + if fixturefunc != fixturedef.func: + fixturefunc = fixturefunc.__get__(request.instance) + return fixturefunc + + +def pytest_fixture_setup(fixturedef, request): + """ Execution of fixture setup. """ + kwargs = {} + for argname in fixturedef.argnames: + fixdef = request._get_active_fixturedef(argname) + result, arg_cache_key, exc = fixdef.cached_result + request._check_scope(argname, request.scope, fixdef.scope) + kwargs[argname] = result + + fixturefunc = resolve_fixture_function(fixturedef, request) + my_cache_key = request.param_index + try: + result = call_fixture_func(fixturefunc, request, kwargs) + except TEST_OUTCOME: + fixturedef.cached_result = (None, my_cache_key, sys.exc_info()) + raise + fixturedef.cached_result = (result, my_cache_key, None) + return result + + +def _ensure_immutable_ids(ids): + if ids is None: + return + if callable(ids): + return ids + return tuple(ids) + + +def wrap_function_to_error_out_if_called_directly(function, fixture_marker): + """Wrap the given fixture function so we can raise an error about it being called directly, + instead of used as an argument in a test function. + """ + message = FIXTURE_FUNCTION_CALL.format( + name=fixture_marker.name or function.__name__ + ) + + @six.wraps(function) + def result(*args, **kwargs): + fail(message, pytrace=False) + + # keep reference to the original function in our own custom attribute so we don't unwrap + # further than this point and lose useful wrappings like @mock.patch (#3774) + result.__pytest_wrapped__ = _PytestWrapper(function) + + return result + + +@attr.s(frozen=True) +class FixtureFunctionMarker(object): + scope = attr.ib() + params = attr.ib(converter=attr.converters.optional(tuple)) + autouse = attr.ib(default=False) + ids = attr.ib(default=None, converter=_ensure_immutable_ids) + name = attr.ib(default=None) + + def __call__(self, function): + if isclass(function): + raise ValueError("class fixtures not supported (maybe in the future)") + + if getattr(function, "_pytestfixturefunction", False): + raise ValueError( + "fixture is being applied more than once to the same function" + ) + + function = wrap_function_to_error_out_if_called_directly(function, self) + + name = self.name or function.__name__ + if name == "request": + warnings.warn(FIXTURE_NAMED_REQUEST) + function._pytestfixturefunction = self + return function + + +def fixture(scope="function", params=None, autouse=False, ids=None, name=None): + """Decorator to mark a fixture factory function. + + This decorator can be used, with or without parameters, to define a + fixture function. + + The name of the fixture function can later be referenced to cause its + invocation ahead of running tests: test + modules or classes can use the ``pytest.mark.usefixtures(fixturename)`` + marker. + + Test functions can directly use fixture names as input + arguments in which case the fixture instance returned from the fixture + function will be injected. + + Fixtures can provide their values to test functions using ``return`` or ``yield`` + statements. When using ``yield`` the code block after the ``yield`` statement is executed + as teardown code regardless of the test outcome, and must yield exactly once. + + :arg scope: the scope for which this fixture is shared, one of + ``"function"`` (default), ``"class"``, ``"module"``, + ``"package"`` or ``"session"``. + + ``"package"`` is considered **experimental** at this time. + + :arg params: an optional list of parameters which will cause multiple + invocations of the fixture function and all of the tests + using it. + The current parameter is available in ``request.param``. + + :arg autouse: if True, the fixture func is activated for all tests that + can see it. If False (the default) then an explicit + reference is needed to activate the fixture. + + :arg ids: list of string ids each corresponding to the params + so that they are part of the test id. If no ids are provided + they will be generated automatically from the params. + + :arg name: the name of the fixture. This defaults to the name of the + decorated function. If a fixture is used in the same module in + which it is defined, the function name of the fixture will be + shadowed by the function arg that requests the fixture; one way + to resolve this is to name the decorated function + ``fixture_`` and then use + ``@pytest.fixture(name='')``. + """ + if callable(scope) and params is None and autouse is False: + # direct decoration + return FixtureFunctionMarker("function", params, autouse, name=name)(scope) + if params is not None and not isinstance(params, (list, tuple)): + params = list(params) + return FixtureFunctionMarker(scope, params, autouse, ids=ids, name=name) + + +def yield_fixture(scope="function", params=None, autouse=False, ids=None, name=None): + """ (return a) decorator to mark a yield-fixture factory function. + + .. deprecated:: 3.0 + Use :py:func:`pytest.fixture` directly instead. + """ + return fixture(scope=scope, params=params, autouse=autouse, ids=ids, name=name) + + +defaultfuncargprefixmarker = fixture() + + +@fixture(scope="session") +def pytestconfig(request): + """Session-scoped fixture that returns the :class:`_pytest.config.Config` object. + + Example:: + + def test_foo(pytestconfig): + if pytestconfig.getoption("verbose") > 0: + ... + + """ + return request.config + + +def pytest_addoption(parser): + parser.addini( + "usefixtures", + type="args", + default=[], + help="list of default fixtures to be used with this project", + ) + + +class FixtureManager(object): + """ + pytest fixtures definitions and information is stored and managed + from this class. + + During collection fm.parsefactories() is called multiple times to parse + fixture function definitions into FixtureDef objects and internal + data structures. + + During collection of test functions, metafunc-mechanics instantiate + a FuncFixtureInfo object which is cached per node/func-name. + This FuncFixtureInfo object is later retrieved by Function nodes + which themselves offer a fixturenames attribute. + + The FuncFixtureInfo object holds information about fixtures and FixtureDefs + relevant for a particular function. An initial list of fixtures is + assembled like this: + + - ini-defined usefixtures + - autouse-marked fixtures along the collection chain up from the function + - usefixtures markers at module/class/function level + - test function funcargs + + Subsequently the funcfixtureinfo.fixturenames attribute is computed + as the closure of the fixtures needed to setup the initial fixtures, + i. e. fixtures needed by fixture functions themselves are appended + to the fixturenames list. + + Upon the test-setup phases all fixturenames are instantiated, retrieved + by a lookup of their FuncFixtureInfo. + """ + + FixtureLookupError = FixtureLookupError + FixtureLookupErrorRepr = FixtureLookupErrorRepr + + def __init__(self, session): + self.session = session + self.config = session.config + self._arg2fixturedefs = {} + self._holderobjseen = set() + self._arg2finish = {} + self._nodeid_and_autousenames = [("", self.config.getini("usefixtures"))] + session.config.pluginmanager.register(self, "funcmanage") + + def _get_direct_parametrize_args(self, node): + """This function returns all the direct parametrization + arguments of a node, so we don't mistake them for fixtures + + Check https://github.com/pytest-dev/pytest/issues/5036 + + This things are done later as well when dealing with parametrization + so this could be improved + """ + from _pytest.mark import ParameterSet + + parametrize_argnames = [] + for marker in node.iter_markers(name="parametrize"): + if not marker.kwargs.get("indirect", False): + p_argnames, _ = ParameterSet._parse_parametrize_args( + *marker.args, **marker.kwargs + ) + parametrize_argnames.extend(p_argnames) + + return parametrize_argnames + + def getfixtureinfo(self, node, func, cls, funcargs=True): + if funcargs and not getattr(node, "nofuncargs", False): + argnames = getfuncargnames(func, cls=cls) + else: + argnames = () + + usefixtures = itertools.chain.from_iterable( + mark.args for mark in node.iter_markers(name="usefixtures") + ) + initialnames = tuple(usefixtures) + argnames + fm = node.session._fixturemanager + initialnames, names_closure, arg2fixturedefs = fm.getfixtureclosure( + initialnames, node, ignore_args=self._get_direct_parametrize_args(node) + ) + return FuncFixtureInfo(argnames, initialnames, names_closure, arg2fixturedefs) + + def pytest_plugin_registered(self, plugin): + nodeid = None + try: + p = py.path.local(plugin.__file__).realpath() + except AttributeError: + pass + else: + # construct the base nodeid which is later used to check + # what fixtures are visible for particular tests (as denoted + # by their test id) + if p.basename.startswith("conftest.py"): + nodeid = p.dirpath().relto(self.config.rootdir) + if p.sep != nodes.SEP: + nodeid = nodeid.replace(p.sep, nodes.SEP) + + self.parsefactories(plugin, nodeid) + + def _getautousenames(self, nodeid): + """ return a tuple of fixture names to be used. """ + autousenames = [] + for baseid, basenames in self._nodeid_and_autousenames: + if nodeid.startswith(baseid): + if baseid: + i = len(baseid) + nextchar = nodeid[i : i + 1] + if nextchar and nextchar not in ":/": + continue + autousenames.extend(basenames) + return autousenames + + def getfixtureclosure(self, fixturenames, parentnode, ignore_args=()): + # collect the closure of all fixtures , starting with the given + # fixturenames as the initial set. As we have to visit all + # factory definitions anyway, we also return an arg2fixturedefs + # mapping so that the caller can reuse it and does not have + # to re-discover fixturedefs again for each fixturename + # (discovering matching fixtures for a given name/node is expensive) + + parentid = parentnode.nodeid + fixturenames_closure = self._getautousenames(parentid) + + def merge(otherlist): + for arg in otherlist: + if arg not in fixturenames_closure: + fixturenames_closure.append(arg) + + merge(fixturenames) + + # at this point, fixturenames_closure contains what we call "initialnames", + # which is a set of fixturenames the function immediately requests. We + # need to return it as well, so save this. + initialnames = tuple(fixturenames_closure) + + arg2fixturedefs = {} + lastlen = -1 + while lastlen != len(fixturenames_closure): + lastlen = len(fixturenames_closure) + for argname in fixturenames_closure: + if argname in ignore_args: + continue + if argname in arg2fixturedefs: + continue + fixturedefs = self.getfixturedefs(argname, parentid) + if fixturedefs: + arg2fixturedefs[argname] = fixturedefs + merge(fixturedefs[-1].argnames) + + def sort_by_scope(arg_name): + try: + fixturedefs = arg2fixturedefs[arg_name] + except KeyError: + return scopes.index("function") + else: + return fixturedefs[-1].scopenum + + fixturenames_closure.sort(key=sort_by_scope) + return initialnames, fixturenames_closure, arg2fixturedefs + + def pytest_generate_tests(self, metafunc): + for argname in metafunc.fixturenames: + faclist = metafunc._arg2fixturedefs.get(argname) + if faclist: + fixturedef = faclist[-1] + if fixturedef.params is not None: + markers = list(metafunc.definition.iter_markers("parametrize")) + for parametrize_mark in markers: + if "argnames" in parametrize_mark.kwargs: + argnames = parametrize_mark.kwargs["argnames"] + else: + argnames = parametrize_mark.args[0] + + if not isinstance(argnames, (tuple, list)): + argnames = [ + x.strip() for x in argnames.split(",") if x.strip() + ] + if argname in argnames: + break + else: + metafunc.parametrize( + argname, + fixturedef.params, + indirect=True, + scope=fixturedef.scope, + ids=fixturedef.ids, + ) + else: + continue # will raise FixtureLookupError at setup time + + def pytest_collection_modifyitems(self, items): + # separate parametrized setups + items[:] = reorder_items(items) + + def parsefactories(self, node_or_obj, nodeid=NOTSET, unittest=False): + if nodeid is not NOTSET: + holderobj = node_or_obj + else: + holderobj = node_or_obj.obj + nodeid = node_or_obj.nodeid + if holderobj in self._holderobjseen: + return + + self._holderobjseen.add(holderobj) + autousenames = [] + for name in dir(holderobj): + # The attribute can be an arbitrary descriptor, so the attribute + # access below can raise. safe_getatt() ignores such exceptions. + obj = safe_getattr(holderobj, name, None) + marker = getfixturemarker(obj) + if not isinstance(marker, FixtureFunctionMarker): + # magic globals with __getattr__ might have got us a wrong + # fixture attribute + continue + + if marker.name: + name = marker.name + + # during fixture definition we wrap the original fixture function + # to issue a warning if called directly, so here we unwrap it in order to not emit the warning + # when pytest itself calls the fixture function + if six.PY2 and unittest: + # hack on Python 2 because of the unbound methods + obj = get_real_func(obj) + else: + obj = get_real_method(obj, holderobj) + + fixture_def = FixtureDef( + self, + nodeid, + name, + obj, + marker.scope, + marker.params, + unittest=unittest, + ids=marker.ids, + ) + + faclist = self._arg2fixturedefs.setdefault(name, []) + if fixture_def.has_location: + faclist.append(fixture_def) + else: + # fixturedefs with no location are at the front + # so this inserts the current fixturedef after the + # existing fixturedefs from external plugins but + # before the fixturedefs provided in conftests. + i = len([f for f in faclist if not f.has_location]) + faclist.insert(i, fixture_def) + if marker.autouse: + autousenames.append(name) + + if autousenames: + self._nodeid_and_autousenames.append((nodeid or "", autousenames)) + + def getfixturedefs(self, argname, nodeid): + """ + Gets a list of fixtures which are applicable to the given node id. + + :param str argname: name of the fixture to search for + :param str nodeid: full node id of the requesting test. + :return: list[FixtureDef] + """ + try: + fixturedefs = self._arg2fixturedefs[argname] + except KeyError: + return None + return tuple(self._matchfactories(fixturedefs, nodeid)) + + def _matchfactories(self, fixturedefs, nodeid): + for fixturedef in fixturedefs: + if nodes.ischildnode(fixturedef.baseid, nodeid): + yield fixturedef diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/freeze_support.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/freeze_support.py new file mode 100644 index 0000000000000000000000000000000000000000..aeeec2a56b4d35820837dd296400f44fb98e24d0 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/freeze_support.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +""" +Provides a function to report all internal modules for using freezing tools +pytest +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + + +def freeze_includes(): + """ + Returns a list of module names used by pytest that should be + included by cx_freeze. + """ + import py + import _pytest + + result = list(_iter_all_modules(py)) + result += list(_iter_all_modules(_pytest)) + return result + + +def _iter_all_modules(package, prefix=""): + """ + Iterates over the names of all modules that can be found in the given + package, recursively. + Example: + _iter_all_modules(_pytest) -> + ['_pytest.assertion.newinterpret', + '_pytest.capture', + '_pytest.core', + ... + ] + """ + import os + import pkgutil + + if type(package) is not str: + path, prefix = package.__path__[0], package.__name__ + "." + else: + path = package + for _, name, is_package in pkgutil.iter_modules([path]): + if is_package: + for m in _iter_all_modules(os.path.join(path, name), prefix=name + "."): + yield prefix + m + else: + yield prefix + name diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/helpconfig.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/helpconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..56811601608e352766a4ca4b65b5cdbcf8987a4e --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/helpconfig.py @@ -0,0 +1,247 @@ +# -*- coding: utf-8 -*- +""" version info, help messages, tracing configuration. """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import sys +from argparse import Action + +import py + +import pytest +from _pytest.config import PrintHelp + + +class HelpAction(Action): + """This is an argparse Action that will raise an exception in + order to skip the rest of the argument parsing when --help is passed. + This prevents argparse from quitting due to missing required arguments + when any are defined, for example by ``pytest_addoption``. + This is similar to the way that the builtin argparse --help option is + implemented by raising SystemExit. + """ + + def __init__(self, option_strings, dest=None, default=False, help=None): + super(HelpAction, self).__init__( + option_strings=option_strings, + dest=dest, + const=True, + default=default, + nargs=0, + help=help, + ) + + def __call__(self, parser, namespace, values, option_string=None): + setattr(namespace, self.dest, self.const) + + # We should only skip the rest of the parsing after preparse is done + if getattr(parser._parser, "after_preparse", False): + raise PrintHelp + + +def pytest_addoption(parser): + group = parser.getgroup("debugconfig") + group.addoption( + "--version", + action="store_true", + help="display pytest lib version and import information.", + ) + group._addoption( + "-h", + "--help", + action=HelpAction, + dest="help", + help="show help message and configuration info", + ) + group._addoption( + "-p", + action="append", + dest="plugins", + default=[], + metavar="name", + help="early-load given plugin module name or entry point (multi-allowed). " + "To avoid loading of plugins, use the `no:` prefix, e.g. " + "`no:doctest`.", + ) + group.addoption( + "--traceconfig", + "--trace-config", + action="store_true", + default=False, + help="trace considerations of conftest.py files.", + ), + group.addoption( + "--debug", + action="store_true", + dest="debug", + default=False, + help="store internal tracing debug information in 'pytestdebug.log'.", + ) + group._addoption( + "-o", + "--override-ini", + dest="override_ini", + action="append", + help='override ini option with "option=value" style, e.g. `-o xfail_strict=True -o cache_dir=cache`.', + ) + + +@pytest.hookimpl(hookwrapper=True) +def pytest_cmdline_parse(): + outcome = yield + config = outcome.get_result() + if config.option.debug: + path = os.path.abspath("pytestdebug.log") + debugfile = open(path, "w") + debugfile.write( + "versions pytest-%s, py-%s, " + "python-%s\ncwd=%s\nargs=%s\n\n" + % ( + pytest.__version__, + py.__version__, + ".".join(map(str, sys.version_info)), + os.getcwd(), + config._origargs, + ) + ) + config.trace.root.setwriter(debugfile.write) + undo_tracing = config.pluginmanager.enable_tracing() + sys.stderr.write("writing pytestdebug information to %s\n" % path) + + def unset_tracing(): + debugfile.close() + sys.stderr.write("wrote pytestdebug information to %s\n" % debugfile.name) + config.trace.root.setwriter(None) + undo_tracing() + + config.add_cleanup(unset_tracing) + + +def showversion(config): + p = py.path.local(pytest.__file__) + sys.stderr.write( + "This is pytest version %s, imported from %s\n" % (pytest.__version__, p) + ) + plugininfo = getpluginversioninfo(config) + if plugininfo: + for line in plugininfo: + sys.stderr.write(line + "\n") + + +def pytest_cmdline_main(config): + if config.option.version: + showversion(config) + return 0 + elif config.option.help: + config._do_configure() + showhelp(config) + config._ensure_unconfigure() + return 0 + + +def showhelp(config): + import textwrap + + reporter = config.pluginmanager.get_plugin("terminalreporter") + tw = reporter._tw + tw.write(config._parser.optparser.format_help()) + tw.line() + tw.line( + "[pytest] ini-options in the first pytest.ini|tox.ini|setup.cfg file found:" + ) + tw.line() + + columns = tw.fullwidth # costly call + indent_len = 24 # based on argparse's max_help_position=24 + indent = " " * indent_len + for name in config._parser._ininames: + help, type, default = config._parser._inidict[name] + if type is None: + type = "string" + spec = "%s (%s):" % (name, type) + tw.write(" %s" % spec) + spec_len = len(spec) + if spec_len > (indent_len - 3): + # Display help starting at a new line. + tw.line() + helplines = textwrap.wrap( + help, + columns, + initial_indent=indent, + subsequent_indent=indent, + break_on_hyphens=False, + ) + + for line in helplines: + tw.line(line) + else: + # Display help starting after the spec, following lines indented. + tw.write(" " * (indent_len - spec_len - 2)) + wrapped = textwrap.wrap(help, columns - indent_len, break_on_hyphens=False) + + tw.line(wrapped[0]) + for line in wrapped[1:]: + tw.line(indent + line) + + tw.line() + tw.line("environment variables:") + vars = [ + ("PYTEST_ADDOPTS", "extra command line options"), + ("PYTEST_PLUGINS", "comma-separated plugins to load during startup"), + ("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "set to disable plugin auto-loading"), + ("PYTEST_DEBUG", "set to enable debug tracing of pytest's internals"), + ] + for name, help in vars: + tw.line(" %-24s %s" % (name, help)) + tw.line() + tw.line() + + tw.line("to see available markers type: pytest --markers") + tw.line("to see available fixtures type: pytest --fixtures") + tw.line( + "(shown according to specified file_or_dir or current dir " + "if not specified; fixtures with leading '_' are only shown " + "with the '-v' option" + ) + + for warningreport in reporter.stats.get("warnings", []): + tw.line("warning : " + warningreport.message, red=True) + return + + +conftest_options = [("pytest_plugins", "list of plugin names to load")] + + +def getpluginversioninfo(config): + lines = [] + plugininfo = config.pluginmanager.list_plugin_distinfo() + if plugininfo: + lines.append("setuptools registered plugins:") + for plugin, dist in plugininfo: + loc = getattr(plugin, "__file__", repr(plugin)) + content = "%s-%s at %s" % (dist.project_name, dist.version, loc) + lines.append(" " + content) + return lines + + +def pytest_report_header(config): + lines = [] + if config.option.debug or config.option.traceconfig: + lines.append("using: pytest-%s pylib-%s" % (pytest.__version__, py.__version__)) + + verinfo = getpluginversioninfo(config) + if verinfo: + lines.extend(verinfo) + + if config.option.traceconfig: + lines.append("active plugins:") + items = config.pluginmanager.list_name_plugin() + for name, plugin in items: + if hasattr(plugin, "__file__"): + r = plugin.__file__ + else: + r = repr(plugin) + lines.append(" %-20s: %s" % (name, r)) + return lines diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/hookspec.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/hookspec.py new file mode 100644 index 0000000000000000000000000000000000000000..7ab6154b1766b9774dcfe4f11fd932c178173333 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/hookspec.py @@ -0,0 +1,639 @@ +# -*- coding: utf-8 -*- +""" hook specifications for pytest plugins, invoked from main.py and builtin plugins. """ +from pluggy import HookspecMarker + +from _pytest.deprecated import PYTEST_LOGWARNING + +hookspec = HookspecMarker("pytest") + +# ------------------------------------------------------------------------- +# Initialization hooks called for every plugin +# ------------------------------------------------------------------------- + + +@hookspec(historic=True) +def pytest_addhooks(pluginmanager): + """called at plugin registration time to allow adding new hooks via a call to + ``pluginmanager.add_hookspecs(module_or_class, prefix)``. + + + :param _pytest.config.PytestPluginManager pluginmanager: pytest plugin manager + + .. note:: + This hook is incompatible with ``hookwrapper=True``. + """ + + +@hookspec(historic=True) +def pytest_plugin_registered(plugin, manager): + """ a new pytest plugin got registered. + + :param plugin: the plugin module or instance + :param _pytest.config.PytestPluginManager manager: pytest plugin manager + + .. note:: + This hook is incompatible with ``hookwrapper=True``. + """ + + +@hookspec(historic=True) +def pytest_addoption(parser): + """register argparse-style options and ini-style config values, + called once at the beginning of a test run. + + .. note:: + + This function should be implemented only in plugins or ``conftest.py`` + files situated at the tests root directory due to how pytest + :ref:`discovers plugins during startup `. + + :arg _pytest.config.Parser parser: To add command line options, call + :py:func:`parser.addoption(...) <_pytest.config.Parser.addoption>`. + To add ini-file values call :py:func:`parser.addini(...) + <_pytest.config.Parser.addini>`. + + Options can later be accessed through the + :py:class:`config <_pytest.config.Config>` object, respectively: + + - :py:func:`config.getoption(name) <_pytest.config.Config.getoption>` to + retrieve the value of a command line option. + + - :py:func:`config.getini(name) <_pytest.config.Config.getini>` to retrieve + a value read from an ini-style file. + + The config object is passed around on many internal objects via the ``.config`` + attribute or can be retrieved as the ``pytestconfig`` fixture. + + .. note:: + This hook is incompatible with ``hookwrapper=True``. + """ + + +@hookspec(historic=True) +def pytest_configure(config): + """ + Allows plugins and conftest files to perform initial configuration. + + This hook is called for every plugin and initial conftest file + after command line options have been parsed. + + After that, the hook is called for other conftest files as they are + imported. + + .. note:: + This hook is incompatible with ``hookwrapper=True``. + + :arg _pytest.config.Config config: pytest config object + """ + + +# ------------------------------------------------------------------------- +# Bootstrapping hooks called for plugins registered early enough: +# internal and 3rd party plugins. +# ------------------------------------------------------------------------- + + +@hookspec(firstresult=True) +def pytest_cmdline_parse(pluginmanager, args): + """return initialized config object, parsing the specified args. + + Stops at first non-None result, see :ref:`firstresult` + + .. note:: + This hook will only be called for plugin classes passed to the ``plugins`` arg when using `pytest.main`_ to + perform an in-process test run. + + :param _pytest.config.PytestPluginManager pluginmanager: pytest plugin manager + :param list[str] args: list of arguments passed on the command line + """ + + +def pytest_cmdline_preparse(config, args): + """(**Deprecated**) modify command line arguments before option parsing. + + This hook is considered deprecated and will be removed in a future pytest version. Consider + using :func:`pytest_load_initial_conftests` instead. + + .. note:: + This hook will not be called for ``conftest.py`` files, only for setuptools plugins. + + :param _pytest.config.Config config: pytest config object + :param list[str] args: list of arguments passed on the command line + """ + + +@hookspec(firstresult=True) +def pytest_cmdline_main(config): + """ called for performing the main command line action. The default + implementation will invoke the configure hooks and runtest_mainloop. + + .. note:: + This hook will not be called for ``conftest.py`` files, only for setuptools plugins. + + Stops at first non-None result, see :ref:`firstresult` + + :param _pytest.config.Config config: pytest config object + """ + + +def pytest_load_initial_conftests(early_config, parser, args): + """ implements the loading of initial conftest files ahead + of command line option parsing. + + .. note:: + This hook will not be called for ``conftest.py`` files, only for setuptools plugins. + + :param _pytest.config.Config early_config: pytest config object + :param list[str] args: list of arguments passed on the command line + :param _pytest.config.Parser parser: to add command line options + """ + + +# ------------------------------------------------------------------------- +# collection hooks +# ------------------------------------------------------------------------- + + +@hookspec(firstresult=True) +def pytest_collection(session): + """Perform the collection protocol for the given session. + + Stops at first non-None result, see :ref:`firstresult`. + + :param _pytest.main.Session session: the pytest session object + """ + + +def pytest_collection_modifyitems(session, config, items): + """ called after collection has been performed, may filter or re-order + the items in-place. + + :param _pytest.main.Session session: the pytest session object + :param _pytest.config.Config config: pytest config object + :param List[_pytest.nodes.Item] items: list of item objects + """ + + +def pytest_collection_finish(session): + """ called after collection has been performed and modified. + + :param _pytest.main.Session session: the pytest session object + """ + + +@hookspec(firstresult=True) +def pytest_ignore_collect(path, config): + """ return True to prevent considering this path for collection. + This hook is consulted for all files and directories prior to calling + more specific hooks. + + Stops at first non-None result, see :ref:`firstresult` + + :param path: a :py:class:`py.path.local` - the path to analyze + :param _pytest.config.Config config: pytest config object + """ + + +@hookspec(firstresult=True) +def pytest_collect_directory(path, parent): + """ called before traversing a directory for collection files. + + Stops at first non-None result, see :ref:`firstresult` + + :param path: a :py:class:`py.path.local` - the path to analyze + """ + + +def pytest_collect_file(path, parent): + """ return collection Node or None for the given path. Any new node + needs to have the specified ``parent`` as a parent. + + :param path: a :py:class:`py.path.local` - the path to collect + """ + + +# logging hooks for collection + + +def pytest_collectstart(collector): + """ collector starts collecting. """ + + +def pytest_itemcollected(item): + """ we just collected a test item. """ + + +def pytest_collectreport(report): + """ collector finished collecting. """ + + +def pytest_deselected(items): + """ called for test items deselected, e.g. by keyword. """ + + +@hookspec(firstresult=True) +def pytest_make_collect_report(collector): + """ perform ``collector.collect()`` and return a CollectReport. + + Stops at first non-None result, see :ref:`firstresult` """ + + +# ------------------------------------------------------------------------- +# Python test function related hooks +# ------------------------------------------------------------------------- + + +@hookspec(firstresult=True) +def pytest_pycollect_makemodule(path, parent): + """ return a Module collector or None for the given path. + This hook will be called for each matching test module path. + The pytest_collect_file hook needs to be used if you want to + create test modules for files that do not match as a test module. + + Stops at first non-None result, see :ref:`firstresult` + + :param path: a :py:class:`py.path.local` - the path of module to collect + """ + + +@hookspec(firstresult=True) +def pytest_pycollect_makeitem(collector, name, obj): + """ return custom item/collector for a python object in a module, or None. + + Stops at first non-None result, see :ref:`firstresult` """ + + +@hookspec(firstresult=True) +def pytest_pyfunc_call(pyfuncitem): + """ call underlying test function. + + Stops at first non-None result, see :ref:`firstresult` """ + + +def pytest_generate_tests(metafunc): + """ generate (multiple) parametrized calls to a test function.""" + + +@hookspec(firstresult=True) +def pytest_make_parametrize_id(config, val, argname): + """Return a user-friendly string representation of the given ``val`` that will be used + by @pytest.mark.parametrize calls. Return None if the hook doesn't know about ``val``. + The parameter name is available as ``argname``, if required. + + Stops at first non-None result, see :ref:`firstresult` + + :param _pytest.config.Config config: pytest config object + :param val: the parametrized value + :param str argname: the automatic parameter name produced by pytest + """ + + +# ------------------------------------------------------------------------- +# generic runtest related hooks +# ------------------------------------------------------------------------- + + +@hookspec(firstresult=True) +def pytest_runtestloop(session): + """ called for performing the main runtest loop + (after collection finished). + + Stops at first non-None result, see :ref:`firstresult` + + :param _pytest.main.Session session: the pytest session object + """ + + +def pytest_itemstart(item, node): + """(**Deprecated**) use pytest_runtest_logstart. """ + + +@hookspec(firstresult=True) +def pytest_runtest_protocol(item, nextitem): + """ implements the runtest_setup/call/teardown protocol for + the given test item, including capturing exceptions and calling + reporting hooks. + + :arg item: test item for which the runtest protocol is performed. + + :arg nextitem: the scheduled-to-be-next test item (or None if this + is the end my friend). This argument is passed on to + :py:func:`pytest_runtest_teardown`. + + :return boolean: True if no further hook implementations should be invoked. + + + Stops at first non-None result, see :ref:`firstresult` """ + + +def pytest_runtest_logstart(nodeid, location): + """ signal the start of running a single test item. + + This hook will be called **before** :func:`pytest_runtest_setup`, :func:`pytest_runtest_call` and + :func:`pytest_runtest_teardown` hooks. + + :param str nodeid: full id of the item + :param location: a triple of ``(filename, linenum, testname)`` + """ + + +def pytest_runtest_logfinish(nodeid, location): + """ signal the complete finish of running a single test item. + + This hook will be called **after** :func:`pytest_runtest_setup`, :func:`pytest_runtest_call` and + :func:`pytest_runtest_teardown` hooks. + + :param str nodeid: full id of the item + :param location: a triple of ``(filename, linenum, testname)`` + """ + + +def pytest_runtest_setup(item): + """ called before ``pytest_runtest_call(item)``. """ + + +def pytest_runtest_call(item): + """ called to execute the test ``item``. """ + + +def pytest_runtest_teardown(item, nextitem): + """ called after ``pytest_runtest_call``. + + :arg nextitem: the scheduled-to-be-next test item (None if no further + test item is scheduled). This argument can be used to + perform exact teardowns, i.e. calling just enough finalizers + so that nextitem only needs to call setup-functions. + """ + + +@hookspec(firstresult=True) +def pytest_runtest_makereport(item, call): + """ return a :py:class:`_pytest.runner.TestReport` object + for the given :py:class:`pytest.Item <_pytest.main.Item>` and + :py:class:`_pytest.runner.CallInfo`. + + Stops at first non-None result, see :ref:`firstresult` """ + + +def pytest_runtest_logreport(report): + """ process a test setup/call/teardown report relating to + the respective phase of executing a test. """ + + +@hookspec(firstresult=True) +def pytest_report_to_serializable(config, report): + """ + .. warning:: + This hook is experimental and subject to change between pytest releases, even + bug fixes. + + The intent is for this to be used by plugins maintained by the core-devs, such + as ``pytest-xdist``, ``pytest-subtests``, and as a replacement for the internal + 'resultlog' plugin. + + In the future it might become part of the public hook API. + + Serializes the given report object into a data structure suitable for sending + over the wire, e.g. converted to JSON. + """ + + +@hookspec(firstresult=True) +def pytest_report_from_serializable(config, data): + """ + .. warning:: + This hook is experimental and subject to change between pytest releases, even + bug fixes. + + The intent is for this to be used by plugins maintained by the core-devs, such + as ``pytest-xdist``, ``pytest-subtests``, and as a replacement for the internal + 'resultlog' plugin. + + In the future it might become part of the public hook API. + + Restores a report object previously serialized with pytest_report_to_serializable(). + """ + + +# ------------------------------------------------------------------------- +# Fixture related hooks +# ------------------------------------------------------------------------- + + +@hookspec(firstresult=True) +def pytest_fixture_setup(fixturedef, request): + """ performs fixture setup execution. + + :return: The return value of the call to the fixture function + + Stops at first non-None result, see :ref:`firstresult` + + .. note:: + If the fixture function returns None, other implementations of + this hook function will continue to be called, according to the + behavior of the :ref:`firstresult` option. + """ + + +def pytest_fixture_post_finalizer(fixturedef, request): + """ called after fixture teardown, but before the cache is cleared so + the fixture result cache ``fixturedef.cached_result`` can + still be accessed.""" + + +# ------------------------------------------------------------------------- +# test session related hooks +# ------------------------------------------------------------------------- + + +def pytest_sessionstart(session): + """ called after the ``Session`` object has been created and before performing collection + and entering the run test loop. + + :param _pytest.main.Session session: the pytest session object + """ + + +def pytest_sessionfinish(session, exitstatus): + """ called after whole test run finished, right before returning the exit status to the system. + + :param _pytest.main.Session session: the pytest session object + :param int exitstatus: the status which pytest will return to the system + """ + + +def pytest_unconfigure(config): + """ called before test process is exited. + + :param _pytest.config.Config config: pytest config object + """ + + +# ------------------------------------------------------------------------- +# hooks for customizing the assert methods +# ------------------------------------------------------------------------- + + +def pytest_assertrepr_compare(config, op, left, right): + """return explanation for comparisons in failing assert expressions. + + Return None for no custom explanation, otherwise return a list + of strings. The strings will be joined by newlines but any newlines + *in* a string will be escaped. Note that all but the first line will + be indented slightly, the intention is for the first line to be a summary. + + :param _pytest.config.Config config: pytest config object + """ + + +# ------------------------------------------------------------------------- +# hooks for influencing reporting (invoked from _pytest_terminal) +# ------------------------------------------------------------------------- + + +def pytest_report_header(config, startdir): + """ return a string or list of strings to be displayed as header info for terminal reporting. + + :param _pytest.config.Config config: pytest config object + :param startdir: py.path object with the starting dir + + .. note:: + + This function should be implemented only in plugins or ``conftest.py`` + files situated at the tests root directory due to how pytest + :ref:`discovers plugins during startup `. + """ + + +def pytest_report_collectionfinish(config, startdir, items): + """ + .. versionadded:: 3.2 + + return a string or list of strings to be displayed after collection has finished successfully. + + This strings will be displayed after the standard "collected X items" message. + + :param _pytest.config.Config config: pytest config object + :param startdir: py.path object with the starting dir + :param items: list of pytest items that are going to be executed; this list should not be modified. + """ + + +@hookspec(firstresult=True) +def pytest_report_teststatus(report, config): + """ return result-category, shortletter and verbose word for reporting. + + :param _pytest.config.Config config: pytest config object + + Stops at first non-None result, see :ref:`firstresult` """ + + +def pytest_terminal_summary(terminalreporter, exitstatus, config): + """Add a section to terminal summary reporting. + + :param _pytest.terminal.TerminalReporter terminalreporter: the internal terminal reporter object + :param int exitstatus: the exit status that will be reported back to the OS + :param _pytest.config.Config config: pytest config object + + .. versionadded:: 4.2 + The ``config`` parameter. + """ + + +@hookspec(historic=True, warn_on_impl=PYTEST_LOGWARNING) +def pytest_logwarning(message, code, nodeid, fslocation): + """ + .. deprecated:: 3.8 + + This hook is will stop working in a future release. + + pytest no longer triggers this hook, but the + terminal writer still implements it to display warnings issued by + :meth:`_pytest.config.Config.warn` and :meth:`_pytest.nodes.Node.warn`. Calling those functions will be + an error in future releases. + + process a warning specified by a message, a code string, + a nodeid and fslocation (both of which may be None + if the warning is not tied to a particular node/location). + + .. note:: + This hook is incompatible with ``hookwrapper=True``. + """ + + +@hookspec(historic=True) +def pytest_warning_captured(warning_message, when, item): + """ + Process a warning captured by the internal pytest warnings plugin. + + :param warnings.WarningMessage warning_message: + The captured warning. This is the same object produced by :py:func:`warnings.catch_warnings`, and contains + the same attributes as the parameters of :py:func:`warnings.showwarning`. + + :param str when: + Indicates when the warning was captured. Possible values: + + * ``"config"``: during pytest configuration/initialization stage. + * ``"collect"``: during test collection. + * ``"runtest"``: during test execution. + + :param pytest.Item|None item: + **DEPRECATED**: This parameter is incompatible with ``pytest-xdist``, and will always receive ``None`` + in a future release. + + The item being executed if ``when`` is ``"runtest"``, otherwise ``None``. + """ + + +# ------------------------------------------------------------------------- +# doctest hooks +# ------------------------------------------------------------------------- + + +@hookspec(firstresult=True) +def pytest_doctest_prepare_content(content): + """ return processed content for a given doctest + + Stops at first non-None result, see :ref:`firstresult` """ + + +# ------------------------------------------------------------------------- +# error handling and internal debugging hooks +# ------------------------------------------------------------------------- + + +def pytest_internalerror(excrepr, excinfo): + """ called for internal errors. """ + + +def pytest_keyboard_interrupt(excinfo): + """ called for keyboard interrupt. """ + + +def pytest_exception_interact(node, call, report): + """called when an exception was raised which can potentially be + interactively handled. + + This hook is only called if an exception was raised + that is not an internal exception like ``skip.Exception``. + """ + + +def pytest_enter_pdb(config, pdb): + """ called upon pdb.set_trace(), can be used by plugins to take special + action just before the python debugger enters in interactive mode. + + :param _pytest.config.Config config: pytest config object + :param pdb.Pdb pdb: Pdb instance + """ + + +def pytest_leave_pdb(config, pdb): + """ called when leaving pdb (e.g. with continue after pdb.set_trace()). + + Can be used by plugins to take special action just after the python + debugger leaves interactive mode. + + :param _pytest.config.Config config: pytest config object + :param pdb.Pdb pdb: Pdb instance + """ diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/junitxml.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/junitxml.py new file mode 100644 index 0000000000000000000000000000000000000000..3972113cbb03f12a773cc278c9d0be6fcd1e9ef3 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/junitxml.py @@ -0,0 +1,702 @@ +# -*- coding: utf-8 -*- +""" + report test results in JUnit-XML format, + for use with Jenkins and build integration servers. + + +Based on initial code from Ross Lawley. + +Output conforms to https://github.com/jenkinsci/xunit-plugin/blob/master/ +src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import functools +import os +import re +import sys +import time + +import py +import six + +import pytest +from _pytest import nodes +from _pytest.config import filename_arg + +# Python 2.X and 3.X compatibility +if sys.version_info[0] < 3: + from codecs import open + + +class Junit(py.xml.Namespace): + pass + + +# We need to get the subset of the invalid unicode ranges according to +# XML 1.0 which are valid in this python build. Hence we calculate +# this dynamically instead of hardcoding it. The spec range of valid +# chars is: Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] +# | [#x10000-#x10FFFF] +_legal_chars = (0x09, 0x0A, 0x0D) +_legal_ranges = ((0x20, 0x7E), (0x80, 0xD7FF), (0xE000, 0xFFFD), (0x10000, 0x10FFFF)) +_legal_xml_re = [ + u"%s-%s" % (six.unichr(low), six.unichr(high)) + for (low, high) in _legal_ranges + if low < sys.maxunicode +] +_legal_xml_re = [six.unichr(x) for x in _legal_chars] + _legal_xml_re +illegal_xml_re = re.compile(u"[^%s]" % u"".join(_legal_xml_re)) +del _legal_chars +del _legal_ranges +del _legal_xml_re + +_py_ext_re = re.compile(r"\.py$") + + +def bin_xml_escape(arg): + def repl(matchobj): + i = ord(matchobj.group()) + if i <= 0xFF: + return u"#x%02X" % i + else: + return u"#x%04X" % i + + return py.xml.raw(illegal_xml_re.sub(repl, py.xml.escape(arg))) + + +def merge_family(left, right): + result = {} + for kl, vl in left.items(): + for kr, vr in right.items(): + if not isinstance(vl, list): + raise TypeError(type(vl)) + result[kl] = vl + vr + left.update(result) + + +families = {} +families["_base"] = {"testcase": ["classname", "name"]} +families["_base_legacy"] = {"testcase": ["file", "line", "url"]} + +# xUnit 1.x inherits legacy attributes +families["xunit1"] = families["_base"].copy() +merge_family(families["xunit1"], families["_base_legacy"]) + +# xUnit 2.x uses strict base attributes +families["xunit2"] = families["_base"] + + +class _NodeReporter(object): + def __init__(self, nodeid, xml): + self.id = nodeid + self.xml = xml + self.add_stats = self.xml.add_stats + self.family = self.xml.family + self.duration = 0 + self.properties = [] + self.nodes = [] + self.testcase = None + self.attrs = {} + + def append(self, node): + self.xml.add_stats(type(node).__name__) + self.nodes.append(node) + + def add_property(self, name, value): + self.properties.append((str(name), bin_xml_escape(value))) + + def add_attribute(self, name, value): + self.attrs[str(name)] = bin_xml_escape(value) + + def make_properties_node(self): + """Return a Junit node containing custom properties, if any. + """ + if self.properties: + return Junit.properties( + [ + Junit.property(name=name, value=value) + for name, value in self.properties + ] + ) + return "" + + def record_testreport(self, testreport): + assert not self.testcase + names = mangle_test_address(testreport.nodeid) + existing_attrs = self.attrs + classnames = names[:-1] + if self.xml.prefix: + classnames.insert(0, self.xml.prefix) + attrs = { + "classname": ".".join(classnames), + "name": bin_xml_escape(names[-1]), + "file": testreport.location[0], + } + if testreport.location[1] is not None: + attrs["line"] = testreport.location[1] + if hasattr(testreport, "url"): + attrs["url"] = testreport.url + self.attrs = attrs + self.attrs.update(existing_attrs) # restore any user-defined attributes + + # Preserve legacy testcase behavior + if self.family == "xunit1": + return + + # Filter out attributes not permitted by this test family. + # Including custom attributes because they are not valid here. + temp_attrs = {} + for key in self.attrs.keys(): + if key in families[self.family]["testcase"]: + temp_attrs[key] = self.attrs[key] + self.attrs = temp_attrs + + def to_xml(self): + testcase = Junit.testcase(time="%.3f" % self.duration, **self.attrs) + testcase.append(self.make_properties_node()) + for node in self.nodes: + testcase.append(node) + return testcase + + def _add_simple(self, kind, message, data=None): + data = bin_xml_escape(data) + node = kind(data, message=message) + self.append(node) + + def write_captured_output(self, report): + if not self.xml.log_passing_tests and report.passed: + return + + content_out = report.capstdout + content_log = report.caplog + content_err = report.capstderr + + if content_log or content_out: + if content_log and self.xml.logging == "system-out": + if content_out: + # syncing stdout and the log-output is not done yet. It's + # probably not worth the effort. Therefore, first the captured + # stdout is shown and then the captured logs. + content = "\n".join( + [ + " Captured Stdout ".center(80, "-"), + content_out, + "", + " Captured Log ".center(80, "-"), + content_log, + ] + ) + else: + content = content_log + else: + content = content_out + + if content: + tag = getattr(Junit, "system-out") + self.append(tag(bin_xml_escape(content))) + + if content_log or content_err: + if content_log and self.xml.logging == "system-err": + if content_err: + content = "\n".join( + [ + " Captured Stderr ".center(80, "-"), + content_err, + "", + " Captured Log ".center(80, "-"), + content_log, + ] + ) + else: + content = content_log + else: + content = content_err + + if content: + tag = getattr(Junit, "system-err") + self.append(tag(bin_xml_escape(content))) + + def append_pass(self, report): + self.add_stats("passed") + + def append_failure(self, report): + # msg = str(report.longrepr.reprtraceback.extraline) + if hasattr(report, "wasxfail"): + self._add_simple(Junit.skipped, "xfail-marked test passes unexpectedly") + else: + if hasattr(report.longrepr, "reprcrash"): + message = report.longrepr.reprcrash.message + elif isinstance(report.longrepr, six.string_types): + message = report.longrepr + else: + message = str(report.longrepr) + message = bin_xml_escape(message) + fail = Junit.failure(message=message) + fail.append(bin_xml_escape(report.longrepr)) + self.append(fail) + + def append_collect_error(self, report): + # msg = str(report.longrepr.reprtraceback.extraline) + self.append( + Junit.error(bin_xml_escape(report.longrepr), message="collection failure") + ) + + def append_collect_skipped(self, report): + self._add_simple(Junit.skipped, "collection skipped", report.longrepr) + + def append_error(self, report): + if report.when == "teardown": + msg = "test teardown failure" + else: + msg = "test setup failure" + self._add_simple(Junit.error, msg, report.longrepr) + + def append_skipped(self, report): + if hasattr(report, "wasxfail"): + xfailreason = report.wasxfail + if xfailreason.startswith("reason: "): + xfailreason = xfailreason[8:] + self.append( + Junit.skipped( + "", type="pytest.xfail", message=bin_xml_escape(xfailreason) + ) + ) + else: + filename, lineno, skipreason = report.longrepr + if skipreason.startswith("Skipped: "): + skipreason = skipreason[9:] + details = "%s:%s: %s" % (filename, lineno, skipreason) + + self.append( + Junit.skipped( + bin_xml_escape(details), + type="pytest.skip", + message=bin_xml_escape(skipreason), + ) + ) + self.write_captured_output(report) + + def finalize(self): + data = self.to_xml().unicode(indent=0) + self.__dict__.clear() + self.to_xml = lambda: py.xml.raw(data) + + +def _warn_incompatibility_with_xunit2(request, fixture_name): + """Emits a PytestWarning about the given fixture being incompatible with newer xunit revisions""" + from _pytest.warning_types import PytestWarning + + xml = getattr(request.config, "_xml", None) + if xml is not None and xml.family not in ("xunit1", "legacy"): + request.node.warn( + PytestWarning( + "{fixture_name} is incompatible with junit_family '{family}' (use 'legacy' or 'xunit1')".format( + fixture_name=fixture_name, family=xml.family + ) + ) + ) + + +@pytest.fixture +def record_property(request): + """Add an extra properties the calling test. + User properties become part of the test report and are available to the + configured reporters, like JUnit XML. + The fixture is callable with ``(name, value)``, with value being automatically + xml-encoded. + + Example:: + + def test_function(record_property): + record_property("example_key", 1) + """ + _warn_incompatibility_with_xunit2(request, "record_property") + + def append_property(name, value): + request.node.user_properties.append((name, value)) + + return append_property + + +@pytest.fixture +def record_xml_attribute(request): + """Add extra xml attributes to the tag for the calling test. + The fixture is callable with ``(name, value)``, with value being + automatically xml-encoded + """ + from _pytest.warning_types import PytestExperimentalApiWarning + + request.node.warn( + PytestExperimentalApiWarning("record_xml_attribute is an experimental feature") + ) + + _warn_incompatibility_with_xunit2(request, "record_xml_attribute") + + # Declare noop + def add_attr_noop(name, value): + pass + + attr_func = add_attr_noop + + xml = getattr(request.config, "_xml", None) + if xml is not None: + node_reporter = xml.node_reporter(request.node.nodeid) + attr_func = node_reporter.add_attribute + + return attr_func + + +def _check_record_param_type(param, v): + """Used by record_testsuite_property to check that the given parameter name is of the proper + type""" + __tracebackhide__ = True + if not isinstance(v, six.string_types): + msg = "{param} parameter needs to be a string, but {g} given" + raise TypeError(msg.format(param=param, g=type(v).__name__)) + + +@pytest.fixture(scope="session") +def record_testsuite_property(request): + """ + Records a new ```` tag as child of the root ````. This is suitable to + writing global information regarding the entire test suite, and is compatible with ``xunit2`` JUnit family. + + This is a ``session``-scoped fixture which is called with ``(name, value)``. Example: + + .. code-block:: python + + def test_foo(record_testsuite_property): + record_testsuite_property("ARCH", "PPC") + record_testsuite_property("STORAGE_TYPE", "CEPH") + + ``name`` must be a string, ``value`` will be converted to a string and properly xml-escaped. + """ + + __tracebackhide__ = True + + def record_func(name, value): + """noop function in case --junitxml was not passed in the command-line""" + __tracebackhide__ = True + _check_record_param_type("name", name) + + xml = getattr(request.config, "_xml", None) + if xml is not None: + record_func = xml.add_global_property # noqa + return record_func + + +def pytest_addoption(parser): + group = parser.getgroup("terminal reporting") + group.addoption( + "--junitxml", + "--junit-xml", + action="store", + dest="xmlpath", + metavar="path", + type=functools.partial(filename_arg, optname="--junitxml"), + default=None, + help="create junit-xml style report file at given path.", + ) + group.addoption( + "--junitprefix", + "--junit-prefix", + action="store", + metavar="str", + default=None, + help="prepend prefix to classnames in junit-xml output", + ) + parser.addini( + "junit_suite_name", "Test suite name for JUnit report", default="pytest" + ) + parser.addini( + "junit_logging", + "Write captured log messages to JUnit report: " + "one of no|system-out|system-err", + default="no", + ) # choices=['no', 'stdout', 'stderr']) + parser.addini( + "junit_log_passing_tests", + "Capture log information for passing tests to JUnit report: ", + type="bool", + default=True, + ) + parser.addini( + "junit_duration_report", + "Duration time to report: one of total|call", + default="total", + ) # choices=['total', 'call']) + parser.addini( + "junit_family", + "Emit XML for schema: one of legacy|xunit1|xunit2", + default="xunit1", + ) + + +def pytest_configure(config): + xmlpath = config.option.xmlpath + # prevent opening xmllog on slave nodes (xdist) + if xmlpath and not hasattr(config, "slaveinput"): + config._xml = LogXML( + xmlpath, + config.option.junitprefix, + config.getini("junit_suite_name"), + config.getini("junit_logging"), + config.getini("junit_duration_report"), + config.getini("junit_family"), + config.getini("junit_log_passing_tests"), + ) + config.pluginmanager.register(config._xml) + + +def pytest_unconfigure(config): + xml = getattr(config, "_xml", None) + if xml: + del config._xml + config.pluginmanager.unregister(xml) + + +def mangle_test_address(address): + path, possible_open_bracket, params = address.partition("[") + names = path.split("::") + try: + names.remove("()") + except ValueError: + pass + # convert file path to dotted path + names[0] = names[0].replace(nodes.SEP, ".") + names[0] = _py_ext_re.sub("", names[0]) + # put any params back + names[-1] += possible_open_bracket + params + return names + + +class LogXML(object): + def __init__( + self, + logfile, + prefix, + suite_name="pytest", + logging="no", + report_duration="total", + family="xunit1", + log_passing_tests=True, + ): + logfile = os.path.expanduser(os.path.expandvars(logfile)) + self.logfile = os.path.normpath(os.path.abspath(logfile)) + self.prefix = prefix + self.suite_name = suite_name + self.logging = logging + self.log_passing_tests = log_passing_tests + self.report_duration = report_duration + self.family = family + self.stats = dict.fromkeys(["error", "passed", "failure", "skipped"], 0) + self.node_reporters = {} # nodeid -> _NodeReporter + self.node_reporters_ordered = [] + self.global_properties = [] + + # List of reports that failed on call but teardown is pending. + self.open_reports = [] + self.cnt_double_fail_tests = 0 + + # Replaces convenience family with real family + if self.family == "legacy": + self.family = "xunit1" + + def finalize(self, report): + nodeid = getattr(report, "nodeid", report) + # local hack to handle xdist report order + slavenode = getattr(report, "node", None) + reporter = self.node_reporters.pop((nodeid, slavenode)) + if reporter is not None: + reporter.finalize() + + def node_reporter(self, report): + nodeid = getattr(report, "nodeid", report) + # local hack to handle xdist report order + slavenode = getattr(report, "node", None) + + key = nodeid, slavenode + + if key in self.node_reporters: + # TODO: breasks for --dist=each + return self.node_reporters[key] + + reporter = _NodeReporter(nodeid, self) + + self.node_reporters[key] = reporter + self.node_reporters_ordered.append(reporter) + + return reporter + + def add_stats(self, key): + if key in self.stats: + self.stats[key] += 1 + + def _opentestcase(self, report): + reporter = self.node_reporter(report) + reporter.record_testreport(report) + return reporter + + def pytest_runtest_logreport(self, report): + """handle a setup/call/teardown report, generating the appropriate + xml tags as necessary. + + note: due to plugins like xdist, this hook may be called in interlaced + order with reports from other nodes. for example: + + usual call order: + -> setup node1 + -> call node1 + -> teardown node1 + -> setup node2 + -> call node2 + -> teardown node2 + + possible call order in xdist: + -> setup node1 + -> call node1 + -> setup node2 + -> call node2 + -> teardown node2 + -> teardown node1 + """ + close_report = None + if report.passed: + if report.when == "call": # ignore setup/teardown + reporter = self._opentestcase(report) + reporter.append_pass(report) + elif report.failed: + if report.when == "teardown": + # The following vars are needed when xdist plugin is used + report_wid = getattr(report, "worker_id", None) + report_ii = getattr(report, "item_index", None) + close_report = next( + ( + rep + for rep in self.open_reports + if ( + rep.nodeid == report.nodeid + and getattr(rep, "item_index", None) == report_ii + and getattr(rep, "worker_id", None) == report_wid + ) + ), + None, + ) + if close_report: + # We need to open new testcase in case we have failure in + # call and error in teardown in order to follow junit + # schema + self.finalize(close_report) + self.cnt_double_fail_tests += 1 + reporter = self._opentestcase(report) + if report.when == "call": + reporter.append_failure(report) + self.open_reports.append(report) + else: + reporter.append_error(report) + elif report.skipped: + reporter = self._opentestcase(report) + reporter.append_skipped(report) + self.update_testcase_duration(report) + if report.when == "teardown": + reporter = self._opentestcase(report) + reporter.write_captured_output(report) + + for propname, propvalue in report.user_properties: + reporter.add_property(propname, propvalue) + + self.finalize(report) + report_wid = getattr(report, "worker_id", None) + report_ii = getattr(report, "item_index", None) + close_report = next( + ( + rep + for rep in self.open_reports + if ( + rep.nodeid == report.nodeid + and getattr(rep, "item_index", None) == report_ii + and getattr(rep, "worker_id", None) == report_wid + ) + ), + None, + ) + if close_report: + self.open_reports.remove(close_report) + + def update_testcase_duration(self, report): + """accumulates total duration for nodeid from given report and updates + the Junit.testcase with the new total if already created. + """ + if self.report_duration == "total" or report.when == self.report_duration: + reporter = self.node_reporter(report) + reporter.duration += getattr(report, "duration", 0.0) + + def pytest_collectreport(self, report): + if not report.passed: + reporter = self._opentestcase(report) + if report.failed: + reporter.append_collect_error(report) + else: + reporter.append_collect_skipped(report) + + def pytest_internalerror(self, excrepr): + reporter = self.node_reporter("internal") + reporter.attrs.update(classname="pytest", name="internal") + reporter._add_simple(Junit.error, "internal error", excrepr) + + def pytest_sessionstart(self): + self.suite_start_time = time.time() + + def pytest_sessionfinish(self): + dirname = os.path.dirname(os.path.abspath(self.logfile)) + if not os.path.isdir(dirname): + os.makedirs(dirname) + logfile = open(self.logfile, "w", encoding="utf-8") + suite_stop_time = time.time() + suite_time_delta = suite_stop_time - self.suite_start_time + + numtests = ( + self.stats["passed"] + + self.stats["failure"] + + self.stats["skipped"] + + self.stats["error"] + - self.cnt_double_fail_tests + ) + logfile.write('') + + logfile.write( + Junit.testsuite( + self._get_global_properties_node(), + [x.to_xml() for x in self.node_reporters_ordered], + name=self.suite_name, + errors=self.stats["error"], + failures=self.stats["failure"], + skipped=self.stats["skipped"], + tests=numtests, + time="%.3f" % suite_time_delta, + ).unicode(indent=0) + ) + logfile.close() + + def pytest_terminal_summary(self, terminalreporter): + terminalreporter.write_sep("-", "generated xml file: %s" % (self.logfile)) + + def add_global_property(self, name, value): + __tracebackhide__ = True + _check_record_param_type("name", name) + self.global_properties.append((name, bin_xml_escape(value))) + + def _get_global_properties_node(self): + """Return a Junit node containing custom properties, if any. + """ + if self.global_properties: + return Junit.properties( + [ + Junit.property(name=name, value=value) + for name, value in self.global_properties + ] + ) + return "" diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/logging.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..2400737ee4e119e6b7350b715c2431e007f3413e --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/logging.py @@ -0,0 +1,708 @@ +# -*- coding: utf-8 -*- +""" Access and control log capturing. """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import logging +import re +from contextlib import contextmanager + +import py +import six + +import pytest +from _pytest.compat import dummy_context_manager +from _pytest.config import create_terminal_writer +from _pytest.pathlib import Path + +DEFAULT_LOG_FORMAT = "%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s" +DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S" +_ANSI_ESCAPE_SEQ = re.compile(r"\x1b\[[\d;]+m") + + +def _remove_ansi_escape_sequences(text): + return _ANSI_ESCAPE_SEQ.sub("", text) + + +class ColoredLevelFormatter(logging.Formatter): + """ + Colorize the %(levelname)..s part of the log format passed to __init__. + """ + + LOGLEVEL_COLOROPTS = { + logging.CRITICAL: {"red"}, + logging.ERROR: {"red", "bold"}, + logging.WARNING: {"yellow"}, + logging.WARN: {"yellow"}, + logging.INFO: {"green"}, + logging.DEBUG: {"purple"}, + logging.NOTSET: set(), + } + LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-]?\d*s)") + + def __init__(self, terminalwriter, *args, **kwargs): + super(ColoredLevelFormatter, self).__init__(*args, **kwargs) + if six.PY2: + self._original_fmt = self._fmt + else: + self._original_fmt = self._style._fmt + self._level_to_fmt_mapping = {} + + levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt) + if not levelname_fmt_match: + return + levelname_fmt = levelname_fmt_match.group() + + for level, color_opts in self.LOGLEVEL_COLOROPTS.items(): + formatted_levelname = levelname_fmt % { + "levelname": logging.getLevelName(level) + } + + # add ANSI escape sequences around the formatted levelname + color_kwargs = {name: True for name in color_opts} + colorized_formatted_levelname = terminalwriter.markup( + formatted_levelname, **color_kwargs + ) + self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub( + colorized_formatted_levelname, self._fmt + ) + + def format(self, record): + fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt) + if six.PY2: + self._fmt = fmt + else: + self._style._fmt = fmt + return super(ColoredLevelFormatter, self).format(record) + + +if not six.PY2: + # Formatter classes don't support format styles in PY2 + + class PercentStyleMultiline(logging.PercentStyle): + """A logging style with special support for multiline messages. + + If the message of a record consists of multiple lines, this style + formats the message as if each line were logged separately. + """ + + @staticmethod + def _update_message(record_dict, message): + tmp = record_dict.copy() + tmp["message"] = message + return tmp + + def format(self, record): + if "\n" in record.message: + lines = record.message.splitlines() + formatted = self._fmt % self._update_message(record.__dict__, lines[0]) + # TODO optimize this by introducing an option that tells the + # logging framework that the indentation doesn't + # change. This allows to compute the indentation only once. + indentation = _remove_ansi_escape_sequences(formatted).find(lines[0]) + lines[0] = formatted + return ("\n" + " " * indentation).join(lines) + else: + return self._fmt % record.__dict__ + + +def get_option_ini(config, *names): + for name in names: + ret = config.getoption(name) # 'default' arg won't work as expected + if ret is None: + ret = config.getini(name) + if ret: + return ret + + +def pytest_addoption(parser): + """Add options to control log capturing.""" + group = parser.getgroup("logging") + + def add_option_ini(option, dest, default=None, type=None, **kwargs): + parser.addini( + dest, default=default, type=type, help="default value for " + option + ) + group.addoption(option, dest=dest, **kwargs) + + add_option_ini( + "--no-print-logs", + dest="log_print", + action="store_const", + const=False, + default=True, + type="bool", + help="disable printing caught logs on failed tests.", + ) + add_option_ini( + "--log-level", + dest="log_level", + default=None, + help="logging level used by the logging module", + ) + add_option_ini( + "--log-format", + dest="log_format", + default=DEFAULT_LOG_FORMAT, + help="log format as used by the logging module.", + ) + add_option_ini( + "--log-date-format", + dest="log_date_format", + default=DEFAULT_LOG_DATE_FORMAT, + help="log date format as used by the logging module.", + ) + parser.addini( + "log_cli", + default=False, + type="bool", + help='enable log display during test run (also known as "live logging").', + ) + add_option_ini( + "--log-cli-level", dest="log_cli_level", default=None, help="cli logging level." + ) + add_option_ini( + "--log-cli-format", + dest="log_cli_format", + default=None, + help="log format as used by the logging module.", + ) + add_option_ini( + "--log-cli-date-format", + dest="log_cli_date_format", + default=None, + help="log date format as used by the logging module.", + ) + add_option_ini( + "--log-file", + dest="log_file", + default=None, + help="path to a file when logging will be written to.", + ) + add_option_ini( + "--log-file-level", + dest="log_file_level", + default=None, + help="log file logging level.", + ) + add_option_ini( + "--log-file-format", + dest="log_file_format", + default=DEFAULT_LOG_FORMAT, + help="log format as used by the logging module.", + ) + add_option_ini( + "--log-file-date-format", + dest="log_file_date_format", + default=DEFAULT_LOG_DATE_FORMAT, + help="log date format as used by the logging module.", + ) + + +@contextmanager +def catching_logs(handler, formatter=None, level=None): + """Context manager that prepares the whole logging machinery properly.""" + root_logger = logging.getLogger() + + if formatter is not None: + handler.setFormatter(formatter) + if level is not None: + handler.setLevel(level) + + # Adding the same handler twice would confuse logging system. + # Just don't do that. + add_new_handler = handler not in root_logger.handlers + + if add_new_handler: + root_logger.addHandler(handler) + if level is not None: + orig_level = root_logger.level + root_logger.setLevel(min(orig_level, level)) + try: + yield handler + finally: + if level is not None: + root_logger.setLevel(orig_level) + if add_new_handler: + root_logger.removeHandler(handler) + + +class LogCaptureHandler(logging.StreamHandler): + """A logging handler that stores log records and the log text.""" + + def __init__(self): + """Creates a new log handler.""" + logging.StreamHandler.__init__(self, py.io.TextIO()) + self.records = [] + + def emit(self, record): + """Keep the log records in a list in addition to the log text.""" + self.records.append(record) + logging.StreamHandler.emit(self, record) + + def reset(self): + self.records = [] + self.stream = py.io.TextIO() + + +class LogCaptureFixture(object): + """Provides access and control of log capturing.""" + + def __init__(self, item): + """Creates a new funcarg.""" + self._item = item + # dict of log name -> log level + self._initial_log_levels = {} # Dict[str, int] + + def _finalize(self): + """Finalizes the fixture. + + This restores the log levels changed by :meth:`set_level`. + """ + # restore log levels + for logger_name, level in self._initial_log_levels.items(): + logger = logging.getLogger(logger_name) + logger.setLevel(level) + + @property + def handler(self): + """ + :rtype: LogCaptureHandler + """ + return self._item.catch_log_handler + + def get_records(self, when): + """ + Get the logging records for one of the possible test phases. + + :param str when: + Which test phase to obtain the records from. Valid values are: "setup", "call" and "teardown". + + :rtype: List[logging.LogRecord] + :return: the list of captured records at the given stage + + .. versionadded:: 3.4 + """ + handler = self._item.catch_log_handlers.get(when) + if handler: + return handler.records + else: + return [] + + @property + def text(self): + """Returns the formatted log text.""" + return _remove_ansi_escape_sequences(self.handler.stream.getvalue()) + + @property + def records(self): + """Returns the list of log records.""" + return self.handler.records + + @property + def record_tuples(self): + """Returns a list of a stripped down version of log records intended + for use in assertion comparison. + + The format of the tuple is: + + (logger_name, log_level, message) + """ + return [(r.name, r.levelno, r.getMessage()) for r in self.records] + + @property + def messages(self): + """Returns a list of format-interpolated log messages. + + Unlike 'records', which contains the format string and parameters for interpolation, log messages in this list + are all interpolated. + Unlike 'text', which contains the output from the handler, log messages in this list are unadorned with + levels, timestamps, etc, making exact comparisons more reliable. + + Note that traceback or stack info (from :func:`logging.exception` or the `exc_info` or `stack_info` arguments + to the logging functions) is not included, as this is added by the formatter in the handler. + + .. versionadded:: 3.7 + """ + return [r.getMessage() for r in self.records] + + def clear(self): + """Reset the list of log records and the captured log text.""" + self.handler.reset() + + def set_level(self, level, logger=None): + """Sets the level for capturing of logs. The level will be restored to its previous value at the end of + the test. + + :param int level: the logger to level. + :param str logger: the logger to update the level. If not given, the root logger level is updated. + + .. versionchanged:: 3.4 + The levels of the loggers changed by this function will be restored to their initial values at the + end of the test. + """ + logger_name = logger + logger = logging.getLogger(logger_name) + # save the original log-level to restore it during teardown + self._initial_log_levels.setdefault(logger_name, logger.level) + logger.setLevel(level) + + @contextmanager + def at_level(self, level, logger=None): + """Context manager that sets the level for capturing of logs. After the end of the 'with' statement the + level is restored to its original value. + + :param int level: the logger to level. + :param str logger: the logger to update the level. If not given, the root logger level is updated. + """ + logger = logging.getLogger(logger) + orig_level = logger.level + logger.setLevel(level) + try: + yield + finally: + logger.setLevel(orig_level) + + +@pytest.fixture +def caplog(request): + """Access and control log capturing. + + Captured logs are available through the following properties/methods:: + + * caplog.text -> string containing formatted log output + * caplog.records -> list of logging.LogRecord instances + * caplog.record_tuples -> list of (logger_name, level, message) tuples + * caplog.clear() -> clear captured records and formatted log output string + """ + result = LogCaptureFixture(request.node) + yield result + result._finalize() + + +def get_actual_log_level(config, *setting_names): + """Return the actual logging level.""" + + for setting_name in setting_names: + log_level = config.getoption(setting_name) + if log_level is None: + log_level = config.getini(setting_name) + if log_level: + break + else: + return + + if isinstance(log_level, six.string_types): + log_level = log_level.upper() + try: + return int(getattr(logging, log_level, log_level)) + except ValueError: + # Python logging does not recognise this as a logging level + raise pytest.UsageError( + "'{}' is not recognized as a logging level name for " + "'{}'. Please consider passing the " + "logging level num instead.".format(log_level, setting_name) + ) + + +# run after terminalreporter/capturemanager are configured +@pytest.hookimpl(trylast=True) +def pytest_configure(config): + config.pluginmanager.register(LoggingPlugin(config), "logging-plugin") + + +class LoggingPlugin(object): + """Attaches to the logging module and captures log messages for each test. + """ + + def __init__(self, config): + """Creates a new plugin to capture log messages. + + The formatter can be safely shared across all handlers so + create a single one for the entire test session here. + """ + self._config = config + + self.print_logs = get_option_ini(config, "log_print") + self.formatter = self._create_formatter( + get_option_ini(config, "log_format"), + get_option_ini(config, "log_date_format"), + ) + self.log_level = get_actual_log_level(config, "log_level") + + self.log_file_level = get_actual_log_level(config, "log_file_level") + self.log_file_format = get_option_ini(config, "log_file_format", "log_format") + self.log_file_date_format = get_option_ini( + config, "log_file_date_format", "log_date_format" + ) + self.log_file_formatter = logging.Formatter( + self.log_file_format, datefmt=self.log_file_date_format + ) + + log_file = get_option_ini(config, "log_file") + if log_file: + self.log_file_handler = logging.FileHandler( + log_file, mode="w", encoding="UTF-8" + ) + self.log_file_handler.setFormatter(self.log_file_formatter) + else: + self.log_file_handler = None + + self.log_cli_handler = None + + self.live_logs_context = lambda: dummy_context_manager() + # Note that the lambda for the live_logs_context is needed because + # live_logs_context can otherwise not be entered multiple times due + # to limitations of contextlib.contextmanager. + + if self._log_cli_enabled(): + self._setup_cli_logging() + + def _create_formatter(self, log_format, log_date_format): + # color option doesn't exist if terminal plugin is disabled + color = getattr(self._config.option, "color", "no") + if color != "no" and ColoredLevelFormatter.LEVELNAME_FMT_REGEX.search( + log_format + ): + formatter = ColoredLevelFormatter( + create_terminal_writer(self._config), log_format, log_date_format + ) + else: + formatter = logging.Formatter(log_format, log_date_format) + + if not six.PY2: + formatter._style = PercentStyleMultiline(formatter._style._fmt) + return formatter + + def _setup_cli_logging(self): + config = self._config + terminal_reporter = config.pluginmanager.get_plugin("terminalreporter") + if terminal_reporter is None: + # terminal reporter is disabled e.g. by pytest-xdist. + return + + capture_manager = config.pluginmanager.get_plugin("capturemanager") + # if capturemanager plugin is disabled, live logging still works. + log_cli_handler = _LiveLoggingStreamHandler(terminal_reporter, capture_manager) + + log_cli_formatter = self._create_formatter( + get_option_ini(config, "log_cli_format", "log_format"), + get_option_ini(config, "log_cli_date_format", "log_date_format"), + ) + + log_cli_level = get_actual_log_level(config, "log_cli_level", "log_level") + self.log_cli_handler = log_cli_handler + self.live_logs_context = lambda: catching_logs( + log_cli_handler, formatter=log_cli_formatter, level=log_cli_level + ) + + def set_log_path(self, fname): + """Public method, which can set filename parameter for + Logging.FileHandler(). Also creates parent directory if + it does not exist. + + .. warning:: + Please considered as an experimental API. + """ + fname = Path(fname) + + if not fname.is_absolute(): + fname = Path(self._config.rootdir, fname) + + if not fname.parent.exists(): + fname.parent.mkdir(exist_ok=True, parents=True) + + self.log_file_handler = logging.FileHandler( + str(fname), mode="w", encoding="UTF-8" + ) + self.log_file_handler.setFormatter(self.log_file_formatter) + + def _log_cli_enabled(self): + """Return True if log_cli should be considered enabled, either explicitly + or because --log-cli-level was given in the command-line. + """ + return self._config.getoption( + "--log-cli-level" + ) is not None or self._config.getini("log_cli") + + @pytest.hookimpl(hookwrapper=True, tryfirst=True) + def pytest_collection(self): + with self.live_logs_context(): + if self.log_cli_handler: + self.log_cli_handler.set_when("collection") + + if self.log_file_handler is not None: + with catching_logs(self.log_file_handler, level=self.log_file_level): + yield + else: + yield + + @contextmanager + def _runtest_for(self, item, when): + with self._runtest_for_main(item, when): + if self.log_file_handler is not None: + with catching_logs(self.log_file_handler, level=self.log_file_level): + yield + else: + yield + + @contextmanager + def _runtest_for_main(self, item, when): + """Implements the internals of pytest_runtest_xxx() hook.""" + with catching_logs( + LogCaptureHandler(), formatter=self.formatter, level=self.log_level + ) as log_handler: + if self.log_cli_handler: + self.log_cli_handler.set_when(when) + + if item is None: + yield # run the test + return + + if not hasattr(item, "catch_log_handlers"): + item.catch_log_handlers = {} + item.catch_log_handlers[when] = log_handler + item.catch_log_handler = log_handler + try: + yield # run test + finally: + if when == "teardown": + del item.catch_log_handler + del item.catch_log_handlers + + if self.print_logs: + # Add a captured log section to the report. + log = log_handler.stream.getvalue().strip() + item.add_report_section(when, "log", log) + + @pytest.hookimpl(hookwrapper=True) + def pytest_runtest_setup(self, item): + with self._runtest_for(item, "setup"): + yield + + @pytest.hookimpl(hookwrapper=True) + def pytest_runtest_call(self, item): + with self._runtest_for(item, "call"): + yield + + @pytest.hookimpl(hookwrapper=True) + def pytest_runtest_teardown(self, item): + with self._runtest_for(item, "teardown"): + yield + + @pytest.hookimpl(hookwrapper=True) + def pytest_runtest_logstart(self): + if self.log_cli_handler: + self.log_cli_handler.reset() + with self._runtest_for(None, "start"): + yield + + @pytest.hookimpl(hookwrapper=True) + def pytest_runtest_logfinish(self): + with self._runtest_for(None, "finish"): + yield + + @pytest.hookimpl(hookwrapper=True) + def pytest_runtest_logreport(self): + with self._runtest_for(None, "logreport"): + yield + + @pytest.hookimpl(hookwrapper=True, tryfirst=True) + def pytest_sessionfinish(self): + with self.live_logs_context(): + if self.log_cli_handler: + self.log_cli_handler.set_when("sessionfinish") + if self.log_file_handler is not None: + try: + with catching_logs( + self.log_file_handler, level=self.log_file_level + ): + yield + finally: + # Close the FileHandler explicitly. + # (logging.shutdown might have lost the weakref?!) + self.log_file_handler.close() + else: + yield + + @pytest.hookimpl(hookwrapper=True, tryfirst=True) + def pytest_sessionstart(self): + with self.live_logs_context(): + if self.log_cli_handler: + self.log_cli_handler.set_when("sessionstart") + if self.log_file_handler is not None: + with catching_logs(self.log_file_handler, level=self.log_file_level): + yield + else: + yield + + @pytest.hookimpl(hookwrapper=True) + def pytest_runtestloop(self, session): + """Runs all collected test items.""" + + if session.config.option.collectonly: + yield + return + + if self._log_cli_enabled() and self._config.getoption("verbose") < 1: + # setting verbose flag is needed to avoid messy test progress output + self._config.option.verbose = 1 + + with self.live_logs_context(): + if self.log_file_handler is not None: + with catching_logs(self.log_file_handler, level=self.log_file_level): + yield # run all the tests + else: + yield # run all the tests + + +class _LiveLoggingStreamHandler(logging.StreamHandler): + """ + Custom StreamHandler used by the live logging feature: it will write a newline before the first log message + in each test. + + During live logging we must also explicitly disable stdout/stderr capturing otherwise it will get captured + and won't appear in the terminal. + """ + + def __init__(self, terminal_reporter, capture_manager): + """ + :param _pytest.terminal.TerminalReporter terminal_reporter: + :param _pytest.capture.CaptureManager capture_manager: + """ + logging.StreamHandler.__init__(self, stream=terminal_reporter) + self.capture_manager = capture_manager + self.reset() + self.set_when(None) + self._test_outcome_written = False + + def reset(self): + """Reset the handler; should be called before the start of each test""" + self._first_record_emitted = False + + def set_when(self, when): + """Prepares for the given test phase (setup/call/teardown)""" + self._when = when + self._section_name_shown = False + if when == "start": + self._test_outcome_written = False + + def emit(self, record): + ctx_manager = ( + self.capture_manager.global_and_fixture_disabled() + if self.capture_manager + else dummy_context_manager() + ) + with ctx_manager: + if not self._first_record_emitted: + self.stream.write("\n") + self._first_record_emitted = True + elif self._when in ("teardown", "finish"): + if not self._test_outcome_written: + self._test_outcome_written = True + self.stream.write("\n") + if not self._section_name_shown and self._when: + self.stream.section("live log " + self._when, sep="-", bold=True) + self._section_name_shown = True + logging.StreamHandler.emit(self, record) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/main.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/main.py new file mode 100644 index 0000000000000000000000000000000000000000..a9d310cb62d9f253784f1932a927a9996bfe4668 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/main.py @@ -0,0 +1,780 @@ +# -*- coding: utf-8 -*- +""" core implementation of testing process: init, session, runtest loop. """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import contextlib +import fnmatch +import functools +import os +import pkgutil +import sys +import warnings + +import attr +import py +import six + +import _pytest._code +from _pytest import nodes +from _pytest.config import directory_arg +from _pytest.config import hookimpl +from _pytest.config import UsageError +from _pytest.deprecated import PYTEST_CONFIG_GLOBAL +from _pytest.outcomes import exit +from _pytest.runner import collect_one_node + +# exitcodes for the command line +EXIT_OK = 0 +EXIT_TESTSFAILED = 1 +EXIT_INTERRUPTED = 2 +EXIT_INTERNALERROR = 3 +EXIT_USAGEERROR = 4 +EXIT_NOTESTSCOLLECTED = 5 + + +def pytest_addoption(parser): + parser.addini( + "norecursedirs", + "directory patterns to avoid for recursion", + type="args", + default=[".*", "build", "dist", "CVS", "_darcs", "{arch}", "*.egg", "venv"], + ) + parser.addini( + "testpaths", + "directories to search for tests when no files or directories are given in the " + "command line.", + type="args", + default=[], + ) + group = parser.getgroup("general", "running and selection options") + group._addoption( + "-x", + "--exitfirst", + action="store_const", + dest="maxfail", + const=1, + help="exit instantly on first error or failed test.", + ), + group._addoption( + "--maxfail", + metavar="num", + action="store", + type=int, + dest="maxfail", + default=0, + help="exit after first num failures or errors.", + ) + group._addoption( + "--strict-markers", + "--strict", + action="store_true", + help="markers not registered in the `markers` section of the configuration file raise errors.", + ) + group._addoption( + "-c", + metavar="file", + type=str, + dest="inifilename", + help="load configuration from `file` instead of trying to locate one of the implicit " + "configuration files.", + ) + group._addoption( + "--continue-on-collection-errors", + action="store_true", + default=False, + dest="continue_on_collection_errors", + help="Force test execution even if collection errors occur.", + ) + group._addoption( + "--rootdir", + action="store", + dest="rootdir", + help="Define root directory for tests. Can be relative path: 'root_dir', './root_dir', " + "'root_dir/another_dir/'; absolute path: '/home/user/root_dir'; path with variables: " + "'$HOME/root_dir'.", + ) + + group = parser.getgroup("collect", "collection") + group.addoption( + "--collectonly", + "--collect-only", + action="store_true", + help="only collect tests, don't execute them.", + ), + group.addoption( + "--pyargs", + action="store_true", + help="try to interpret all arguments as python packages.", + ) + group.addoption( + "--ignore", + action="append", + metavar="path", + help="ignore path during collection (multi-allowed).", + ) + group.addoption( + "--ignore-glob", + action="append", + metavar="path", + help="ignore path pattern during collection (multi-allowed).", + ) + group.addoption( + "--deselect", + action="append", + metavar="nodeid_prefix", + help="deselect item during collection (multi-allowed).", + ) + # when changing this to --conf-cut-dir, config.py Conftest.setinitial + # needs upgrading as well + group.addoption( + "--confcutdir", + dest="confcutdir", + default=None, + metavar="dir", + type=functools.partial(directory_arg, optname="--confcutdir"), + help="only load conftest.py's relative to specified dir.", + ) + group.addoption( + "--noconftest", + action="store_true", + dest="noconftest", + default=False, + help="Don't load any conftest.py files.", + ) + group.addoption( + "--keepduplicates", + "--keep-duplicates", + action="store_true", + dest="keepduplicates", + default=False, + help="Keep duplicate tests.", + ) + group.addoption( + "--collect-in-virtualenv", + action="store_true", + dest="collect_in_virtualenv", + default=False, + help="Don't ignore tests in a local virtualenv directory", + ) + + group = parser.getgroup("debugconfig", "test session debugging and configuration") + group.addoption( + "--basetemp", + dest="basetemp", + default=None, + metavar="dir", + help=( + "base temporary directory for this test run." + "(warning: this directory is removed if it exists)" + ), + ) + + +class _ConfigDeprecated(object): + def __init__(self, config): + self.__dict__["_config"] = config + + def __getattr__(self, attr): + warnings.warn(PYTEST_CONFIG_GLOBAL, stacklevel=2) + return getattr(self._config, attr) + + def __setattr__(self, attr, val): + warnings.warn(PYTEST_CONFIG_GLOBAL, stacklevel=2) + return setattr(self._config, attr, val) + + def __repr__(self): + return "{}({!r})".format(type(self).__name__, self._config) + + +def pytest_configure(config): + __import__("pytest").config = _ConfigDeprecated(config) # compatibility + + +def wrap_session(config, doit): + """Skeleton command line program""" + session = Session(config) + session.exitstatus = EXIT_OK + initstate = 0 + try: + try: + config._do_configure() + initstate = 1 + config.hook.pytest_sessionstart(session=session) + initstate = 2 + session.exitstatus = doit(config, session) or 0 + except UsageError: + session.exitstatus = EXIT_USAGEERROR + raise + except Failed: + session.exitstatus = EXIT_TESTSFAILED + except (KeyboardInterrupt, exit.Exception): + excinfo = _pytest._code.ExceptionInfo.from_current() + exitstatus = EXIT_INTERRUPTED + if isinstance(excinfo.value, exit.Exception): + if excinfo.value.returncode is not None: + exitstatus = excinfo.value.returncode + if initstate < 2: + sys.stderr.write( + "{}: {}\n".format(excinfo.typename, excinfo.value.msg) + ) + config.hook.pytest_keyboard_interrupt(excinfo=excinfo) + session.exitstatus = exitstatus + except: # noqa + excinfo = _pytest._code.ExceptionInfo.from_current() + config.notify_exception(excinfo, config.option) + session.exitstatus = EXIT_INTERNALERROR + if excinfo.errisinstance(SystemExit): + sys.stderr.write("mainloop: caught unexpected SystemExit!\n") + + finally: + excinfo = None # Explicitly break reference cycle. + session.startdir.chdir() + if initstate >= 2: + config.hook.pytest_sessionfinish( + session=session, exitstatus=session.exitstatus + ) + config._ensure_unconfigure() + return session.exitstatus + + +def pytest_cmdline_main(config): + return wrap_session(config, _main) + + +def _main(config, session): + """ default command line protocol for initialization, session, + running tests and reporting. """ + config.hook.pytest_collection(session=session) + config.hook.pytest_runtestloop(session=session) + + if session.testsfailed: + return EXIT_TESTSFAILED + elif session.testscollected == 0: + return EXIT_NOTESTSCOLLECTED + + +def pytest_collection(session): + return session.perform_collect() + + +def pytest_runtestloop(session): + if session.testsfailed and not session.config.option.continue_on_collection_errors: + raise session.Interrupted("%d errors during collection" % session.testsfailed) + + if session.config.option.collectonly: + return True + + for i, item in enumerate(session.items): + nextitem = session.items[i + 1] if i + 1 < len(session.items) else None + item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem) + if session.shouldfail: + raise session.Failed(session.shouldfail) + if session.shouldstop: + raise session.Interrupted(session.shouldstop) + return True + + +def _in_venv(path): + """Attempts to detect if ``path`` is the root of a Virtual Environment by + checking for the existence of the appropriate activate script""" + bindir = path.join("Scripts" if sys.platform.startswith("win") else "bin") + if not bindir.isdir(): + return False + activates = ( + "activate", + "activate.csh", + "activate.fish", + "Activate", + "Activate.bat", + "Activate.ps1", + ) + return any([fname.basename in activates for fname in bindir.listdir()]) + + +def pytest_ignore_collect(path, config): + ignore_paths = config._getconftest_pathlist("collect_ignore", path=path.dirpath()) + ignore_paths = ignore_paths or [] + excludeopt = config.getoption("ignore") + if excludeopt: + ignore_paths.extend([py.path.local(x) for x in excludeopt]) + + if py.path.local(path) in ignore_paths: + return True + + ignore_globs = config._getconftest_pathlist( + "collect_ignore_glob", path=path.dirpath() + ) + ignore_globs = ignore_globs or [] + excludeglobopt = config.getoption("ignore_glob") + if excludeglobopt: + ignore_globs.extend([py.path.local(x) for x in excludeglobopt]) + + if any( + fnmatch.fnmatch(six.text_type(path), six.text_type(glob)) + for glob in ignore_globs + ): + return True + + allow_in_venv = config.getoption("collect_in_virtualenv") + if not allow_in_venv and _in_venv(path): + return True + + return False + + +def pytest_collection_modifyitems(items, config): + deselect_prefixes = tuple(config.getoption("deselect") or []) + if not deselect_prefixes: + return + + remaining = [] + deselected = [] + for colitem in items: + if colitem.nodeid.startswith(deselect_prefixes): + deselected.append(colitem) + else: + remaining.append(colitem) + + if deselected: + config.hook.pytest_deselected(items=deselected) + items[:] = remaining + + +@contextlib.contextmanager +def _patched_find_module(): + """Patch bug in pkgutil.ImpImporter.find_module + + When using pkgutil.find_loader on python<3.4 it removes symlinks + from the path due to a call to os.path.realpath. This is not consistent + with actually doing the import (in these versions, pkgutil and __import__ + did not share the same underlying code). This can break conftest + discovery for pytest where symlinks are involved. + + The only supported python<3.4 by pytest is python 2.7. + """ + if six.PY2: # python 3.4+ uses importlib instead + + def find_module_patched(self, fullname, path=None): + # Note: we ignore 'path' argument since it is only used via meta_path + subname = fullname.split(".")[-1] + if subname != fullname and self.path is None: + return None + if self.path is None: + path = None + else: + # original: path = [os.path.realpath(self.path)] + path = [self.path] + try: + file, filename, etc = pkgutil.imp.find_module(subname, path) + except ImportError: + return None + return pkgutil.ImpLoader(fullname, file, filename, etc) + + old_find_module = pkgutil.ImpImporter.find_module + pkgutil.ImpImporter.find_module = find_module_patched + try: + yield + finally: + pkgutil.ImpImporter.find_module = old_find_module + else: + yield + + +class FSHookProxy(object): + def __init__(self, fspath, pm, remove_mods): + self.fspath = fspath + self.pm = pm + self.remove_mods = remove_mods + + def __getattr__(self, name): + x = self.pm.subset_hook_caller(name, remove_plugins=self.remove_mods) + self.__dict__[name] = x + return x + + +class NoMatch(Exception): + """ raised if matching cannot locate a matching names. """ + + +class Interrupted(KeyboardInterrupt): + """ signals an interrupted test run. """ + + __module__ = "builtins" # for py3 + + +class Failed(Exception): + """ signals a stop as failed test run. """ + + +@attr.s +class _bestrelpath_cache(dict): + path = attr.ib() + + def __missing__(self, path): + r = self.path.bestrelpath(path) + self[path] = r + return r + + +class Session(nodes.FSCollector): + Interrupted = Interrupted + Failed = Failed + + def __init__(self, config): + nodes.FSCollector.__init__( + self, config.rootdir, parent=None, config=config, session=self, nodeid="" + ) + self.testsfailed = 0 + self.testscollected = 0 + self.shouldstop = False + self.shouldfail = False + self.trace = config.trace.root.get("collection") + self._norecursepatterns = config.getini("norecursedirs") + self.startdir = config.invocation_dir + self._initialpaths = frozenset() + # Keep track of any collected nodes in here, so we don't duplicate fixtures + self._node_cache = {} + self._bestrelpathcache = _bestrelpath_cache(config.rootdir) + # Dirnames of pkgs with dunder-init files. + self._pkg_roots = {} + + self.config.pluginmanager.register(self, name="session") + + def __repr__(self): + return "<%s %s exitstatus=%r testsfailed=%d testscollected=%d>" % ( + self.__class__.__name__, + self.name, + getattr(self, "exitstatus", ""), + self.testsfailed, + self.testscollected, + ) + + def _node_location_to_relpath(self, node_path): + # bestrelpath is a quite slow function + return self._bestrelpathcache[node_path] + + @hookimpl(tryfirst=True) + def pytest_collectstart(self): + if self.shouldfail: + raise self.Failed(self.shouldfail) + if self.shouldstop: + raise self.Interrupted(self.shouldstop) + + @hookimpl(tryfirst=True) + def pytest_runtest_logreport(self, report): + if report.failed and not hasattr(report, "wasxfail"): + self.testsfailed += 1 + maxfail = self.config.getvalue("maxfail") + if maxfail and self.testsfailed >= maxfail: + self.shouldfail = "stopping after %d failures" % (self.testsfailed) + + pytest_collectreport = pytest_runtest_logreport + + def isinitpath(self, path): + return path in self._initialpaths + + def gethookproxy(self, fspath): + # check if we have the common case of running + # hooks with all conftest.py files + pm = self.config.pluginmanager + my_conftestmodules = pm._getconftestmodules(fspath) + remove_mods = pm._conftest_plugins.difference(my_conftestmodules) + if remove_mods: + # one or more conftests are not in use at this fspath + proxy = FSHookProxy(fspath, pm, remove_mods) + else: + # all plugis are active for this fspath + proxy = self.config.hook + return proxy + + def perform_collect(self, args=None, genitems=True): + hook = self.config.hook + try: + items = self._perform_collect(args, genitems) + self.config.pluginmanager.check_pending() + hook.pytest_collection_modifyitems( + session=self, config=self.config, items=items + ) + finally: + hook.pytest_collection_finish(session=self) + self.testscollected = len(items) + return items + + def _perform_collect(self, args, genitems): + if args is None: + args = self.config.args + self.trace("perform_collect", self, args) + self.trace.root.indent += 1 + self._notfound = [] + initialpaths = [] + self._initialparts = [] + self.items = items = [] + for arg in args: + parts = self._parsearg(arg) + self._initialparts.append(parts) + initialpaths.append(parts[0]) + self._initialpaths = frozenset(initialpaths) + rep = collect_one_node(self) + self.ihook.pytest_collectreport(report=rep) + self.trace.root.indent -= 1 + if self._notfound: + errors = [] + for arg, exc in self._notfound: + line = "(no name %r in any of %r)" % (arg, exc.args[0]) + errors.append("not found: %s\n%s" % (arg, line)) + # XXX: test this + raise UsageError(*errors) + if not genitems: + return rep.result + else: + if rep.passed: + for node in rep.result: + self.items.extend(self.genitems(node)) + return items + + def collect(self): + for initialpart in self._initialparts: + arg = "::".join(map(str, initialpart)) + self.trace("processing argument", arg) + self.trace.root.indent += 1 + try: + for x in self._collect(arg): + yield x + except NoMatch: + # we are inside a make_report hook so + # we cannot directly pass through the exception + self._notfound.append((arg, sys.exc_info()[1])) + + self.trace.root.indent -= 1 + + def _collect(self, arg): + from _pytest.python import Package + + names = self._parsearg(arg) + argpath = names.pop(0) + + # Start with a Session root, and delve to argpath item (dir or file) + # and stack all Packages found on the way. + # No point in finding packages when collecting doctests + if not self.config.getoption("doctestmodules", False): + pm = self.config.pluginmanager + for parent in reversed(argpath.parts()): + if pm._confcutdir and pm._confcutdir.relto(parent): + break + + if parent.isdir(): + pkginit = parent.join("__init__.py") + if pkginit.isfile(): + if pkginit not in self._node_cache: + col = self._collectfile(pkginit, handle_dupes=False) + if col: + if isinstance(col[0], Package): + self._pkg_roots[parent] = col[0] + # always store a list in the cache, matchnodes expects it + self._node_cache[col[0].fspath] = [col[0]] + + # If it's a directory argument, recurse and look for any Subpackages. + # Let the Package collector deal with subnodes, don't collect here. + if argpath.check(dir=1): + assert not names, "invalid arg %r" % (arg,) + + seen_dirs = set() + for path in argpath.visit( + fil=self._visit_filter, rec=self._recurse, bf=True, sort=True + ): + dirpath = path.dirpath() + if dirpath not in seen_dirs: + # Collect packages first. + seen_dirs.add(dirpath) + pkginit = dirpath.join("__init__.py") + if pkginit.exists(): + for x in self._collectfile(pkginit): + yield x + if isinstance(x, Package): + self._pkg_roots[dirpath] = x + if dirpath in self._pkg_roots: + # Do not collect packages here. + continue + + for x in self._collectfile(path): + key = (type(x), x.fspath) + if key in self._node_cache: + yield self._node_cache[key] + else: + self._node_cache[key] = x + yield x + else: + assert argpath.check(file=1) + + if argpath in self._node_cache: + col = self._node_cache[argpath] + else: + collect_root = self._pkg_roots.get(argpath.dirname, self) + col = collect_root._collectfile(argpath, handle_dupes=False) + if col: + self._node_cache[argpath] = col + m = self.matchnodes(col, names) + # If __init__.py was the only file requested, then the matched node will be + # the corresponding Package, and the first yielded item will be the __init__ + # Module itself, so just use that. If this special case isn't taken, then all + # the files in the package will be yielded. + if argpath.basename == "__init__.py": + try: + yield next(m[0].collect()) + except StopIteration: + # The package collects nothing with only an __init__.py + # file in it, which gets ignored by the default + # "python_files" option. + pass + return + for y in m: + yield y + + def _collectfile(self, path, handle_dupes=True): + assert path.isfile(), "%r is not a file (isdir=%r, exists=%r, islink=%r)" % ( + path, + path.isdir(), + path.exists(), + path.islink(), + ) + ihook = self.gethookproxy(path) + if not self.isinitpath(path): + if ihook.pytest_ignore_collect(path=path, config=self.config): + return () + + if handle_dupes: + keepduplicates = self.config.getoption("keepduplicates") + if not keepduplicates: + duplicate_paths = self.config.pluginmanager._duplicatepaths + if path in duplicate_paths: + return () + else: + duplicate_paths.add(path) + + return ihook.pytest_collect_file(path=path, parent=self) + + def _recurse(self, dirpath): + if dirpath.basename == "__pycache__": + return False + ihook = self.gethookproxy(dirpath.dirpath()) + if ihook.pytest_ignore_collect(path=dirpath, config=self.config): + return False + for pat in self._norecursepatterns: + if dirpath.check(fnmatch=pat): + return False + ihook = self.gethookproxy(dirpath) + ihook.pytest_collect_directory(path=dirpath, parent=self) + return True + + if six.PY2: + + @staticmethod + def _visit_filter(f): + return f.check(file=1) and not f.strpath.endswith("*.pyc") + + else: + + @staticmethod + def _visit_filter(f): + return f.check(file=1) + + def _tryconvertpyarg(self, x): + """Convert a dotted module name to path.""" + try: + with _patched_find_module(): + loader = pkgutil.find_loader(x) + except ImportError: + return x + if loader is None: + return x + # This method is sometimes invoked when AssertionRewritingHook, which + # does not define a get_filename method, is already in place: + try: + with _patched_find_module(): + path = loader.get_filename(x) + except AttributeError: + # Retrieve path from AssertionRewritingHook: + path = loader.modules[x][0].co_filename + if loader.is_package(x): + path = os.path.dirname(path) + return path + + def _parsearg(self, arg): + """ return (fspath, names) tuple after checking the file exists. """ + parts = str(arg).split("::") + if self.config.option.pyargs: + parts[0] = self._tryconvertpyarg(parts[0]) + relpath = parts[0].replace("/", os.sep) + path = self.config.invocation_dir.join(relpath, abs=True) + if not path.check(): + if self.config.option.pyargs: + raise UsageError( + "file or package not found: " + arg + " (missing __init__.py?)" + ) + raise UsageError("file not found: " + arg) + parts[0] = path.realpath() + return parts + + def matchnodes(self, matching, names): + self.trace("matchnodes", matching, names) + self.trace.root.indent += 1 + nodes = self._matchnodes(matching, names) + num = len(nodes) + self.trace("matchnodes finished -> ", num, "nodes") + self.trace.root.indent -= 1 + if num == 0: + raise NoMatch(matching, names[:1]) + return nodes + + def _matchnodes(self, matching, names): + if not matching or not names: + return matching + name = names[0] + assert name + nextnames = names[1:] + resultnodes = [] + for node in matching: + if isinstance(node, nodes.Item): + if not names: + resultnodes.append(node) + continue + assert isinstance(node, nodes.Collector) + key = (type(node), node.nodeid) + if key in self._node_cache: + rep = self._node_cache[key] + else: + rep = collect_one_node(node) + self._node_cache[key] = rep + if rep.passed: + has_matched = False + for x in rep.result: + # TODO: remove parametrized workaround once collection structure contains parametrization + if x.name == name or x.name.split("[")[0] == name: + resultnodes.extend(self.matchnodes([x], nextnames)) + has_matched = True + # XXX accept IDs that don't have "()" for class instances + if not has_matched and len(rep.result) == 1 and x.name == "()": + nextnames.insert(0, name) + resultnodes.extend(self.matchnodes([x], nextnames)) + else: + # report collection failures here to avoid failing to run some test + # specified in the command line because the module could not be + # imported (#134) + node.ihook.pytest_collectreport(report=rep) + return resultnodes + + def genitems(self, node): + self.trace("genitems", node) + if isinstance(node, nodes.Item): + node.ihook.pytest_itemcollected(item=node) + yield node + else: + assert isinstance(node, nodes.Collector) + rep = collect_one_node(node) + if rep.passed: + for subnode in rep.result: + for x in self.genitems(subnode): + yield x + node.ihook.pytest_collectreport(report=rep) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/mark/__init__.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/mark/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6bc22fe27da96c38a347f3b49505c5e6b55e86db --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/mark/__init__.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +""" generic mechanism for marking and selecting python functions. """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from .legacy import matchkeyword +from .legacy import matchmark +from .structures import EMPTY_PARAMETERSET_OPTION +from .structures import get_empty_parameterset_mark +from .structures import Mark +from .structures import MARK_GEN +from .structures import MarkDecorator +from .structures import MarkGenerator +from .structures import ParameterSet +from _pytest.config import UsageError + +__all__ = ["Mark", "MarkDecorator", "MarkGenerator", "get_empty_parameterset_mark"] + + +def param(*values, **kw): + """Specify a parameter in `pytest.mark.parametrize`_ calls or + :ref:`parametrized fixtures `. + + .. code-block:: python + + @pytest.mark.parametrize("test_input,expected", [ + ("3+5", 8), + pytest.param("6*9", 42, marks=pytest.mark.xfail), + ]) + def test_eval(test_input, expected): + assert eval(test_input) == expected + + :param values: variable args of the values of the parameter set, in order. + :keyword marks: a single mark or a list of marks to be applied to this parameter set. + :keyword str id: the id to attribute to this parameter set. + """ + return ParameterSet.param(*values, **kw) + + +def pytest_addoption(parser): + group = parser.getgroup("general") + group._addoption( + "-k", + action="store", + dest="keyword", + default="", + metavar="EXPRESSION", + help="only run tests which match the given substring expression. " + "An expression is a python evaluatable expression " + "where all names are substring-matched against test names " + "and their parent classes. Example: -k 'test_method or test_" + "other' matches all test functions and classes whose name " + "contains 'test_method' or 'test_other', while -k 'not test_method' " + "matches those that don't contain 'test_method' in their names. " + "-k 'not test_method and not test_other' will eliminate the matches. " + "Additionally keywords are matched to classes and functions " + "containing extra names in their 'extra_keyword_matches' set, " + "as well as functions which have names assigned directly to them.", + ) + + group._addoption( + "-m", + action="store", + dest="markexpr", + default="", + metavar="MARKEXPR", + help="only run tests matching given mark expression. " + "example: -m 'mark1 and not mark2'.", + ) + + group.addoption( + "--markers", + action="store_true", + help="show markers (builtin, plugin and per-project ones).", + ) + + parser.addini("markers", "markers for test functions", "linelist") + parser.addini(EMPTY_PARAMETERSET_OPTION, "default marker for empty parametersets") + + +def pytest_cmdline_main(config): + import _pytest.config + + if config.option.markers: + config._do_configure() + tw = _pytest.config.create_terminal_writer(config) + for line in config.getini("markers"): + parts = line.split(":", 1) + name = parts[0] + rest = parts[1] if len(parts) == 2 else "" + tw.write("@pytest.mark.%s:" % name, bold=True) + tw.line(rest) + tw.line() + config._ensure_unconfigure() + return 0 + + +pytest_cmdline_main.tryfirst = True + + +def deselect_by_keyword(items, config): + keywordexpr = config.option.keyword.lstrip() + if not keywordexpr: + return + + if keywordexpr.startswith("-"): + keywordexpr = "not " + keywordexpr[1:] + selectuntil = False + if keywordexpr[-1:] == ":": + selectuntil = True + keywordexpr = keywordexpr[:-1] + + remaining = [] + deselected = [] + for colitem in items: + if keywordexpr and not matchkeyword(colitem, keywordexpr): + deselected.append(colitem) + else: + if selectuntil: + keywordexpr = None + remaining.append(colitem) + + if deselected: + config.hook.pytest_deselected(items=deselected) + items[:] = remaining + + +def deselect_by_mark(items, config): + matchexpr = config.option.markexpr + if not matchexpr: + return + + remaining = [] + deselected = [] + for item in items: + if matchmark(item, matchexpr): + remaining.append(item) + else: + deselected.append(item) + + if deselected: + config.hook.pytest_deselected(items=deselected) + items[:] = remaining + + +def pytest_collection_modifyitems(items, config): + deselect_by_keyword(items, config) + deselect_by_mark(items, config) + + +def pytest_configure(config): + config._old_mark_config = MARK_GEN._config + MARK_GEN._config = config + + empty_parameterset = config.getini(EMPTY_PARAMETERSET_OPTION) + + if empty_parameterset not in ("skip", "xfail", "fail_at_collect", None, ""): + raise UsageError( + "{!s} must be one of skip, xfail or fail_at_collect" + " but it is {!r}".format(EMPTY_PARAMETERSET_OPTION, empty_parameterset) + ) + + +def pytest_unconfigure(config): + MARK_GEN._config = getattr(config, "_old_mark_config", None) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/mark/evaluate.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/mark/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..506546e253a3b9fcd288febfe81ac73ad54ec517 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/mark/evaluate.py @@ -0,0 +1,126 @@ +# -*- coding: utf-8 -*- +import os +import platform +import sys +import traceback + +import six + +from ..outcomes import fail +from ..outcomes import TEST_OUTCOME + + +def cached_eval(config, expr, d): + if not hasattr(config, "_evalcache"): + config._evalcache = {} + try: + return config._evalcache[expr] + except KeyError: + import _pytest._code + + exprcode = _pytest._code.compile(expr, mode="eval") + config._evalcache[expr] = x = eval(exprcode, d) + return x + + +class MarkEvaluator(object): + def __init__(self, item, name): + self.item = item + self._marks = None + self._mark = None + self._mark_name = name + + def __bool__(self): + # dont cache here to prevent staleness + return bool(self._get_marks()) + + __nonzero__ = __bool__ + + def wasvalid(self): + return not hasattr(self, "exc") + + def _get_marks(self): + return list(self.item.iter_markers(name=self._mark_name)) + + def invalidraise(self, exc): + raises = self.get("raises") + if not raises: + return + return not isinstance(exc, raises) + + def istrue(self): + try: + return self._istrue() + except TEST_OUTCOME: + self.exc = sys.exc_info() + if isinstance(self.exc[1], SyntaxError): + msg = [" " * (self.exc[1].offset + 4) + "^"] + msg.append("SyntaxError: invalid syntax") + else: + msg = traceback.format_exception_only(*self.exc[:2]) + fail( + "Error evaluating %r expression\n" + " %s\n" + "%s" % (self._mark_name, self.expr, "\n".join(msg)), + pytrace=False, + ) + + def _getglobals(self): + d = {"os": os, "sys": sys, "platform": platform, "config": self.item.config} + if hasattr(self.item, "obj"): + d.update(self.item.obj.__globals__) + return d + + def _istrue(self): + if hasattr(self, "result"): + return self.result + self._marks = self._get_marks() + + if self._marks: + self.result = False + for mark in self._marks: + self._mark = mark + if "condition" in mark.kwargs: + args = (mark.kwargs["condition"],) + else: + args = mark.args + + for expr in args: + self.expr = expr + if isinstance(expr, six.string_types): + d = self._getglobals() + result = cached_eval(self.item.config, expr, d) + else: + if "reason" not in mark.kwargs: + # XXX better be checked at collection time + msg = ( + "you need to specify reason=STRING " + "when using booleans as conditions." + ) + fail(msg) + result = bool(expr) + if result: + self.result = True + self.reason = mark.kwargs.get("reason", None) + self.expr = expr + return self.result + + if not args: + self.result = True + self.reason = mark.kwargs.get("reason", None) + return self.result + return False + + def get(self, attr, default=None): + if self._mark is None: + return default + return self._mark.kwargs.get(attr, default) + + def getexplanation(self): + expl = getattr(self, "reason", None) or self.get("reason", None) + if not expl: + if not hasattr(self, "expr"): + return "" + else: + return "condition: " + str(self.expr) + return expl diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/mark/legacy.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/mark/legacy.py new file mode 100644 index 0000000000000000000000000000000000000000..c56482f14d0d9de71f29e67d9439ae68aa89195a --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/mark/legacy.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +""" +this is a place where we put datastructures used by legacy apis +we hope ot remove +""" +import keyword + +import attr + +from _pytest.config import UsageError + + +@attr.s +class MarkMapping(object): + """Provides a local mapping for markers where item access + resolves to True if the marker is present. """ + + own_mark_names = attr.ib() + + @classmethod + def from_item(cls, item): + mark_names = {mark.name for mark in item.iter_markers()} + return cls(mark_names) + + def __getitem__(self, name): + return name in self.own_mark_names + + +class KeywordMapping(object): + """Provides a local mapping for keywords. + Given a list of names, map any substring of one of these names to True. + """ + + def __init__(self, names): + self._names = names + + @classmethod + def from_item(cls, item): + mapped_names = set() + + # Add the names of the current item and any parent items + import pytest + + for item in item.listchain(): + if not isinstance(item, pytest.Instance): + mapped_names.add(item.name) + + # Add the names added as extra keywords to current or parent items + mapped_names.update(item.listextrakeywords()) + + # Add the names attached to the current function through direct assignment + if hasattr(item, "function"): + mapped_names.update(item.function.__dict__) + + # add the markers to the keywords as we no longer handle them correctly + mapped_names.update(mark.name for mark in item.iter_markers()) + + return cls(mapped_names) + + def __getitem__(self, subname): + for name in self._names: + if subname in name: + return True + return False + + +python_keywords_allowed_list = ["or", "and", "not"] + + +def matchmark(colitem, markexpr): + """Tries to match on any marker names, attached to the given colitem.""" + try: + return eval(markexpr, {}, MarkMapping.from_item(colitem)) + except SyntaxError as e: + raise SyntaxError(str(e) + "\nMarker expression must be valid Python!") + + +def matchkeyword(colitem, keywordexpr): + """Tries to match given keyword expression to given collector item. + + Will match on the name of colitem, including the names of its parents. + Only matches names of items which are either a :class:`Class` or a + :class:`Function`. + Additionally, matches on names in the 'extra_keyword_matches' set of + any item, as well as names directly assigned to test functions. + """ + mapping = KeywordMapping.from_item(colitem) + if " " not in keywordexpr: + # special case to allow for simple "-k pass" and "-k 1.3" + return mapping[keywordexpr] + elif keywordexpr.startswith("not ") and " " not in keywordexpr[4:]: + return not mapping[keywordexpr[4:]] + for kwd in keywordexpr.split(): + if keyword.iskeyword(kwd) and kwd not in python_keywords_allowed_list: + raise UsageError( + "Python keyword '{}' not accepted in expressions passed to '-k'".format( + kwd + ) + ) + try: + return eval(keywordexpr, {}, mapping) + except SyntaxError: + raise UsageError("Wrong expression passed to '-k': {}".format(keywordexpr)) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/mark/structures.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/mark/structures.py new file mode 100644 index 0000000000000000000000000000000000000000..bfbe71c2654210738c1971b8a85f924eb569fdfd --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/mark/structures.py @@ -0,0 +1,408 @@ +# -*- coding: utf-8 -*- +import inspect +import warnings +from collections import namedtuple +from operator import attrgetter + +import attr +import six + +from ..compat import ascii_escaped +from ..compat import getfslineno +from ..compat import MappingMixin +from ..compat import NOTSET +from _pytest.deprecated import PYTEST_PARAM_UNKNOWN_KWARGS +from _pytest.outcomes import fail +from _pytest.warning_types import PytestUnknownMarkWarning + +EMPTY_PARAMETERSET_OPTION = "empty_parameter_set_mark" + + +def alias(name, warning=None): + getter = attrgetter(name) + + def warned(self): + warnings.warn(warning, stacklevel=2) + return getter(self) + + return property(getter if warning is None else warned, doc="alias for " + name) + + +def istestfunc(func): + return ( + hasattr(func, "__call__") + and getattr(func, "__name__", "") != "" + ) + + +def get_empty_parameterset_mark(config, argnames, func): + from ..nodes import Collector + + requested_mark = config.getini(EMPTY_PARAMETERSET_OPTION) + if requested_mark in ("", None, "skip"): + mark = MARK_GEN.skip + elif requested_mark == "xfail": + mark = MARK_GEN.xfail(run=False) + elif requested_mark == "fail_at_collect": + f_name = func.__name__ + _, lineno = getfslineno(func) + raise Collector.CollectError( + "Empty parameter set in '%s' at line %d" % (f_name, lineno + 1) + ) + else: + raise LookupError(requested_mark) + fs, lineno = getfslineno(func) + reason = "got empty parameter set %r, function %s at %s:%d" % ( + argnames, + func.__name__, + fs, + lineno, + ) + return mark(reason=reason) + + +class ParameterSet(namedtuple("ParameterSet", "values, marks, id")): + @classmethod + def param(cls, *values, **kwargs): + marks = kwargs.pop("marks", ()) + if isinstance(marks, MarkDecorator): + marks = (marks,) + else: + assert isinstance(marks, (tuple, list, set)) + + id_ = kwargs.pop("id", None) + if id_ is not None: + if not isinstance(id_, six.string_types): + raise TypeError( + "Expected id to be a string, got {}: {!r}".format(type(id_), id_) + ) + id_ = ascii_escaped(id_) + + if kwargs: + warnings.warn( + PYTEST_PARAM_UNKNOWN_KWARGS.format(args=sorted(kwargs)), stacklevel=3 + ) + return cls(values, marks, id_) + + @classmethod + def extract_from(cls, parameterset, force_tuple=False): + """ + :param parameterset: + a legacy style parameterset that may or may not be a tuple, + and may or may not be wrapped into a mess of mark objects + + :param force_tuple: + enforce tuple wrapping so single argument tuple values + don't get decomposed and break tests + """ + + if isinstance(parameterset, cls): + return parameterset + if force_tuple: + return cls.param(parameterset) + else: + return cls(parameterset, marks=[], id=None) + + @staticmethod + def _parse_parametrize_args(argnames, argvalues, *args, **kwargs): + if not isinstance(argnames, (tuple, list)): + argnames = [x.strip() for x in argnames.split(",") if x.strip()] + force_tuple = len(argnames) == 1 + else: + force_tuple = False + return argnames, force_tuple + + @staticmethod + def _parse_parametrize_parameters(argvalues, force_tuple): + return [ + ParameterSet.extract_from(x, force_tuple=force_tuple) for x in argvalues + ] + + @classmethod + def _for_parametrize(cls, argnames, argvalues, func, config, function_definition): + argnames, force_tuple = cls._parse_parametrize_args(argnames, argvalues) + parameters = cls._parse_parametrize_parameters(argvalues, force_tuple) + del argvalues + + if parameters: + # check all parameter sets have the correct number of values + for param in parameters: + if len(param.values) != len(argnames): + msg = ( + '{nodeid}: in "parametrize" the number of names ({names_len}):\n' + " {names}\n" + "must be equal to the number of values ({values_len}):\n" + " {values}" + ) + fail( + msg.format( + nodeid=function_definition.nodeid, + values=param.values, + names=argnames, + names_len=len(argnames), + values_len=len(param.values), + ), + pytrace=False, + ) + else: + # empty parameter set (likely computed at runtime): create a single + # parameter set with NOTSET values, with the "empty parameter set" mark applied to it + mark = get_empty_parameterset_mark(config, argnames, func) + parameters.append( + ParameterSet(values=(NOTSET,) * len(argnames), marks=[mark], id=None) + ) + return argnames, parameters + + +@attr.s(frozen=True) +class Mark(object): + #: name of the mark + name = attr.ib(type=str) + #: positional arguments of the mark decorator + args = attr.ib() # List[object] + #: keyword arguments of the mark decorator + kwargs = attr.ib() # Dict[str, object] + + def combined_with(self, other): + """ + :param other: the mark to combine with + :type other: Mark + :rtype: Mark + + combines by appending args and merging the mappings + """ + assert self.name == other.name + return Mark( + self.name, self.args + other.args, dict(self.kwargs, **other.kwargs) + ) + + +@attr.s +class MarkDecorator(object): + """ A decorator for test functions and test classes. When applied + it will create :class:`MarkInfo` objects which may be + :ref:`retrieved by hooks as item keywords `. + MarkDecorator instances are often created like this:: + + mark1 = pytest.mark.NAME # simple MarkDecorator + mark2 = pytest.mark.NAME(name1=value) # parametrized MarkDecorator + + and can then be applied as decorators to test functions:: + + @mark2 + def test_function(): + pass + + When a MarkDecorator instance is called it does the following: + 1. If called with a single class as its only positional argument and no + additional keyword arguments, it attaches itself to the class so it + gets applied automatically to all test cases found in that class. + 2. If called with a single function as its only positional argument and + no additional keyword arguments, it attaches a MarkInfo object to the + function, containing all the arguments already stored internally in + the MarkDecorator. + 3. When called in any other case, it performs a 'fake construction' call, + i.e. it returns a new MarkDecorator instance with the original + MarkDecorator's content updated with the arguments passed to this + call. + + Note: The rules above prevent MarkDecorator objects from storing only a + single function or class reference as their positional argument with no + additional keyword or positional arguments. + + """ + + mark = attr.ib(validator=attr.validators.instance_of(Mark)) + + name = alias("mark.name") + args = alias("mark.args") + kwargs = alias("mark.kwargs") + + @property + def markname(self): + return self.name # for backward-compat (2.4.1 had this attr) + + def __eq__(self, other): + return self.mark == other.mark if isinstance(other, MarkDecorator) else False + + def __repr__(self): + return "" % (self.mark,) + + def with_args(self, *args, **kwargs): + """ return a MarkDecorator with extra arguments added + + unlike call this can be used even if the sole argument is a callable/class + + :return: MarkDecorator + """ + + mark = Mark(self.name, args, kwargs) + return self.__class__(self.mark.combined_with(mark)) + + def __call__(self, *args, **kwargs): + """ if passed a single callable argument: decorate it with mark info. + otherwise add *args/**kwargs in-place to mark information. """ + if args and not kwargs: + func = args[0] + is_class = inspect.isclass(func) + if len(args) == 1 and (istestfunc(func) or is_class): + store_mark(func, self.mark) + return func + return self.with_args(*args, **kwargs) + + +def get_unpacked_marks(obj): + """ + obtain the unpacked marks that are stored on an object + """ + mark_list = getattr(obj, "pytestmark", []) + if not isinstance(mark_list, list): + mark_list = [mark_list] + return normalize_mark_list(mark_list) + + +def normalize_mark_list(mark_list): + """ + normalizes marker decorating helpers to mark objects + + :type mark_list: List[Union[Mark, Markdecorator]] + :rtype: List[Mark] + """ + extracted = [ + getattr(mark, "mark", mark) for mark in mark_list + ] # unpack MarkDecorator + for mark in extracted: + if not isinstance(mark, Mark): + raise TypeError("got {!r} instead of Mark".format(mark)) + return [x for x in extracted if isinstance(x, Mark)] + + +def store_mark(obj, mark): + """store a Mark on an object + this is used to implement the Mark declarations/decorators correctly + """ + assert isinstance(mark, Mark), mark + # always reassign name to avoid updating pytestmark + # in a reference that was only borrowed + obj.pytestmark = get_unpacked_marks(obj) + [mark] + + +class MarkGenerator(object): + """ Factory for :class:`MarkDecorator` objects - exposed as + a ``pytest.mark`` singleton instance. Example:: + + import pytest + @pytest.mark.slowtest + def test_function(): + pass + + will set a 'slowtest' :class:`MarkInfo` object + on the ``test_function`` object. """ + + _config = None + _markers = set() + + def __getattr__(self, name): + if name[0] == "_": + raise AttributeError("Marker name must NOT start with underscore") + + if self._config is not None: + # We store a set of markers as a performance optimisation - if a mark + # name is in the set we definitely know it, but a mark may be known and + # not in the set. We therefore start by updating the set! + if name not in self._markers: + for line in self._config.getini("markers"): + # example lines: "skipif(condition): skip the given test if..." + # or "hypothesis: tests which use Hypothesis", so to get the + # marker name we split on both `:` and `(`. + marker = line.split(":")[0].split("(")[0].strip() + self._markers.add(marker) + + # If the name is not in the set of known marks after updating, + # then it really is time to issue a warning or an error. + if name not in self._markers: + if self._config.option.strict_markers: + fail( + "{!r} not found in `markers` configuration option".format(name), + pytrace=False, + ) + else: + warnings.warn( + "Unknown pytest.mark.%s - is this a typo? You can register " + "custom marks to avoid this warning - for details, see " + "https://docs.pytest.org/en/latest/mark.html" % name, + PytestUnknownMarkWarning, + ) + + return MarkDecorator(Mark(name, (), {})) + + +MARK_GEN = MarkGenerator() + + +class NodeKeywords(MappingMixin): + def __init__(self, node): + self.node = node + self.parent = node.parent + self._markers = {node.name: True} + + def __getitem__(self, key): + try: + return self._markers[key] + except KeyError: + if self.parent is None: + raise + return self.parent.keywords[key] + + def __setitem__(self, key, value): + self._markers[key] = value + + def __delitem__(self, key): + raise ValueError("cannot delete key in keywords dict") + + def __iter__(self): + seen = self._seen() + return iter(seen) + + def _seen(self): + seen = set(self._markers) + if self.parent is not None: + seen.update(self.parent.keywords) + return seen + + def __len__(self): + return len(self._seen()) + + def __repr__(self): + return "" % (self.node,) + + +@attr.s(cmp=False, hash=False) +class NodeMarkers(object): + """ + internal structure for storing marks belonging to a node + + ..warning:: + + unstable api + + """ + + own_markers = attr.ib(default=attr.Factory(list)) + + def update(self, add_markers): + """update the own markers + """ + self.own_markers.extend(add_markers) + + def find(self, name): + """ + find markers in own nodes or parent nodes + needs a better place + """ + for mark in self.own_markers: + if mark.name == name: + yield mark + + def __iter__(self): + return iter(self.own_markers) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/monkeypatch.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/monkeypatch.py new file mode 100644 index 0000000000000000000000000000000000000000..e8671b0c7024fcef48b3cd9ce558dc6d639cf64b --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/monkeypatch.py @@ -0,0 +1,336 @@ +# -*- coding: utf-8 -*- +""" monkeypatching and mocking functionality. """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import re +import sys +import warnings +from contextlib import contextmanager + +import six + +import pytest +from _pytest.fixtures import fixture +from _pytest.pathlib import Path + +RE_IMPORT_ERROR_NAME = re.compile(r"^No module named (.*)$") + + +@fixture +def monkeypatch(): + """The returned ``monkeypatch`` fixture provides these + helper methods to modify objects, dictionaries or os.environ:: + + monkeypatch.setattr(obj, name, value, raising=True) + monkeypatch.delattr(obj, name, raising=True) + monkeypatch.setitem(mapping, name, value) + monkeypatch.delitem(obj, name, raising=True) + monkeypatch.setenv(name, value, prepend=False) + monkeypatch.delenv(name, raising=True) + monkeypatch.syspath_prepend(path) + monkeypatch.chdir(path) + + All modifications will be undone after the requesting + test function or fixture has finished. The ``raising`` + parameter determines if a KeyError or AttributeError + will be raised if the set/deletion operation has no target. + """ + mpatch = MonkeyPatch() + yield mpatch + mpatch.undo() + + +def resolve(name): + # simplified from zope.dottedname + parts = name.split(".") + + used = parts.pop(0) + found = __import__(used) + for part in parts: + used += "." + part + try: + found = getattr(found, part) + except AttributeError: + pass + else: + continue + # we use explicit un-nesting of the handling block in order + # to avoid nested exceptions on python 3 + try: + __import__(used) + except ImportError as ex: + # str is used for py2 vs py3 + expected = str(ex).split()[-1] + if expected == used: + raise + else: + raise ImportError("import error in %s: %s" % (used, ex)) + found = annotated_getattr(found, part, used) + return found + + +def annotated_getattr(obj, name, ann): + try: + obj = getattr(obj, name) + except AttributeError: + raise AttributeError( + "%r object at %s has no attribute %r" % (type(obj).__name__, ann, name) + ) + return obj + + +def derive_importpath(import_path, raising): + if not isinstance(import_path, six.string_types) or "." not in import_path: + raise TypeError("must be absolute import path string, not %r" % (import_path,)) + module, attr = import_path.rsplit(".", 1) + target = resolve(module) + if raising: + annotated_getattr(target, attr, ann=module) + return attr, target + + +class Notset(object): + def __repr__(self): + return "" + + +notset = Notset() + + +class MonkeyPatch(object): + """ Object returned by the ``monkeypatch`` fixture keeping a record of setattr/item/env/syspath changes. + """ + + def __init__(self): + self._setattr = [] + self._setitem = [] + self._cwd = None + self._savesyspath = None + + @contextmanager + def context(self): + """ + Context manager that returns a new :class:`MonkeyPatch` object which + undoes any patching done inside the ``with`` block upon exit: + + .. code-block:: python + + import functools + def test_partial(monkeypatch): + with monkeypatch.context() as m: + m.setattr(functools, "partial", 3) + + Useful in situations where it is desired to undo some patches before the test ends, + such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples + of this see `#3290 `_. + """ + m = MonkeyPatch() + try: + yield m + finally: + m.undo() + + def setattr(self, target, name, value=notset, raising=True): + """ Set attribute value on target, memorizing the old value. + By default raise AttributeError if the attribute did not exist. + + For convenience you can specify a string as ``target`` which + will be interpreted as a dotted import path, with the last part + being the attribute name. Example: + ``monkeypatch.setattr("os.getcwd", lambda: "/")`` + would set the ``getcwd`` function of the ``os`` module. + + The ``raising`` value determines if the setattr should fail + if the attribute is not already present (defaults to True + which means it will raise). + """ + __tracebackhide__ = True + import inspect + + if value is notset: + if not isinstance(target, six.string_types): + raise TypeError( + "use setattr(target, name, value) or " + "setattr(target, value) with target being a dotted " + "import string" + ) + value = name + name, target = derive_importpath(target, raising) + + oldval = getattr(target, name, notset) + if raising and oldval is notset: + raise AttributeError("%r has no attribute %r" % (target, name)) + + # avoid class descriptors like staticmethod/classmethod + if inspect.isclass(target): + oldval = target.__dict__.get(name, notset) + self._setattr.append((target, name, oldval)) + setattr(target, name, value) + + def delattr(self, target, name=notset, raising=True): + """ Delete attribute ``name`` from ``target``, by default raise + AttributeError it the attribute did not previously exist. + + If no ``name`` is specified and ``target`` is a string + it will be interpreted as a dotted import path with the + last part being the attribute name. + + If ``raising`` is set to False, no exception will be raised if the + attribute is missing. + """ + __tracebackhide__ = True + import inspect + + if name is notset: + if not isinstance(target, six.string_types): + raise TypeError( + "use delattr(target, name) or " + "delattr(target) with target being a dotted " + "import string" + ) + name, target = derive_importpath(target, raising) + + if not hasattr(target, name): + if raising: + raise AttributeError(name) + else: + oldval = getattr(target, name, notset) + # Avoid class descriptors like staticmethod/classmethod. + if inspect.isclass(target): + oldval = target.__dict__.get(name, notset) + self._setattr.append((target, name, oldval)) + delattr(target, name) + + def setitem(self, dic, name, value): + """ Set dictionary entry ``name`` to value. """ + self._setitem.append((dic, name, dic.get(name, notset))) + dic[name] = value + + def delitem(self, dic, name, raising=True): + """ Delete ``name`` from dict. Raise KeyError if it doesn't exist. + + If ``raising`` is set to False, no exception will be raised if the + key is missing. + """ + if name not in dic: + if raising: + raise KeyError(name) + else: + self._setitem.append((dic, name, dic.get(name, notset))) + del dic[name] + + def _warn_if_env_name_is_not_str(self, name): + """On Python 2, warn if the given environment variable name is not a native str (#4056)""" + if six.PY2 and not isinstance(name, str): + warnings.warn( + pytest.PytestWarning( + "Environment variable name {!r} should be str".format(name) + ) + ) + + def setenv(self, name, value, prepend=None): + """ Set environment variable ``name`` to ``value``. If ``prepend`` + is a character, read the current environment variable value + and prepend the ``value`` adjoined with the ``prepend`` character.""" + if not isinstance(value, str): + warnings.warn( + pytest.PytestWarning( + "Value of environment variable {name} type should be str, but got " + "{value!r} (type: {type}); converted to str implicitly".format( + name=name, value=value, type=type(value).__name__ + ) + ), + stacklevel=2, + ) + value = str(value) + if prepend and name in os.environ: + value = value + prepend + os.environ[name] + self._warn_if_env_name_is_not_str(name) + self.setitem(os.environ, name, value) + + def delenv(self, name, raising=True): + """ Delete ``name`` from the environment. Raise KeyError if it does + not exist. + + If ``raising`` is set to False, no exception will be raised if the + environment variable is missing. + """ + self._warn_if_env_name_is_not_str(name) + self.delitem(os.environ, name, raising=raising) + + def syspath_prepend(self, path): + """ Prepend ``path`` to ``sys.path`` list of import locations. """ + from pkg_resources import fixup_namespace_packages + + if self._savesyspath is None: + self._savesyspath = sys.path[:] + sys.path.insert(0, str(path)) + + # https://github.com/pypa/setuptools/blob/d8b901bc/docs/pkg_resources.txt#L162-L171 + fixup_namespace_packages(str(path)) + + # A call to syspathinsert() usually means that the caller wants to + # import some dynamically created files, thus with python3 we + # invalidate its import caches. + # This is especially important when any namespace package is in used, + # since then the mtime based FileFinder cache (that gets created in + # this case already) gets not invalidated when writing the new files + # quickly afterwards. + if sys.version_info >= (3, 3): + from importlib import invalidate_caches + + invalidate_caches() + + def chdir(self, path): + """ Change the current working directory to the specified path. + Path can be a string or a py.path.local object. + """ + if self._cwd is None: + self._cwd = os.getcwd() + if hasattr(path, "chdir"): + path.chdir() + elif isinstance(path, Path): + # modern python uses the fspath protocol here LEGACY + os.chdir(str(path)) + else: + os.chdir(path) + + def undo(self): + """ Undo previous changes. This call consumes the + undo stack. Calling it a second time has no effect unless + you do more monkeypatching after the undo call. + + There is generally no need to call `undo()`, since it is + called automatically during tear-down. + + Note that the same `monkeypatch` fixture is used across a + single test function invocation. If `monkeypatch` is used both by + the test function itself and one of the test fixtures, + calling `undo()` will undo all of the changes made in + both functions. + """ + for obj, name, value in reversed(self._setattr): + if value is not notset: + setattr(obj, name, value) + else: + delattr(obj, name) + self._setattr[:] = [] + for dictionary, name, value in reversed(self._setitem): + if value is notset: + try: + del dictionary[name] + except KeyError: + pass # was already deleted, so we have the desired state + else: + dictionary[name] = value + self._setitem[:] = [] + if self._savesyspath is not None: + sys.path[:] = self._savesyspath + self._savesyspath = None + + if self._cwd is not None: + os.chdir(self._cwd) + self._cwd = None diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/nodes.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..206e9ae163e38b7dbba11693bab7968d00e5d19c --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/nodes.py @@ -0,0 +1,429 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import warnings + +import py +import six + +import _pytest._code +from _pytest.compat import getfslineno +from _pytest.mark.structures import NodeKeywords +from _pytest.outcomes import fail + +SEP = "/" + +tracebackcutdir = py.path.local(_pytest.__file__).dirpath() + + +def _splitnode(nodeid): + """Split a nodeid into constituent 'parts'. + + Node IDs are strings, and can be things like: + '' + 'testing/code' + 'testing/code/test_excinfo.py' + 'testing/code/test_excinfo.py::TestFormattedExcinfo' + + Return values are lists e.g. + [] + ['testing', 'code'] + ['testing', 'code', 'test_excinfo.py'] + ['testing', 'code', 'test_excinfo.py', 'TestFormattedExcinfo', '()'] + """ + if nodeid == "": + # If there is no root node at all, return an empty list so the caller's logic can remain sane + return [] + parts = nodeid.split(SEP) + # Replace single last element 'test_foo.py::Bar' with multiple elements 'test_foo.py', 'Bar' + parts[-1:] = parts[-1].split("::") + return parts + + +def ischildnode(baseid, nodeid): + """Return True if the nodeid is a child node of the baseid. + + E.g. 'foo/bar::Baz' is a child of 'foo', 'foo/bar' and 'foo/bar::Baz', but not of 'foo/blorp' + """ + base_parts = _splitnode(baseid) + node_parts = _splitnode(nodeid) + if len(node_parts) < len(base_parts): + return False + return node_parts[: len(base_parts)] == base_parts + + +class Node(object): + """ base class for Collector and Item the test collection tree. + Collector subclasses have children, Items are terminal nodes.""" + + def __init__( + self, name, parent=None, config=None, session=None, fspath=None, nodeid=None + ): + #: a unique name within the scope of the parent node + self.name = name + + #: the parent collector node. + self.parent = parent + + #: the pytest config object + self.config = config or parent.config + + #: the session this node is part of + self.session = session or parent.session + + #: filesystem path where this node was collected from (can be None) + self.fspath = fspath or getattr(parent, "fspath", None) + + #: keywords/markers collected from all scopes + self.keywords = NodeKeywords(self) + + #: the marker objects belonging to this node + self.own_markers = [] + + #: allow adding of extra keywords to use for matching + self.extra_keyword_matches = set() + + # used for storing artificial fixturedefs for direct parametrization + self._name2pseudofixturedef = {} + + if nodeid is not None: + assert "::()" not in nodeid + self._nodeid = nodeid + else: + self._nodeid = self.parent.nodeid + if self.name != "()": + self._nodeid += "::" + self.name + + @property + def ihook(self): + """ fspath sensitive hook proxy used to call pytest hooks""" + return self.session.gethookproxy(self.fspath) + + def __repr__(self): + return "<%s %s>" % (self.__class__.__name__, getattr(self, "name", None)) + + def warn(self, warning): + """Issue a warning for this item. + + Warnings will be displayed after the test session, unless explicitly suppressed + + :param Warning warning: the warning instance to issue. Must be a subclass of PytestWarning. + + :raise ValueError: if ``warning`` instance is not a subclass of PytestWarning. + + Example usage: + + .. code-block:: python + + node.warn(PytestWarning("some message")) + + """ + from _pytest.warning_types import PytestWarning + + if not isinstance(warning, PytestWarning): + raise ValueError( + "warning must be an instance of PytestWarning or subclass, got {!r}".format( + warning + ) + ) + path, lineno = get_fslocation_from_item(self) + warnings.warn_explicit( + warning, + category=None, + filename=str(path), + lineno=lineno + 1 if lineno is not None else None, + ) + + # methods for ordering nodes + @property + def nodeid(self): + """ a ::-separated string denoting its collection tree address. """ + return self._nodeid + + def __hash__(self): + return hash(self.nodeid) + + def setup(self): + pass + + def teardown(self): + pass + + def listchain(self): + """ return list of all parent collectors up to self, + starting from root of collection tree. """ + chain = [] + item = self + while item is not None: + chain.append(item) + item = item.parent + chain.reverse() + return chain + + def add_marker(self, marker, append=True): + """dynamically add a marker object to the node. + + :type marker: ``str`` or ``pytest.mark.*`` object + :param marker: + ``append=True`` whether to append the marker, + if ``False`` insert at position ``0``. + """ + from _pytest.mark import MarkDecorator, MARK_GEN + + if isinstance(marker, six.string_types): + marker = getattr(MARK_GEN, marker) + elif not isinstance(marker, MarkDecorator): + raise ValueError("is not a string or pytest.mark.* Marker") + self.keywords[marker.name] = marker + if append: + self.own_markers.append(marker.mark) + else: + self.own_markers.insert(0, marker.mark) + + def iter_markers(self, name=None): + """ + :param name: if given, filter the results by the name attribute + + iterate over all markers of the node + """ + return (x[1] for x in self.iter_markers_with_node(name=name)) + + def iter_markers_with_node(self, name=None): + """ + :param name: if given, filter the results by the name attribute + + iterate over all markers of the node + returns sequence of tuples (node, mark) + """ + for node in reversed(self.listchain()): + for mark in node.own_markers: + if name is None or getattr(mark, "name", None) == name: + yield node, mark + + def get_closest_marker(self, name, default=None): + """return the first marker matching the name, from closest (for example function) to farther level (for example + module level). + + :param default: fallback return value of no marker was found + :param name: name to filter by + """ + return next(self.iter_markers(name=name), default) + + def listextrakeywords(self): + """ Return a set of all extra keywords in self and any parents.""" + extra_keywords = set() + for item in self.listchain(): + extra_keywords.update(item.extra_keyword_matches) + return extra_keywords + + def listnames(self): + return [x.name for x in self.listchain()] + + def addfinalizer(self, fin): + """ register a function to be called when this node is finalized. + + This method can only be called when this node is active + in a setup chain, for example during self.setup(). + """ + self.session._setupstate.addfinalizer(fin, self) + + def getparent(self, cls): + """ get the next parent node (including ourself) + which is an instance of the given class""" + current = self + while current and not isinstance(current, cls): + current = current.parent + return current + + def _prunetraceback(self, excinfo): + pass + + def _repr_failure_py(self, excinfo, style=None): + if excinfo.errisinstance(fail.Exception): + if not excinfo.value.pytrace: + return six.text_type(excinfo.value) + fm = self.session._fixturemanager + if excinfo.errisinstance(fm.FixtureLookupError): + return excinfo.value.formatrepr() + tbfilter = True + if self.config.getoption("fulltrace", False): + style = "long" + else: + tb = _pytest._code.Traceback([excinfo.traceback[-1]]) + self._prunetraceback(excinfo) + if len(excinfo.traceback) == 0: + excinfo.traceback = tb + tbfilter = False # prunetraceback already does it + if style == "auto": + style = "long" + # XXX should excinfo.getrepr record all data and toterminal() process it? + if style is None: + if self.config.getoption("tbstyle", "auto") == "short": + style = "short" + else: + style = "long" + + if self.config.getoption("verbose", 0) > 1: + truncate_locals = False + else: + truncate_locals = True + + try: + os.getcwd() + abspath = False + except OSError: + abspath = True + + return excinfo.getrepr( + funcargs=True, + abspath=abspath, + showlocals=self.config.getoption("showlocals", False), + style=style, + tbfilter=tbfilter, + truncate_locals=truncate_locals, + ) + + repr_failure = _repr_failure_py + + +def get_fslocation_from_item(item): + """Tries to extract the actual location from an item, depending on available attributes: + + * "fslocation": a pair (path, lineno) + * "obj": a Python object that the item wraps. + * "fspath": just a path + + :rtype: a tuple of (str|LocalPath, int) with filename and line number. + """ + result = getattr(item, "location", None) + if result is not None: + return result[:2] + obj = getattr(item, "obj", None) + if obj is not None: + return getfslineno(obj) + return getattr(item, "fspath", "unknown location"), -1 + + +class Collector(Node): + """ Collector instances create children through collect() + and thus iteratively build a tree. + """ + + class CollectError(Exception): + """ an error during collection, contains a custom message. """ + + def collect(self): + """ returns a list of children (items and collectors) + for this collection node. + """ + raise NotImplementedError("abstract") + + def repr_failure(self, excinfo): + """ represent a collection failure. """ + if excinfo.errisinstance(self.CollectError): + exc = excinfo.value + return str(exc.args[0]) + + # Respect explicit tbstyle option, but default to "short" + # (None._repr_failure_py defaults to "long" without "fulltrace" option). + tbstyle = self.config.getoption("tbstyle", "auto") + if tbstyle == "auto": + tbstyle = "short" + + return self._repr_failure_py(excinfo, style=tbstyle) + + def _prunetraceback(self, excinfo): + if hasattr(self, "fspath"): + traceback = excinfo.traceback + ntraceback = traceback.cut(path=self.fspath) + if ntraceback == traceback: + ntraceback = ntraceback.cut(excludepath=tracebackcutdir) + excinfo.traceback = ntraceback.filter() + + +def _check_initialpaths_for_relpath(session, fspath): + for initial_path in session._initialpaths: + if fspath.common(initial_path) == initial_path: + return fspath.relto(initial_path) + + +class FSCollector(Collector): + def __init__(self, fspath, parent=None, config=None, session=None, nodeid=None): + fspath = py.path.local(fspath) # xxx only for test_resultlog.py? + name = fspath.basename + if parent is not None: + rel = fspath.relto(parent.fspath) + if rel: + name = rel + name = name.replace(os.sep, SEP) + self.fspath = fspath + + session = session or parent.session + + if nodeid is None: + nodeid = self.fspath.relto(session.config.rootdir) + + if not nodeid: + nodeid = _check_initialpaths_for_relpath(session, fspath) + if nodeid and os.sep != SEP: + nodeid = nodeid.replace(os.sep, SEP) + + super(FSCollector, self).__init__( + name, parent, config, session, nodeid=nodeid, fspath=fspath + ) + + +class File(FSCollector): + """ base class for collecting tests from a file. """ + + +class Item(Node): + """ a basic test invocation item. Note that for a single function + there might be multiple test invocation items. + """ + + nextitem = None + + def __init__(self, name, parent=None, config=None, session=None, nodeid=None): + super(Item, self).__init__(name, parent, config, session, nodeid=nodeid) + self._report_sections = [] + + #: user properties is a list of tuples (name, value) that holds user + #: defined properties for this test. + self.user_properties = [] + + def add_report_section(self, when, key, content): + """ + Adds a new report section, similar to what's done internally to add stdout and + stderr captured output:: + + item.add_report_section("call", "stdout", "report section contents") + + :param str when: + One of the possible capture states, ``"setup"``, ``"call"``, ``"teardown"``. + :param str key: + Name of the section, can be customized at will. Pytest uses ``"stdout"`` and + ``"stderr"`` internally. + + :param str content: + The full contents as a string. + """ + if content: + self._report_sections.append((when, key, content)) + + def reportinfo(self): + return self.fspath, None, "" + + @property + def location(self): + try: + return self._location + except AttributeError: + location = self.reportinfo() + fspath = self.session._node_location_to_relpath(location[0]) + location = (fspath, location[1], str(location[2])) + self._location = location + return location diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/nose.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/nose.py new file mode 100644 index 0000000000000000000000000000000000000000..fbab91da2499b783c70eac2417073239babc95c8 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/nose.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +""" run test suites written for nose. """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import sys + +import six + +import pytest +from _pytest import python +from _pytest import runner +from _pytest import unittest +from _pytest.config import hookimpl + + +def get_skip_exceptions(): + skip_classes = set() + for module_name in ("unittest", "unittest2", "nose"): + mod = sys.modules.get(module_name) + if hasattr(mod, "SkipTest"): + skip_classes.add(mod.SkipTest) + return tuple(skip_classes) + + +def pytest_runtest_makereport(item, call): + if call.excinfo and call.excinfo.errisinstance(get_skip_exceptions()): + # let's substitute the excinfo with a pytest.skip one + call2 = runner.CallInfo.from_call( + lambda: pytest.skip(six.text_type(call.excinfo.value)), call.when + ) + call.excinfo = call2.excinfo + + +@hookimpl(trylast=True) +def pytest_runtest_setup(item): + if is_potential_nosetest(item): + if not call_optional(item.obj, "setup"): + # call module level setup if there is no object level one + call_optional(item.parent.obj, "setup") + # XXX this implies we only call teardown when setup worked + item.session._setupstate.addfinalizer((lambda: teardown_nose(item)), item) + + +def teardown_nose(item): + if is_potential_nosetest(item): + if not call_optional(item.obj, "teardown"): + call_optional(item.parent.obj, "teardown") + # if hasattr(item.parent, '_nosegensetup'): + # #call_optional(item._nosegensetup, 'teardown') + # del item.parent._nosegensetup + + +def is_potential_nosetest(item): + # extra check needed since we do not do nose style setup/teardown + # on direct unittest style classes + return isinstance(item, python.Function) and not isinstance( + item, unittest.TestCaseFunction + ) + + +def call_optional(obj, name): + method = getattr(obj, name, None) + isfixture = hasattr(method, "_pytestfixturefunction") + if method is not None and not isfixture and callable(method): + # If there's any problems allow the exception to raise rather than + # silently ignoring them + method() + return True diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/outcomes.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/outcomes.py new file mode 100644 index 0000000000000000000000000000000000000000..4620f957c7da66bbcdff57ee8da82e703f686d83 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/outcomes.py @@ -0,0 +1,187 @@ +# -*- coding: utf-8 -*- +""" +exception classes and constants handling test outcomes +as well as functions creating them +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import sys + +from packaging.version import Version + + +class OutcomeException(BaseException): + """ OutcomeException and its subclass instances indicate and + contain info about test and collection outcomes. + """ + + def __init__(self, msg=None, pytrace=True): + BaseException.__init__(self, msg) + self.msg = msg + self.pytrace = pytrace + + def __repr__(self): + if self.msg: + val = self.msg + if isinstance(val, bytes): + val = val.decode("UTF-8", errors="replace") + return val + return "<%s instance>" % (self.__class__.__name__,) + + __str__ = __repr__ + + +TEST_OUTCOME = (OutcomeException, Exception) + + +class Skipped(OutcomeException): + # XXX hackish: on 3k we fake to live in the builtins + # in order to have Skipped exception printing shorter/nicer + __module__ = "builtins" + + def __init__(self, msg=None, pytrace=True, allow_module_level=False): + OutcomeException.__init__(self, msg=msg, pytrace=pytrace) + self.allow_module_level = allow_module_level + + +class Failed(OutcomeException): + """ raised from an explicit call to pytest.fail() """ + + __module__ = "builtins" + + +class Exit(Exception): + """ raised for immediate program exits (no tracebacks/summaries)""" + + def __init__(self, msg="unknown reason", returncode=None): + self.msg = msg + self.returncode = returncode + super(Exit, self).__init__(msg) + + +# exposed helper methods + + +def exit(msg, returncode=None): + """ + Exit testing process. + + :param str msg: message to display upon exit. + :param int returncode: return code to be used when exiting pytest. + """ + __tracebackhide__ = True + raise Exit(msg, returncode) + + +exit.Exception = Exit + + +def skip(msg="", **kwargs): + """ + Skip an executing test with the given message. + + This function should be called only during testing (setup, call or teardown) or + during collection by using the ``allow_module_level`` flag. This function can + be called in doctests as well. + + :kwarg bool allow_module_level: allows this function to be called at + module level, skipping the rest of the module. Default to False. + + .. note:: + It is better to use the :ref:`pytest.mark.skipif ref` marker when possible to declare a test to be + skipped under certain conditions like mismatching platforms or + dependencies. + Similarly, use the ``# doctest: +SKIP`` directive (see `doctest.SKIP + `_) + to skip a doctest statically. + """ + __tracebackhide__ = True + allow_module_level = kwargs.pop("allow_module_level", False) + if kwargs: + raise TypeError("unexpected keyword arguments: {}".format(sorted(kwargs))) + raise Skipped(msg=msg, allow_module_level=allow_module_level) + + +skip.Exception = Skipped + + +def fail(msg="", pytrace=True): + """ + Explicitly fail an executing test with the given message. + + :param str msg: the message to show the user as reason for the failure. + :param bool pytrace: if false the msg represents the full failure information and no + python traceback will be reported. + """ + __tracebackhide__ = True + raise Failed(msg=msg, pytrace=pytrace) + + +fail.Exception = Failed + + +class XFailed(fail.Exception): + """ raised from an explicit call to pytest.xfail() """ + + +def xfail(reason=""): + """ + Imperatively xfail an executing test or setup functions with the given reason. + + This function should be called only during testing (setup, call or teardown). + + .. note:: + It is better to use the :ref:`pytest.mark.xfail ref` marker when possible to declare a test to be + xfailed under certain conditions like known bugs or missing features. + """ + __tracebackhide__ = True + raise XFailed(reason) + + +xfail.Exception = XFailed + + +def importorskip(modname, minversion=None, reason=None): + """Imports and returns the requested module ``modname``, or skip the current test + if the module cannot be imported. + + :param str modname: the name of the module to import + :param str minversion: if given, the imported module ``__version__`` attribute must be + at least this minimal version, otherwise the test is still skipped. + :param str reason: if given, this reason is shown as the message when the module + cannot be imported. + """ + import warnings + + __tracebackhide__ = True + compile(modname, "", "eval") # to catch syntaxerrors + import_exc = None + + with warnings.catch_warnings(): + # make sure to ignore ImportWarnings that might happen because + # of existing directories with the same name we're trying to + # import but without a __init__.py file + warnings.simplefilter("ignore") + try: + __import__(modname) + except ImportError as exc: + # Do not raise chained exception here(#1485) + import_exc = exc + if import_exc: + if reason is None: + reason = "could not import %r: %s" % (modname, import_exc) + raise Skipped(reason, allow_module_level=True) + mod = sys.modules[modname] + if minversion is None: + return mod + verattr = getattr(mod, "__version__", None) + if minversion is not None: + if verattr is None or Version(verattr) < Version(minversion): + raise Skipped( + "module %r has __version__ %r, required is: %r" + % (modname, verattr, minversion), + allow_module_level=True, + ) + return mod diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/pastebin.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/pastebin.py new file mode 100644 index 0000000000000000000000000000000000000000..3f4171207a32aa0c28d2ddccd5f796d09372ec7d --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/pastebin.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- +""" submit failure or test session information to a pastebin service. """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import sys +import tempfile + +import six + +import pytest + + +def pytest_addoption(parser): + group = parser.getgroup("terminal reporting") + group._addoption( + "--pastebin", + metavar="mode", + action="store", + dest="pastebin", + default=None, + choices=["failed", "all"], + help="send failed|all info to bpaste.net pastebin service.", + ) + + +@pytest.hookimpl(trylast=True) +def pytest_configure(config): + if config.option.pastebin == "all": + tr = config.pluginmanager.getplugin("terminalreporter") + # if no terminal reporter plugin is present, nothing we can do here; + # this can happen when this function executes in a slave node + # when using pytest-xdist, for example + if tr is not None: + # pastebin file will be utf-8 encoded binary file + config._pastebinfile = tempfile.TemporaryFile("w+b") + oldwrite = tr._tw.write + + def tee_write(s, **kwargs): + oldwrite(s, **kwargs) + if isinstance(s, six.text_type): + s = s.encode("utf-8") + config._pastebinfile.write(s) + + tr._tw.write = tee_write + + +def pytest_unconfigure(config): + if hasattr(config, "_pastebinfile"): + # get terminal contents and delete file + config._pastebinfile.seek(0) + sessionlog = config._pastebinfile.read() + config._pastebinfile.close() + del config._pastebinfile + # undo our patching in the terminal reporter + tr = config.pluginmanager.getplugin("terminalreporter") + del tr._tw.__dict__["write"] + # write summary + tr.write_sep("=", "Sending information to Paste Service") + pastebinurl = create_new_paste(sessionlog) + tr.write_line("pastebin session-log: %s\n" % pastebinurl) + + +def create_new_paste(contents): + """ + Creates a new paste using bpaste.net service. + + :contents: paste contents as utf-8 encoded bytes + :returns: url to the pasted contents + """ + import re + + if sys.version_info < (3, 0): + from urllib import urlopen, urlencode + else: + from urllib.request import urlopen + from urllib.parse import urlencode + + params = { + "code": contents, + "lexer": "python3" if sys.version_info[0] == 3 else "python", + "expiry": "1week", + } + url = "https://bpaste.net" + response = urlopen(url, data=urlencode(params).encode("ascii")).read() + m = re.search(r'href="/raw/(\w+)"', response.decode("utf-8")) + if m: + return "%s/show/%s" % (url, m.group(1)) + else: + return "bad response: " + response + + +def pytest_terminal_summary(terminalreporter): + import _pytest.config + + if terminalreporter.config.option.pastebin != "failed": + return + tr = terminalreporter + if "failed" in tr.stats: + terminalreporter.write_sep("=", "Sending information to Paste Service") + for rep in terminalreporter.stats.get("failed"): + try: + msg = rep.longrepr.reprtraceback.reprentries[-1].reprfileloc + except AttributeError: + msg = tr._getfailureheadline(rep) + tw = _pytest.config.create_terminal_writer( + terminalreporter.config, stringio=True + ) + rep.toterminal(tw) + s = tw.stringio.getvalue() + assert len(s) + pastebinurl = create_new_paste(s) + tr.write_line("%s --> %s" % (msg, pastebinurl)) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/pathlib.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/pathlib.py new file mode 100644 index 0000000000000000000000000000000000000000..8d12161944436764e8f32aef73c916046c239033 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/pathlib.py @@ -0,0 +1,365 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import + +import atexit +import errno +import fnmatch +import itertools +import operator +import os +import shutil +import sys +import uuid +import warnings +from functools import partial +from functools import reduce +from os.path import expanduser +from os.path import expandvars +from os.path import isabs +from os.path import sep +from posixpath import sep as posix_sep + +import six +from six.moves import map + +from .compat import PY36 +from _pytest.warning_types import PytestWarning + +if PY36: + from pathlib import Path, PurePath +else: + from pathlib2 import Path, PurePath + +__all__ = ["Path", "PurePath"] + + +LOCK_TIMEOUT = 60 * 60 * 3 + +get_lock_path = operator.methodcaller("joinpath", ".lock") + + +def ensure_reset_dir(path): + """ + ensures the given path is an empty directory + """ + if path.exists(): + rm_rf(path) + path.mkdir() + + +def on_rm_rf_error(func, path, exc, **kwargs): + """Handles known read-only errors during rmtree.""" + start_path = kwargs["start_path"] + excvalue = exc[1] + + if not isinstance(excvalue, OSError) or excvalue.errno not in ( + errno.EACCES, + errno.EPERM, + ): + warnings.warn( + PytestWarning("(rm_rf) error removing {}: {}".format(path, excvalue)) + ) + return + + if func not in (os.rmdir, os.remove, os.unlink): + warnings.warn( + PytestWarning("(rm_rf) error removing {}: {}".format(path, excvalue)) + ) + return + + # Chmod + retry. + import stat + + def chmod_rw(p): + mode = os.stat(p).st_mode + os.chmod(p, mode | stat.S_IRUSR | stat.S_IWUSR) + + # For files, we need to recursively go upwards in the directories to + # ensure they all are also writable. + p = Path(path) + if p.is_file(): + for parent in p.parents: + chmod_rw(str(parent)) + # stop when we reach the original path passed to rm_rf + if parent == start_path: + break + chmod_rw(str(path)) + + func(path) + + +def rm_rf(path): + """Remove the path contents recursively, even if some elements + are read-only. + """ + onerror = partial(on_rm_rf_error, start_path=path) + shutil.rmtree(str(path), onerror=onerror) + + +def find_prefixed(root, prefix): + """finds all elements in root that begin with the prefix, case insensitive""" + l_prefix = prefix.lower() + for x in root.iterdir(): + if x.name.lower().startswith(l_prefix): + yield x + + +def extract_suffixes(iter, prefix): + """ + :param iter: iterator over path names + :param prefix: expected prefix of the path names + :returns: the parts of the paths following the prefix + """ + p_len = len(prefix) + for p in iter: + yield p.name[p_len:] + + +def find_suffixes(root, prefix): + """combines find_prefixes and extract_suffixes + """ + return extract_suffixes(find_prefixed(root, prefix), prefix) + + +def parse_num(maybe_num): + """parses number path suffixes, returns -1 on error""" + try: + return int(maybe_num) + except ValueError: + return -1 + + +if six.PY2: + + def _max(iterable, default): + """needed due to python2.7 lacking the default argument for max""" + return reduce(max, iterable, default) + + +else: + _max = max + + +def _force_symlink(root, target, link_to): + """helper to create the current symlink + + it's full of race conditions that are reasonably ok to ignore + for the context of best effort linking to the latest testrun + + the presumption being thatin case of much parallelism + the inaccuracy is going to be acceptable + """ + current_symlink = root.joinpath(target) + try: + current_symlink.unlink() + except OSError: + pass + try: + current_symlink.symlink_to(link_to) + except Exception: + pass + + +def make_numbered_dir(root, prefix): + """create a directory with an increased number as suffix for the given prefix""" + for i in range(10): + # try up to 10 times to create the folder + max_existing = _max(map(parse_num, find_suffixes(root, prefix)), default=-1) + new_number = max_existing + 1 + new_path = root.joinpath("{}{}".format(prefix, new_number)) + try: + new_path.mkdir() + except Exception: + pass + else: + _force_symlink(root, prefix + "current", new_path) + return new_path + else: + raise EnvironmentError( + "could not create numbered dir with prefix " + "{prefix} in {root} after 10 tries".format(prefix=prefix, root=root) + ) + + +def create_cleanup_lock(p): + """crates a lock to prevent premature folder cleanup""" + lock_path = get_lock_path(p) + try: + fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644) + except OSError as e: + if e.errno == errno.EEXIST: + six.raise_from( + EnvironmentError("cannot create lockfile in {path}".format(path=p)), e + ) + else: + raise + else: + pid = os.getpid() + spid = str(pid) + if not isinstance(spid, bytes): + spid = spid.encode("ascii") + os.write(fd, spid) + os.close(fd) + if not lock_path.is_file(): + raise EnvironmentError("lock path got renamed after successful creation") + return lock_path + + +def register_cleanup_lock_removal(lock_path, register=atexit.register): + """registers a cleanup function for removing a lock, by default on atexit""" + pid = os.getpid() + + def cleanup_on_exit(lock_path=lock_path, original_pid=pid): + current_pid = os.getpid() + if current_pid != original_pid: + # fork + return + try: + lock_path.unlink() + except (OSError, IOError): + pass + + return register(cleanup_on_exit) + + +def maybe_delete_a_numbered_dir(path): + """removes a numbered directory if its lock can be obtained and it does not seem to be in use""" + lock_path = None + try: + lock_path = create_cleanup_lock(path) + parent = path.parent + + garbage = parent.joinpath("garbage-{}".format(uuid.uuid4())) + path.rename(garbage) + rm_rf(garbage) + except (OSError, EnvironmentError): + # known races: + # * other process did a cleanup at the same time + # * deletable folder was found + # * process cwd (Windows) + return + finally: + # if we created the lock, ensure we remove it even if we failed + # to properly remove the numbered dir + if lock_path is not None: + try: + lock_path.unlink() + except (OSError, IOError): + pass + + +def ensure_deletable(path, consider_lock_dead_if_created_before): + """checks if a lock exists and breaks it if its considered dead""" + if path.is_symlink(): + return False + lock = get_lock_path(path) + if not lock.exists(): + return True + try: + lock_time = lock.stat().st_mtime + except Exception: + return False + else: + if lock_time < consider_lock_dead_if_created_before: + lock.unlink() + return True + else: + return False + + +def try_cleanup(path, consider_lock_dead_if_created_before): + """tries to cleanup a folder if we can ensure it's deletable""" + if ensure_deletable(path, consider_lock_dead_if_created_before): + maybe_delete_a_numbered_dir(path) + + +def cleanup_candidates(root, prefix, keep): + """lists candidates for numbered directories to be removed - follows py.path""" + max_existing = _max(map(parse_num, find_suffixes(root, prefix)), default=-1) + max_delete = max_existing - keep + paths = find_prefixed(root, prefix) + paths, paths2 = itertools.tee(paths) + numbers = map(parse_num, extract_suffixes(paths2, prefix)) + for path, number in zip(paths, numbers): + if number <= max_delete: + yield path + + +def cleanup_numbered_dir(root, prefix, keep, consider_lock_dead_if_created_before): + """cleanup for lock driven numbered directories""" + for path in cleanup_candidates(root, prefix, keep): + try_cleanup(path, consider_lock_dead_if_created_before) + for path in root.glob("garbage-*"): + try_cleanup(path, consider_lock_dead_if_created_before) + + +def make_numbered_dir_with_cleanup(root, prefix, keep, lock_timeout): + """creates a numbered dir with a cleanup lock and removes old ones""" + e = None + for i in range(10): + try: + p = make_numbered_dir(root, prefix) + lock_path = create_cleanup_lock(p) + register_cleanup_lock_removal(lock_path) + except Exception as exc: + e = exc + else: + consider_lock_dead_if_created_before = p.stat().st_mtime - lock_timeout + cleanup_numbered_dir( + root=root, + prefix=prefix, + keep=keep, + consider_lock_dead_if_created_before=consider_lock_dead_if_created_before, + ) + return p + assert e is not None + raise e + + +def resolve_from_str(input, root): + assert not isinstance(input, Path), "would break on py2" + root = Path(root) + input = expanduser(input) + input = expandvars(input) + if isabs(input): + return Path(input) + else: + return root.joinpath(input) + + +def fnmatch_ex(pattern, path): + """FNMatcher port from py.path.common which works with PurePath() instances. + + The difference between this algorithm and PurePath.match() is that the latter matches "**" glob expressions + for each part of the path, while this algorithm uses the whole path instead. + + For example: + "tests/foo/bar/doc/test_foo.py" matches pattern "tests/**/doc/test*.py" with this algorithm, but not with + PurePath.match(). + + This algorithm was ported to keep backward-compatibility with existing settings which assume paths match according + this logic. + + References: + * https://bugs.python.org/issue29249 + * https://bugs.python.org/issue34731 + """ + path = PurePath(path) + iswin32 = sys.platform.startswith("win") + + if iswin32 and sep not in pattern and posix_sep in pattern: + # Running on Windows, the pattern has no Windows path separators, + # and the pattern has one or more Posix path separators. Replace + # the Posix path separators with the Windows path separator. + pattern = pattern.replace(posix_sep, sep) + + if sep not in pattern: + name = path.name + else: + name = six.text_type(path) + return fnmatch.fnmatch(name, pattern) + + +def parts(s): + parts = s.split(sep) + return {sep.join(parts[: i + 1]) or sep for i in range(len(parts))} diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/pytester.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/pytester.py new file mode 100644 index 0000000000000000000000000000000000000000..605451630a6463b8ec631e2ab4cd13ae8866d08a --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/pytester.py @@ -0,0 +1,1413 @@ +# -*- coding: utf-8 -*- +"""(disabled by default) support for testing pytest and pytest plugins.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import codecs +import gc +import os +import platform +import re +import subprocess +import sys +import time +import traceback +from fnmatch import fnmatch +from weakref import WeakKeyDictionary + +import py +import six + +import pytest +from _pytest._code import Source +from _pytest._io.saferepr import saferepr +from _pytest.assertion.rewrite import AssertionRewritingHook +from _pytest.capture import MultiCapture +from _pytest.capture import SysCapture +from _pytest.compat import safe_str +from _pytest.compat import Sequence +from _pytest.main import EXIT_INTERRUPTED +from _pytest.main import EXIT_OK +from _pytest.main import Session +from _pytest.monkeypatch import MonkeyPatch +from _pytest.pathlib import Path + +IGNORE_PAM = [ # filenames added when obtaining details about the current user + u"/var/lib/sss/mc/passwd" +] + + +def pytest_addoption(parser): + parser.addoption( + "--lsof", + action="store_true", + dest="lsof", + default=False, + help="run FD checks if lsof is available", + ) + + parser.addoption( + "--runpytest", + default="inprocess", + dest="runpytest", + choices=("inprocess", "subprocess"), + help=( + "run pytest sub runs in tests using an 'inprocess' " + "or 'subprocess' (python -m main) method" + ), + ) + + parser.addini( + "pytester_example_dir", help="directory to take the pytester example files from" + ) + + +def pytest_configure(config): + if config.getvalue("lsof"): + checker = LsofFdLeakChecker() + if checker.matching_platform(): + config.pluginmanager.register(checker) + + config.addinivalue_line( + "markers", + "pytester_example_path(*path_segments): join the given path " + "segments to `pytester_example_dir` for this test.", + ) + + +def raise_on_kwargs(kwargs): + __tracebackhide__ = True + if kwargs: # pragma: no branch + raise TypeError( + "Unexpected keyword arguments: {}".format(", ".join(sorted(kwargs))) + ) + + +class LsofFdLeakChecker(object): + def get_open_files(self): + out = self._exec_lsof() + open_files = self._parse_lsof_output(out) + return open_files + + def _exec_lsof(self): + pid = os.getpid() + # py3: use subprocess.DEVNULL directly. + with open(os.devnull, "wb") as devnull: + return subprocess.check_output( + ("lsof", "-Ffn0", "-p", str(pid)), stderr=devnull + ).decode() + + def _parse_lsof_output(self, out): + def isopen(line): + return line.startswith("f") and ( + "deleted" not in line + and "mem" not in line + and "txt" not in line + and "cwd" not in line + ) + + open_files = [] + + for line in out.split("\n"): + if isopen(line): + fields = line.split("\0") + fd = fields[0][1:] + filename = fields[1][1:] + if filename in IGNORE_PAM: + continue + if filename.startswith("/"): + open_files.append((fd, filename)) + + return open_files + + def matching_platform(self): + try: + subprocess.check_output(("lsof", "-v")) + except (OSError, subprocess.CalledProcessError): + return False + else: + return True + + @pytest.hookimpl(hookwrapper=True, tryfirst=True) + def pytest_runtest_protocol(self, item): + lines1 = self.get_open_files() + yield + if hasattr(sys, "pypy_version_info"): + gc.collect() + lines2 = self.get_open_files() + + new_fds = {t[0] for t in lines2} - {t[0] for t in lines1} + leaked_files = [t for t in lines2 if t[0] in new_fds] + if leaked_files: + error = [] + error.append("***** %s FD leakage detected" % len(leaked_files)) + error.extend([str(f) for f in leaked_files]) + error.append("*** Before:") + error.extend([str(f) for f in lines1]) + error.append("*** After:") + error.extend([str(f) for f in lines2]) + error.append(error[0]) + error.append("*** function %s:%s: %s " % item.location) + error.append("See issue #2366") + item.warn(pytest.PytestWarning("\n".join(error))) + + +# used at least by pytest-xdist plugin + + +@pytest.fixture +def _pytest(request): + """Return a helper which offers a gethookrecorder(hook) method which + returns a HookRecorder instance which helps to make assertions about called + hooks. + + """ + return PytestArg(request) + + +class PytestArg(object): + def __init__(self, request): + self.request = request + + def gethookrecorder(self, hook): + hookrecorder = HookRecorder(hook._pm) + self.request.addfinalizer(hookrecorder.finish_recording) + return hookrecorder + + +def get_public_names(values): + """Only return names from iterator values without a leading underscore.""" + return [x for x in values if x[0] != "_"] + + +class ParsedCall(object): + def __init__(self, name, kwargs): + self.__dict__.update(kwargs) + self._name = name + + def __repr__(self): + d = self.__dict__.copy() + del d["_name"] + return "" % (self._name, d) + + +class HookRecorder(object): + """Record all hooks called in a plugin manager. + + This wraps all the hook calls in the plugin manager, recording each call + before propagating the normal calls. + + """ + + def __init__(self, pluginmanager): + self._pluginmanager = pluginmanager + self.calls = [] + + def before(hook_name, hook_impls, kwargs): + self.calls.append(ParsedCall(hook_name, kwargs)) + + def after(outcome, hook_name, hook_impls, kwargs): + pass + + self._undo_wrapping = pluginmanager.add_hookcall_monitoring(before, after) + + def finish_recording(self): + self._undo_wrapping() + + def getcalls(self, names): + if isinstance(names, str): + names = names.split() + return [call for call in self.calls if call._name in names] + + def assert_contains(self, entries): + __tracebackhide__ = True + i = 0 + entries = list(entries) + backlocals = sys._getframe(1).f_locals + while entries: + name, check = entries.pop(0) + for ind, call in enumerate(self.calls[i:]): + if call._name == name: + print("NAMEMATCH", name, call) + if eval(check, backlocals, call.__dict__): + print("CHECKERMATCH", repr(check), "->", call) + else: + print("NOCHECKERMATCH", repr(check), "-", call) + continue + i += ind + 1 + break + print("NONAMEMATCH", name, "with", call) + else: + pytest.fail("could not find %r check %r" % (name, check)) + + def popcall(self, name): + __tracebackhide__ = True + for i, call in enumerate(self.calls): + if call._name == name: + del self.calls[i] + return call + lines = ["could not find call %r, in:" % (name,)] + lines.extend([" %s" % x for x in self.calls]) + pytest.fail("\n".join(lines)) + + def getcall(self, name): + values = self.getcalls(name) + assert len(values) == 1, (name, values) + return values[0] + + # functionality for test reports + + def getreports(self, names="pytest_runtest_logreport pytest_collectreport"): + return [x.report for x in self.getcalls(names)] + + def matchreport( + self, + inamepart="", + names="pytest_runtest_logreport pytest_collectreport", + when=None, + ): + """return a testreport whose dotted import path matches""" + values = [] + for rep in self.getreports(names=names): + if not when and rep.when != "call" and rep.passed: + # setup/teardown passing reports - let's ignore those + continue + if when and rep.when != when: + continue + if not inamepart or inamepart in rep.nodeid.split("::"): + values.append(rep) + if not values: + raise ValueError( + "could not find test report matching %r: " + "no test reports at all!" % (inamepart,) + ) + if len(values) > 1: + raise ValueError( + "found 2 or more testreports matching %r: %s" % (inamepart, values) + ) + return values[0] + + def getfailures(self, names="pytest_runtest_logreport pytest_collectreport"): + return [rep for rep in self.getreports(names) if rep.failed] + + def getfailedcollections(self): + return self.getfailures("pytest_collectreport") + + def listoutcomes(self): + passed = [] + skipped = [] + failed = [] + for rep in self.getreports("pytest_collectreport pytest_runtest_logreport"): + if rep.passed: + if rep.when == "call": + passed.append(rep) + elif rep.skipped: + skipped.append(rep) + else: + assert rep.failed, "Unexpected outcome: {!r}".format(rep) + failed.append(rep) + return passed, skipped, failed + + def countoutcomes(self): + return [len(x) for x in self.listoutcomes()] + + def assertoutcome(self, passed=0, skipped=0, failed=0): + realpassed, realskipped, realfailed = self.listoutcomes() + assert passed == len(realpassed) + assert skipped == len(realskipped) + assert failed == len(realfailed) + + def clear(self): + self.calls[:] = [] + + +@pytest.fixture +def linecomp(request): + return LineComp() + + +@pytest.fixture(name="LineMatcher") +def LineMatcher_fixture(request): + return LineMatcher + + +@pytest.fixture +def testdir(request, tmpdir_factory): + return Testdir(request, tmpdir_factory) + + +@pytest.fixture +def _sys_snapshot(): + snappaths = SysPathsSnapshot() + snapmods = SysModulesSnapshot() + yield + snapmods.restore() + snappaths.restore() + + +@pytest.fixture +def _config_for_test(): + from _pytest.config import get_config + + config = get_config() + yield config + config._ensure_unconfigure() # cleanup, e.g. capman closing tmpfiles. + + +rex_outcome = re.compile(r"(\d+) ([\w-]+)") + + +class RunResult(object): + """The result of running a command. + + Attributes: + + :ret: the return value + :outlines: list of lines captured from stdout + :errlines: list of lines captures from stderr + :stdout: :py:class:`LineMatcher` of stdout, use ``stdout.str()`` to + reconstruct stdout or the commonly used ``stdout.fnmatch_lines()`` + method + :stderr: :py:class:`LineMatcher` of stderr + :duration: duration in seconds + + """ + + def __init__(self, ret, outlines, errlines, duration): + self.ret = ret + self.outlines = outlines + self.errlines = errlines + self.stdout = LineMatcher(outlines) + self.stderr = LineMatcher(errlines) + self.duration = duration + + def __repr__(self): + return ( + "" + % (self.ret, len(self.stdout.lines), len(self.stderr.lines), self.duration) + ) + + def parseoutcomes(self): + """Return a dictionary of outcomestring->num from parsing the terminal + output that the test process produced. + + """ + for line in reversed(self.outlines): + if "seconds" in line: + outcomes = rex_outcome.findall(line) + if outcomes: + d = {} + for num, cat in outcomes: + d[cat] = int(num) + return d + raise ValueError("Pytest terminal report not found") + + def assert_outcomes( + self, passed=0, skipped=0, failed=0, error=0, xpassed=0, xfailed=0 + ): + """Assert that the specified outcomes appear with the respective + numbers (0 means it didn't occur) in the text output from a test run. + + """ + d = self.parseoutcomes() + obtained = { + "passed": d.get("passed", 0), + "skipped": d.get("skipped", 0), + "failed": d.get("failed", 0), + "error": d.get("error", 0), + "xpassed": d.get("xpassed", 0), + "xfailed": d.get("xfailed", 0), + } + expected = { + "passed": passed, + "skipped": skipped, + "failed": failed, + "error": error, + "xpassed": xpassed, + "xfailed": xfailed, + } + assert obtained == expected + + +class CwdSnapshot(object): + def __init__(self): + self.__saved = os.getcwd() + + def restore(self): + os.chdir(self.__saved) + + +class SysModulesSnapshot(object): + def __init__(self, preserve=None): + self.__preserve = preserve + self.__saved = dict(sys.modules) + + def restore(self): + if self.__preserve: + self.__saved.update( + (k, m) for k, m in sys.modules.items() if self.__preserve(k) + ) + sys.modules.clear() + sys.modules.update(self.__saved) + + +class SysPathsSnapshot(object): + def __init__(self): + self.__saved = list(sys.path), list(sys.meta_path) + + def restore(self): + sys.path[:], sys.meta_path[:] = self.__saved + + +class Testdir(object): + """Temporary test directory with tools to test/run pytest itself. + + This is based on the ``tmpdir`` fixture but provides a number of methods + which aid with testing pytest itself. Unless :py:meth:`chdir` is used all + methods will use :py:attr:`tmpdir` as their current working directory. + + Attributes: + + :tmpdir: The :py:class:`py.path.local` instance of the temporary directory. + + :plugins: A list of plugins to use with :py:meth:`parseconfig` and + :py:meth:`runpytest`. Initially this is an empty list but plugins can + be added to the list. The type of items to add to the list depends on + the method using them so refer to them for details. + + """ + + CLOSE_STDIN = object + + class TimeoutExpired(Exception): + pass + + def __init__(self, request, tmpdir_factory): + self.request = request + self._mod_collections = WeakKeyDictionary() + name = request.function.__name__ + self.tmpdir = tmpdir_factory.mktemp(name, numbered=True) + self.test_tmproot = tmpdir_factory.mktemp("tmp-" + name, numbered=True) + self.plugins = [] + self._cwd_snapshot = CwdSnapshot() + self._sys_path_snapshot = SysPathsSnapshot() + self._sys_modules_snapshot = self.__take_sys_modules_snapshot() + self.chdir() + self.request.addfinalizer(self.finalize) + method = self.request.config.getoption("--runpytest") + if method == "inprocess": + self._runpytest_method = self.runpytest_inprocess + elif method == "subprocess": + self._runpytest_method = self.runpytest_subprocess + + mp = self.monkeypatch = MonkeyPatch() + mp.setenv("PYTEST_DEBUG_TEMPROOT", str(self.test_tmproot)) + # Ensure no unexpected caching via tox. + mp.delenv("TOX_ENV_DIR", raising=False) + # Discard outer pytest options. + mp.delenv("PYTEST_ADDOPTS", raising=False) + + # Environment (updates) for inner runs. + tmphome = str(self.tmpdir) + self._env_run_update = {"HOME": tmphome, "USERPROFILE": tmphome} + + def __repr__(self): + return "" % (self.tmpdir,) + + def __str__(self): + return str(self.tmpdir) + + def finalize(self): + """Clean up global state artifacts. + + Some methods modify the global interpreter state and this tries to + clean this up. It does not remove the temporary directory however so + it can be looked at after the test run has finished. + + """ + self._sys_modules_snapshot.restore() + self._sys_path_snapshot.restore() + self._cwd_snapshot.restore() + self.monkeypatch.undo() + + def __take_sys_modules_snapshot(self): + # some zope modules used by twisted-related tests keep internal state + # and can't be deleted; we had some trouble in the past with + # `zope.interface` for example + def preserve_module(name): + return name.startswith("zope") + + return SysModulesSnapshot(preserve=preserve_module) + + def make_hook_recorder(self, pluginmanager): + """Create a new :py:class:`HookRecorder` for a PluginManager.""" + pluginmanager.reprec = reprec = HookRecorder(pluginmanager) + self.request.addfinalizer(reprec.finish_recording) + return reprec + + def chdir(self): + """Cd into the temporary directory. + + This is done automatically upon instantiation. + + """ + self.tmpdir.chdir() + + def _makefile(self, ext, args, kwargs, encoding="utf-8"): + items = list(kwargs.items()) + + def to_text(s): + return s.decode(encoding) if isinstance(s, bytes) else six.text_type(s) + + if args: + source = u"\n".join(to_text(x) for x in args) + basename = self.request.function.__name__ + items.insert(0, (basename, source)) + + ret = None + for basename, value in items: + p = self.tmpdir.join(basename).new(ext=ext) + p.dirpath().ensure_dir() + source = Source(value) + source = u"\n".join(to_text(line) for line in source.lines) + p.write(source.strip().encode(encoding), "wb") + if ret is None: + ret = p + return ret + + def makefile(self, ext, *args, **kwargs): + r"""Create new file(s) in the testdir. + + :param str ext: The extension the file(s) should use, including the dot, e.g. `.py`. + :param list[str] args: All args will be treated as strings and joined using newlines. + The result will be written as contents to the file. The name of the + file will be based on the test function requesting this fixture. + :param kwargs: Each keyword is the name of a file, while the value of it will + be written as contents of the file. + + Examples: + + .. code-block:: python + + testdir.makefile(".txt", "line1", "line2") + + testdir.makefile(".ini", pytest="[pytest]\naddopts=-rs\n") + + """ + return self._makefile(ext, args, kwargs) + + def makeconftest(self, source): + """Write a contest.py file with 'source' as contents.""" + return self.makepyfile(conftest=source) + + def makeini(self, source): + """Write a tox.ini file with 'source' as contents.""" + return self.makefile(".ini", tox=source) + + def getinicfg(self, source): + """Return the pytest section from the tox.ini config file.""" + p = self.makeini(source) + return py.iniconfig.IniConfig(p)["pytest"] + + def makepyfile(self, *args, **kwargs): + """Shortcut for .makefile() with a .py extension.""" + return self._makefile(".py", args, kwargs) + + def maketxtfile(self, *args, **kwargs): + """Shortcut for .makefile() with a .txt extension.""" + return self._makefile(".txt", args, kwargs) + + def syspathinsert(self, path=None): + """Prepend a directory to sys.path, defaults to :py:attr:`tmpdir`. + + This is undone automatically when this object dies at the end of each + test. + """ + if path is None: + path = self.tmpdir + + self.monkeypatch.syspath_prepend(str(path)) + + def mkdir(self, name): + """Create a new (sub)directory.""" + return self.tmpdir.mkdir(name) + + def mkpydir(self, name): + """Create a new python package. + + This creates a (sub)directory with an empty ``__init__.py`` file so it + gets recognised as a python package. + + """ + p = self.mkdir(name) + p.ensure("__init__.py") + return p + + def copy_example(self, name=None): + import warnings + from _pytest.warning_types import PYTESTER_COPY_EXAMPLE + + warnings.warn(PYTESTER_COPY_EXAMPLE, stacklevel=2) + example_dir = self.request.config.getini("pytester_example_dir") + if example_dir is None: + raise ValueError("pytester_example_dir is unset, can't copy examples") + example_dir = self.request.config.rootdir.join(example_dir) + + for extra_element in self.request.node.iter_markers("pytester_example_path"): + assert extra_element.args + example_dir = example_dir.join(*extra_element.args) + + if name is None: + func_name = self.request.function.__name__ + maybe_dir = example_dir / func_name + maybe_file = example_dir / (func_name + ".py") + + if maybe_dir.isdir(): + example_path = maybe_dir + elif maybe_file.isfile(): + example_path = maybe_file + else: + raise LookupError( + "{} cant be found as module or package in {}".format( + func_name, example_dir.bestrelpath(self.request.config.rootdir) + ) + ) + else: + example_path = example_dir.join(name) + + if example_path.isdir() and not example_path.join("__init__.py").isfile(): + example_path.copy(self.tmpdir) + return self.tmpdir + elif example_path.isfile(): + result = self.tmpdir.join(example_path.basename) + example_path.copy(result) + return result + else: + raise LookupError( + 'example "{}" is not found as a file or directory'.format(example_path) + ) + + Session = Session + + def getnode(self, config, arg): + """Return the collection node of a file. + + :param config: :py:class:`_pytest.config.Config` instance, see + :py:meth:`parseconfig` and :py:meth:`parseconfigure` to create the + configuration + + :param arg: a :py:class:`py.path.local` instance of the file + + """ + session = Session(config) + assert "::" not in str(arg) + p = py.path.local(arg) + config.hook.pytest_sessionstart(session=session) + res = session.perform_collect([str(p)], genitems=False)[0] + config.hook.pytest_sessionfinish(session=session, exitstatus=EXIT_OK) + return res + + def getpathnode(self, path): + """Return the collection node of a file. + + This is like :py:meth:`getnode` but uses :py:meth:`parseconfigure` to + create the (configured) pytest Config instance. + + :param path: a :py:class:`py.path.local` instance of the file + + """ + config = self.parseconfigure(path) + session = Session(config) + x = session.fspath.bestrelpath(path) + config.hook.pytest_sessionstart(session=session) + res = session.perform_collect([x], genitems=False)[0] + config.hook.pytest_sessionfinish(session=session, exitstatus=EXIT_OK) + return res + + def genitems(self, colitems): + """Generate all test items from a collection node. + + This recurses into the collection node and returns a list of all the + test items contained within. + + """ + session = colitems[0].session + result = [] + for colitem in colitems: + result.extend(session.genitems(colitem)) + return result + + def runitem(self, source): + """Run the "test_func" Item. + + The calling test instance (class containing the test method) must + provide a ``.getrunner()`` method which should return a runner which + can run the test protocol for a single item, e.g. + :py:func:`_pytest.runner.runtestprotocol`. + + """ + # used from runner functional tests + item = self.getitem(source) + # the test class where we are called from wants to provide the runner + testclassinstance = self.request.instance + runner = testclassinstance.getrunner() + return runner(item) + + def inline_runsource(self, source, *cmdlineargs): + """Run a test module in process using ``pytest.main()``. + + This run writes "source" into a temporary file and runs + ``pytest.main()`` on it, returning a :py:class:`HookRecorder` instance + for the result. + + :param source: the source code of the test module + + :param cmdlineargs: any extra command line arguments to use + + :return: :py:class:`HookRecorder` instance of the result + + """ + p = self.makepyfile(source) + values = list(cmdlineargs) + [p] + return self.inline_run(*values) + + def inline_genitems(self, *args): + """Run ``pytest.main(['--collectonly'])`` in-process. + + Runs the :py:func:`pytest.main` function to run all of pytest inside + the test process itself like :py:meth:`inline_run`, but returns a + tuple of the collected items and a :py:class:`HookRecorder` instance. + + """ + rec = self.inline_run("--collect-only", *args) + items = [x.item for x in rec.getcalls("pytest_itemcollected")] + return items, rec + + def inline_run(self, *args, **kwargs): + """Run ``pytest.main()`` in-process, returning a HookRecorder. + + Runs the :py:func:`pytest.main` function to run all of pytest inside + the test process itself. This means it can return a + :py:class:`HookRecorder` instance which gives more detailed results + from that run than can be done by matching stdout/stderr from + :py:meth:`runpytest`. + + :param args: command line arguments to pass to :py:func:`pytest.main` + + :param plugins: (keyword-only) extra plugin instances the + ``pytest.main()`` instance should use + + :return: a :py:class:`HookRecorder` instance + """ + plugins = kwargs.pop("plugins", []) + no_reraise_ctrlc = kwargs.pop("no_reraise_ctrlc", None) + raise_on_kwargs(kwargs) + + finalizers = [] + try: + # Do not load user config (during runs only). + mp_run = MonkeyPatch() + for k, v in self._env_run_update.items(): + mp_run.setenv(k, v) + finalizers.append(mp_run.undo) + + # When running pytest inline any plugins active in the main test + # process are already imported. So this disables the warning which + # will trigger to say they can no longer be rewritten, which is + # fine as they have already been rewritten. + orig_warn = AssertionRewritingHook._warn_already_imported + + def revert_warn_already_imported(): + AssertionRewritingHook._warn_already_imported = orig_warn + + finalizers.append(revert_warn_already_imported) + AssertionRewritingHook._warn_already_imported = lambda *a: None + + # Any sys.module or sys.path changes done while running pytest + # inline should be reverted after the test run completes to avoid + # clashing with later inline tests run within the same pytest test, + # e.g. just because they use matching test module names. + finalizers.append(self.__take_sys_modules_snapshot().restore) + finalizers.append(SysPathsSnapshot().restore) + + # Important note: + # - our tests should not leave any other references/registrations + # laying around other than possibly loaded test modules + # referenced from sys.modules, as nothing will clean those up + # automatically + + rec = [] + + class Collect(object): + def pytest_configure(x, config): + rec.append(self.make_hook_recorder(config.pluginmanager)) + + plugins.append(Collect()) + ret = pytest.main(list(args), plugins=plugins) + if len(rec) == 1: + reprec = rec.pop() + else: + + class reprec(object): + pass + + reprec.ret = ret + + # typically we reraise keyboard interrupts from the child run + # because it's our user requesting interruption of the testing + if ret == EXIT_INTERRUPTED and not no_reraise_ctrlc: + calls = reprec.getcalls("pytest_keyboard_interrupt") + if calls and calls[-1].excinfo.type == KeyboardInterrupt: + raise KeyboardInterrupt() + return reprec + finally: + for finalizer in finalizers: + finalizer() + + def runpytest_inprocess(self, *args, **kwargs): + """Return result of running pytest in-process, providing a similar + interface to what self.runpytest() provides. + """ + syspathinsert = kwargs.pop("syspathinsert", False) + + if syspathinsert: + self.syspathinsert() + now = time.time() + capture = MultiCapture(Capture=SysCapture) + capture.start_capturing() + try: + try: + reprec = self.inline_run(*args, **kwargs) + except SystemExit as e: + + class reprec(object): + ret = e.args[0] + + except Exception: + traceback.print_exc() + + class reprec(object): + ret = 3 + + finally: + out, err = capture.readouterr() + capture.stop_capturing() + sys.stdout.write(out) + sys.stderr.write(err) + + res = RunResult(reprec.ret, out.split("\n"), err.split("\n"), time.time() - now) + res.reprec = reprec + return res + + def runpytest(self, *args, **kwargs): + """Run pytest inline or in a subprocess, depending on the command line + option "--runpytest" and return a :py:class:`RunResult`. + + """ + args = self._ensure_basetemp(args) + return self._runpytest_method(*args, **kwargs) + + def _ensure_basetemp(self, args): + args = list(args) + for x in args: + if safe_str(x).startswith("--basetemp"): + break + else: + args.append("--basetemp=%s" % self.tmpdir.dirpath("basetemp")) + return args + + def parseconfig(self, *args): + """Return a new pytest Config instance from given commandline args. + + This invokes the pytest bootstrapping code in _pytest.config to create + a new :py:class:`_pytest.core.PluginManager` and call the + pytest_cmdline_parse hook to create a new + :py:class:`_pytest.config.Config` instance. + + If :py:attr:`plugins` has been populated they should be plugin modules + to be registered with the PluginManager. + + """ + args = self._ensure_basetemp(args) + + import _pytest.config + + config = _pytest.config._prepareconfig(args, self.plugins) + # we don't know what the test will do with this half-setup config + # object and thus we make sure it gets unconfigured properly in any + # case (otherwise capturing could still be active, for example) + self.request.addfinalizer(config._ensure_unconfigure) + return config + + def parseconfigure(self, *args): + """Return a new pytest configured Config instance. + + This returns a new :py:class:`_pytest.config.Config` instance like + :py:meth:`parseconfig`, but also calls the pytest_configure hook. + + """ + config = self.parseconfig(*args) + config._do_configure() + self.request.addfinalizer(config._ensure_unconfigure) + return config + + def getitem(self, source, funcname="test_func"): + """Return the test item for a test function. + + This writes the source to a python file and runs pytest's collection on + the resulting module, returning the test item for the requested + function name. + + :param source: the module source + + :param funcname: the name of the test function for which to return a + test item + + """ + items = self.getitems(source) + for item in items: + if item.name == funcname: + return item + assert 0, "%r item not found in module:\n%s\nitems: %s" % ( + funcname, + source, + items, + ) + + def getitems(self, source): + """Return all test items collected from the module. + + This writes the source to a python file and runs pytest's collection on + the resulting module, returning all test items contained within. + + """ + modcol = self.getmodulecol(source) + return self.genitems([modcol]) + + def getmodulecol(self, source, configargs=(), withinit=False): + """Return the module collection node for ``source``. + + This writes ``source`` to a file using :py:meth:`makepyfile` and then + runs the pytest collection on it, returning the collection node for the + test module. + + :param source: the source code of the module to collect + + :param configargs: any extra arguments to pass to + :py:meth:`parseconfigure` + + :param withinit: whether to also write an ``__init__.py`` file to the + same directory to ensure it is a package + + """ + if isinstance(source, Path): + path = self.tmpdir.join(str(source)) + assert not withinit, "not supported for paths" + else: + kw = {self.request.function.__name__: Source(source).strip()} + path = self.makepyfile(**kw) + if withinit: + self.makepyfile(__init__="#") + self.config = config = self.parseconfigure(path, *configargs) + return self.getnode(config, path) + + def collect_by_name(self, modcol, name): + """Return the collection node for name from the module collection. + + This will search a module collection node for a collection node + matching the given name. + + :param modcol: a module collection node; see :py:meth:`getmodulecol` + + :param name: the name of the node to return + + """ + if modcol not in self._mod_collections: + self._mod_collections[modcol] = list(modcol.collect()) + for colitem in self._mod_collections[modcol]: + if colitem.name == name: + return colitem + + def popen( + self, + cmdargs, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + stdin=CLOSE_STDIN, + **kw + ): + """Invoke subprocess.Popen. + + This calls subprocess.Popen making sure the current working directory + is in the PYTHONPATH. + + You probably want to use :py:meth:`run` instead. + + """ + env = os.environ.copy() + env["PYTHONPATH"] = os.pathsep.join( + filter(None, [os.getcwd(), env.get("PYTHONPATH", "")]) + ) + env.update(self._env_run_update) + kw["env"] = env + + if stdin is Testdir.CLOSE_STDIN: + kw["stdin"] = subprocess.PIPE + elif isinstance(stdin, bytes): + kw["stdin"] = subprocess.PIPE + else: + kw["stdin"] = stdin + + popen = subprocess.Popen(cmdargs, stdout=stdout, stderr=stderr, **kw) + if stdin is Testdir.CLOSE_STDIN: + popen.stdin.close() + elif isinstance(stdin, bytes): + popen.stdin.write(stdin) + + return popen + + def run(self, *cmdargs, **kwargs): + """Run a command with arguments. + + Run a process using subprocess.Popen saving the stdout and stderr. + + :param args: the sequence of arguments to pass to `subprocess.Popen()` + :param timeout: the period in seconds after which to timeout and raise + :py:class:`Testdir.TimeoutExpired` + :param stdin: optional standard input. Bytes are being send, closing + the pipe, otherwise it is passed through to ``popen``. + Defaults to ``CLOSE_STDIN``, which translates to using a pipe + (``subprocess.PIPE``) that gets closed. + + Returns a :py:class:`RunResult`. + + """ + __tracebackhide__ = True + + timeout = kwargs.pop("timeout", None) + stdin = kwargs.pop("stdin", Testdir.CLOSE_STDIN) + raise_on_kwargs(kwargs) + + cmdargs = [ + str(arg) if isinstance(arg, py.path.local) else arg for arg in cmdargs + ] + p1 = self.tmpdir.join("stdout") + p2 = self.tmpdir.join("stderr") + print("running:", *cmdargs) + print(" in:", py.path.local()) + f1 = codecs.open(str(p1), "w", encoding="utf8") + f2 = codecs.open(str(p2), "w", encoding="utf8") + try: + now = time.time() + popen = self.popen( + cmdargs, + stdin=stdin, + stdout=f1, + stderr=f2, + close_fds=(sys.platform != "win32"), + ) + if isinstance(stdin, bytes): + popen.stdin.close() + + def handle_timeout(): + __tracebackhide__ = True + + timeout_message = ( + "{seconds} second timeout expired running:" + " {command}".format(seconds=timeout, command=cmdargs) + ) + + popen.kill() + popen.wait() + raise self.TimeoutExpired(timeout_message) + + if timeout is None: + ret = popen.wait() + elif six.PY3: + try: + ret = popen.wait(timeout) + except subprocess.TimeoutExpired: + handle_timeout() + else: + end = time.time() + timeout + + resolution = min(0.1, timeout / 10) + + while True: + ret = popen.poll() + if ret is not None: + break + + if time.time() > end: + handle_timeout() + + time.sleep(resolution) + finally: + f1.close() + f2.close() + f1 = codecs.open(str(p1), "r", encoding="utf8") + f2 = codecs.open(str(p2), "r", encoding="utf8") + try: + out = f1.read().splitlines() + err = f2.read().splitlines() + finally: + f1.close() + f2.close() + self._dump_lines(out, sys.stdout) + self._dump_lines(err, sys.stderr) + return RunResult(ret, out, err, time.time() - now) + + def _dump_lines(self, lines, fp): + try: + for line in lines: + print(line, file=fp) + except UnicodeEncodeError: + print("couldn't print to %s because of encoding" % (fp,)) + + def _getpytestargs(self): + return sys.executable, "-mpytest" + + def runpython(self, script): + """Run a python script using sys.executable as interpreter. + + Returns a :py:class:`RunResult`. + + """ + return self.run(sys.executable, script) + + def runpython_c(self, command): + """Run python -c "command", return a :py:class:`RunResult`.""" + return self.run(sys.executable, "-c", command) + + def runpytest_subprocess(self, *args, **kwargs): + """Run pytest as a subprocess with given arguments. + + Any plugins added to the :py:attr:`plugins` list will be added using the + ``-p`` command line option. Additionally ``--basetemp`` is used to put + any temporary files and directories in a numbered directory prefixed + with "runpytest-" to not conflict with the normal numbered pytest + location for temporary files and directories. + + :param args: the sequence of arguments to pass to the pytest subprocess + :param timeout: the period in seconds after which to timeout and raise + :py:class:`Testdir.TimeoutExpired` + + Returns a :py:class:`RunResult`. + """ + __tracebackhide__ = True + timeout = kwargs.pop("timeout", None) + raise_on_kwargs(kwargs) + + p = py.path.local.make_numbered_dir( + prefix="runpytest-", keep=None, rootdir=self.tmpdir + ) + args = ("--basetemp=%s" % p,) + args + plugins = [x for x in self.plugins if isinstance(x, str)] + if plugins: + args = ("-p", plugins[0]) + args + args = self._getpytestargs() + args + return self.run(*args, timeout=timeout) + + def spawn_pytest(self, string, expect_timeout=10.0): + """Run pytest using pexpect. + + This makes sure to use the right pytest and sets up the temporary + directory locations. + + The pexpect child is returned. + + """ + basetemp = self.tmpdir.mkdir("temp-pexpect") + invoke = " ".join(map(str, self._getpytestargs())) + cmd = "%s --basetemp=%s %s" % (invoke, basetemp, string) + return self.spawn(cmd, expect_timeout=expect_timeout) + + def spawn(self, cmd, expect_timeout=10.0): + """Run a command using pexpect. + + The pexpect child is returned. + + """ + pexpect = pytest.importorskip("pexpect", "3.0") + if hasattr(sys, "pypy_version_info") and "64" in platform.machine(): + pytest.skip("pypy-64 bit not supported") + if sys.platform.startswith("freebsd"): + pytest.xfail("pexpect does not work reliably on freebsd") + logfile = self.tmpdir.join("spawn.out").open("wb") + + # Do not load user config. + env = os.environ.copy() + env.update(self._env_run_update) + + child = pexpect.spawn(cmd, logfile=logfile, env=env) + self.request.addfinalizer(logfile.close) + child.timeout = expect_timeout + return child + + +def getdecoded(out): + try: + return out.decode("utf-8") + except UnicodeDecodeError: + return "INTERNAL not-utf8-decodeable, truncated string:\n%s" % (saferepr(out),) + + +class LineComp(object): + def __init__(self): + self.stringio = py.io.TextIO() + + def assert_contains_lines(self, lines2): + """Assert that lines2 are contained (linearly) in lines1. + + Return a list of extralines found. + + """ + __tracebackhide__ = True + val = self.stringio.getvalue() + self.stringio.truncate(0) + self.stringio.seek(0) + lines1 = val.split("\n") + return LineMatcher(lines1).fnmatch_lines(lines2) + + +class LineMatcher(object): + """Flexible matching of text. + + This is a convenience class to test large texts like the output of + commands. + + The constructor takes a list of lines without their trailing newlines, i.e. + ``text.splitlines()``. + + """ + + def __init__(self, lines): + self.lines = lines + self._log_output = [] + + def str(self): + """Return the entire original text.""" + return "\n".join(self.lines) + + def _getlines(self, lines2): + if isinstance(lines2, str): + lines2 = Source(lines2) + if isinstance(lines2, Source): + lines2 = lines2.strip().lines + return lines2 + + def fnmatch_lines_random(self, lines2): + """Check lines exist in the output using in any order. + + Lines are checked using ``fnmatch.fnmatch``. The argument is a list of + lines which have to occur in the output, in any order. + + """ + self._match_lines_random(lines2, fnmatch) + + def re_match_lines_random(self, lines2): + """Check lines exist in the output using ``re.match``, in any order. + + The argument is a list of lines which have to occur in the output, in + any order. + + """ + self._match_lines_random(lines2, lambda name, pat: re.match(pat, name)) + + def _match_lines_random(self, lines2, match_func): + """Check lines exist in the output. + + The argument is a list of lines which have to occur in the output, in + any order. Each line can contain glob whildcards. + + """ + lines2 = self._getlines(lines2) + for line in lines2: + for x in self.lines: + if line == x or match_func(x, line): + self._log("matched: ", repr(line)) + break + else: + self._log("line %r not found in output" % line) + raise ValueError(self._log_text) + + def get_lines_after(self, fnline): + """Return all lines following the given line in the text. + + The given line can contain glob wildcards. + + """ + for i, line in enumerate(self.lines): + if fnline == line or fnmatch(line, fnline): + return self.lines[i + 1 :] + raise ValueError("line %r not found in output" % fnline) + + def _log(self, *args): + self._log_output.append(" ".join(str(x) for x in args)) + + @property + def _log_text(self): + return "\n".join(self._log_output) + + def fnmatch_lines(self, lines2): + """Search captured text for matching lines using ``fnmatch.fnmatch``. + + The argument is a list of lines which have to match and can use glob + wildcards. If they do not match a pytest.fail() is called. The + matches and non-matches are also printed on stdout. + + """ + __tracebackhide__ = True + self._match_lines(lines2, fnmatch, "fnmatch") + + def re_match_lines(self, lines2): + """Search captured text for matching lines using ``re.match``. + + The argument is a list of lines which have to match using ``re.match``. + If they do not match a pytest.fail() is called. + + The matches and non-matches are also printed on stdout. + + """ + __tracebackhide__ = True + self._match_lines(lines2, lambda name, pat: re.match(pat, name), "re.match") + + def _match_lines(self, lines2, match_func, match_nickname): + """Underlying implementation of ``fnmatch_lines`` and ``re_match_lines``. + + :param list[str] lines2: list of string patterns to match. The actual + format depends on ``match_func`` + :param match_func: a callable ``match_func(line, pattern)`` where line + is the captured line from stdout/stderr and pattern is the matching + pattern + :param str match_nickname: the nickname for the match function that + will be logged to stdout when a match occurs + + """ + assert isinstance(lines2, Sequence) + lines2 = self._getlines(lines2) + lines1 = self.lines[:] + nextline = None + extralines = [] + __tracebackhide__ = True + for line in lines2: + nomatchprinted = False + while lines1: + nextline = lines1.pop(0) + if line == nextline: + self._log("exact match:", repr(line)) + break + elif match_func(nextline, line): + self._log("%s:" % match_nickname, repr(line)) + self._log(" with:", repr(nextline)) + break + else: + if not nomatchprinted: + self._log("nomatch:", repr(line)) + nomatchprinted = True + self._log(" and:", repr(nextline)) + extralines.append(nextline) + else: + self._log("remains unmatched: %r" % (line,)) + pytest.fail(self._log_text) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/python.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/python.py new file mode 100644 index 0000000000000000000000000000000000000000..5f1e6885be337d7d95942a84e7eb93759fa682ce --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/python.py @@ -0,0 +1,1480 @@ +# -*- coding: utf-8 -*- +""" Python test discovery, setup and run of test functions. """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import collections +import fnmatch +import inspect +import os +import sys +import warnings +from functools import partial +from textwrap import dedent + +import py +import six + +import _pytest +from _pytest import deprecated +from _pytest import fixtures +from _pytest import nodes +from _pytest._code import filter_traceback +from _pytest.compat import ascii_escaped +from _pytest.compat import enum +from _pytest.compat import get_default_arg_names +from _pytest.compat import get_real_func +from _pytest.compat import getfslineno +from _pytest.compat import getimfunc +from _pytest.compat import getlocation +from _pytest.compat import is_generator +from _pytest.compat import isclass +from _pytest.compat import isfunction +from _pytest.compat import NOTSET +from _pytest.compat import REGEX_TYPE +from _pytest.compat import safe_getattr +from _pytest.compat import safe_isclass +from _pytest.compat import safe_str +from _pytest.compat import STRING_TYPES +from _pytest.config import hookimpl +from _pytest.main import FSHookProxy +from _pytest.mark import MARK_GEN +from _pytest.mark.structures import get_unpacked_marks +from _pytest.mark.structures import normalize_mark_list +from _pytest.outcomes import fail +from _pytest.outcomes import skip +from _pytest.pathlib import parts +from _pytest.warning_types import PytestCollectionWarning +from _pytest.warning_types import PytestUnhandledCoroutineWarning + + +def pyobj_property(name): + def get(self): + node = self.getparent(getattr(__import__("pytest"), name)) + if node is not None: + return node.obj + + doc = "python %s object this node was collected from (can be None)." % ( + name.lower(), + ) + return property(get, None, None, doc) + + +def pytest_addoption(parser): + group = parser.getgroup("general") + group.addoption( + "--fixtures", + "--funcargs", + action="store_true", + dest="showfixtures", + default=False, + help="show available fixtures, sorted by plugin appearance " + "(fixtures with leading '_' are only shown with '-v')", + ) + group.addoption( + "--fixtures-per-test", + action="store_true", + dest="show_fixtures_per_test", + default=False, + help="show fixtures per test", + ) + parser.addini( + "python_files", + type="args", + # NOTE: default is also used in AssertionRewritingHook. + default=["test_*.py", "*_test.py"], + help="glob-style file patterns for Python test module discovery", + ) + parser.addini( + "python_classes", + type="args", + default=["Test"], + help="prefixes or glob names for Python test class discovery", + ) + parser.addini( + "python_functions", + type="args", + default=["test"], + help="prefixes or glob names for Python test function and method discovery", + ) + parser.addini( + "disable_test_id_escaping_and_forfeit_all_rights_to_community_support", + type="bool", + default=False, + help="disable string escape non-ascii characters, might cause unwanted " + "side effects(use at your own risk)", + ) + + group.addoption( + "--import-mode", + default="prepend", + choices=["prepend", "append"], + dest="importmode", + help="prepend/append to sys.path when importing test modules, " + "default is to prepend.", + ) + + +def pytest_cmdline_main(config): + if config.option.showfixtures: + showfixtures(config) + return 0 + if config.option.show_fixtures_per_test: + show_fixtures_per_test(config) + return 0 + + +def pytest_generate_tests(metafunc): + # those alternative spellings are common - raise a specific error to alert + # the user + alt_spellings = ["parameterize", "parametrise", "parameterise"] + for mark_name in alt_spellings: + if metafunc.definition.get_closest_marker(mark_name): + msg = "{0} has '{1}' mark, spelling should be 'parametrize'" + fail(msg.format(metafunc.function.__name__, mark_name), pytrace=False) + for marker in metafunc.definition.iter_markers(name="parametrize"): + metafunc.parametrize(*marker.args, **marker.kwargs) + + +def pytest_configure(config): + config.addinivalue_line( + "markers", + "parametrize(argnames, argvalues): call a test function multiple " + "times passing in different arguments in turn. argvalues generally " + "needs to be a list of values if argnames specifies only one name " + "or a list of tuples of values if argnames specifies multiple names. " + "Example: @parametrize('arg1', [1,2]) would lead to two calls of the " + "decorated test function, one with arg1=1 and another with arg1=2." + "see https://docs.pytest.org/en/latest/parametrize.html for more info " + "and examples.", + ) + config.addinivalue_line( + "markers", + "usefixtures(fixturename1, fixturename2, ...): mark tests as needing " + "all of the specified fixtures. see " + "https://docs.pytest.org/en/latest/fixture.html#usefixtures ", + ) + + +@hookimpl(trylast=True) +def pytest_pyfunc_call(pyfuncitem): + testfunction = pyfuncitem.obj + iscoroutinefunction = getattr(inspect, "iscoroutinefunction", None) + if iscoroutinefunction is not None and iscoroutinefunction(testfunction): + msg = "Coroutine functions are not natively supported and have been skipped.\n" + msg += "You need to install a suitable plugin for your async framework, for example:\n" + msg += " - pytest-asyncio\n" + msg += " - pytest-trio\n" + msg += " - pytest-tornasync" + warnings.warn(PytestUnhandledCoroutineWarning(msg.format(pyfuncitem.nodeid))) + skip(msg="coroutine function and no async plugin installed (see warnings)") + funcargs = pyfuncitem.funcargs + testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames} + testfunction(**testargs) + return True + + +def pytest_collect_file(path, parent): + ext = path.ext + if ext == ".py": + if not parent.session.isinitpath(path): + if not path_matches_patterns( + path, parent.config.getini("python_files") + ["__init__.py"] + ): + return + ihook = parent.session.gethookproxy(path) + return ihook.pytest_pycollect_makemodule(path=path, parent=parent) + + +def path_matches_patterns(path, patterns): + """Returns True if the given py.path.local matches one of the patterns in the list of globs given""" + return any(path.fnmatch(pattern) for pattern in patterns) + + +def pytest_pycollect_makemodule(path, parent): + if path.basename == "__init__.py": + return Package(path, parent) + return Module(path, parent) + + +@hookimpl(hookwrapper=True) +def pytest_pycollect_makeitem(collector, name, obj): + outcome = yield + res = outcome.get_result() + if res is not None: + return + # nothing was collected elsewhere, let's do it here + if safe_isclass(obj): + if collector.istestclass(obj, name): + outcome.force_result(Class(name, parent=collector)) + elif collector.istestfunction(obj, name): + # mock seems to store unbound methods (issue473), normalize it + obj = getattr(obj, "__func__", obj) + # We need to try and unwrap the function if it's a functools.partial + # or a funtools.wrapped. + # We musn't if it's been wrapped with mock.patch (python 2 only) + if not (isfunction(obj) or isfunction(get_real_func(obj))): + filename, lineno = getfslineno(obj) + warnings.warn_explicit( + message=PytestCollectionWarning( + "cannot collect %r because it is not a function." % name + ), + category=None, + filename=str(filename), + lineno=lineno + 1, + ) + elif getattr(obj, "__test__", True): + if is_generator(obj): + res = Function(name, parent=collector) + reason = deprecated.YIELD_TESTS.format(name=name) + res.add_marker(MARK_GEN.xfail(run=False, reason=reason)) + res.warn(PytestCollectionWarning(reason)) + else: + res = list(collector._genfunctions(name, obj)) + outcome.force_result(res) + + +def pytest_make_parametrize_id(config, val, argname=None): + return None + + +class PyobjContext(object): + module = pyobj_property("Module") + cls = pyobj_property("Class") + instance = pyobj_property("Instance") + + +class PyobjMixin(PyobjContext): + _ALLOW_MARKERS = True + + def __init__(self, *k, **kw): + super(PyobjMixin, self).__init__(*k, **kw) + + @property + def obj(self): + """Underlying Python object.""" + obj = getattr(self, "_obj", None) + if obj is None: + self._obj = obj = self._getobj() + # XXX evil hack + # used to avoid Instance collector marker duplication + if self._ALLOW_MARKERS: + self.own_markers.extend(get_unpacked_marks(self.obj)) + return obj + + @obj.setter + def obj(self, value): + self._obj = value + + def _getobj(self): + """Gets the underlying Python object. May be overwritten by subclasses.""" + return getattr(self.parent.obj, self.name) + + def getmodpath(self, stopatmodule=True, includemodule=False): + """ return python path relative to the containing module. """ + chain = self.listchain() + chain.reverse() + parts = [] + for node in chain: + if isinstance(node, Instance): + continue + name = node.name + if isinstance(node, Module): + name = os.path.splitext(name)[0] + if stopatmodule: + if includemodule: + parts.append(name) + break + parts.append(name) + parts.reverse() + s = ".".join(parts) + return s.replace(".[", "[") + + def reportinfo(self): + # XXX caching? + obj = self.obj + compat_co_firstlineno = getattr(obj, "compat_co_firstlineno", None) + if isinstance(compat_co_firstlineno, int): + # nose compatibility + fspath = sys.modules[obj.__module__].__file__ + if fspath.endswith(".pyc"): + fspath = fspath[:-1] + lineno = compat_co_firstlineno + else: + fspath, lineno = getfslineno(obj) + modpath = self.getmodpath() + assert isinstance(lineno, int) + return fspath, lineno, modpath + + +class PyCollector(PyobjMixin, nodes.Collector): + def funcnamefilter(self, name): + return self._matches_prefix_or_glob_option("python_functions", name) + + def isnosetest(self, obj): + """ Look for the __test__ attribute, which is applied by the + @nose.tools.istest decorator + """ + # We explicitly check for "is True" here to not mistakenly treat + # classes with a custom __getattr__ returning something truthy (like a + # function) as test classes. + return safe_getattr(obj, "__test__", False) is True + + def classnamefilter(self, name): + return self._matches_prefix_or_glob_option("python_classes", name) + + def istestfunction(self, obj, name): + if self.funcnamefilter(name) or self.isnosetest(obj): + if isinstance(obj, staticmethod): + # static methods need to be unwrapped + obj = safe_getattr(obj, "__func__", False) + return ( + safe_getattr(obj, "__call__", False) + and fixtures.getfixturemarker(obj) is None + ) + else: + return False + + def istestclass(self, obj, name): + return self.classnamefilter(name) or self.isnosetest(obj) + + def _matches_prefix_or_glob_option(self, option_name, name): + """ + checks if the given name matches the prefix or glob-pattern defined + in ini configuration. + """ + for option in self.config.getini(option_name): + if name.startswith(option): + return True + # check that name looks like a glob-string before calling fnmatch + # because this is called for every name in each collected module, + # and fnmatch is somewhat expensive to call + elif ("*" in option or "?" in option or "[" in option) and fnmatch.fnmatch( + name, option + ): + return True + return False + + def collect(self): + if not getattr(self.obj, "__test__", True): + return [] + + # NB. we avoid random getattrs and peek in the __dict__ instead + # (XXX originally introduced from a PyPy need, still true?) + dicts = [getattr(self.obj, "__dict__", {})] + for basecls in inspect.getmro(self.obj.__class__): + dicts.append(basecls.__dict__) + seen = {} + values = [] + for dic in dicts: + for name, obj in list(dic.items()): + if name in seen: + continue + seen[name] = True + res = self._makeitem(name, obj) + if res is None: + continue + if not isinstance(res, list): + res = [res] + values.extend(res) + values.sort(key=lambda item: item.reportinfo()[:2]) + return values + + def _makeitem(self, name, obj): + # assert self.ihook.fspath == self.fspath, self + return self.ihook.pytest_pycollect_makeitem(collector=self, name=name, obj=obj) + + def _genfunctions(self, name, funcobj): + module = self.getparent(Module).obj + clscol = self.getparent(Class) + cls = clscol and clscol.obj or None + fm = self.session._fixturemanager + + definition = FunctionDefinition(name=name, parent=self, callobj=funcobj) + fixtureinfo = fm.getfixtureinfo(definition, funcobj, cls) + + metafunc = Metafunc( + definition, fixtureinfo, self.config, cls=cls, module=module + ) + methods = [] + if hasattr(module, "pytest_generate_tests"): + methods.append(module.pytest_generate_tests) + if hasattr(cls, "pytest_generate_tests"): + methods.append(cls().pytest_generate_tests) + if methods: + self.ihook.pytest_generate_tests.call_extra( + methods, dict(metafunc=metafunc) + ) + else: + self.ihook.pytest_generate_tests(metafunc=metafunc) + + if not metafunc._calls: + yield Function(name, parent=self, fixtureinfo=fixtureinfo) + else: + # add funcargs() as fixturedefs to fixtureinfo.arg2fixturedefs + fixtures.add_funcarg_pseudo_fixture_def(self, metafunc, fm) + + # add_funcarg_pseudo_fixture_def may have shadowed some fixtures + # with direct parametrization, so make sure we update what the + # function really needs. + fixtureinfo.prune_dependency_tree() + + for callspec in metafunc._calls: + subname = "%s[%s]" % (name, callspec.id) + yield Function( + name=subname, + parent=self, + callspec=callspec, + callobj=funcobj, + fixtureinfo=fixtureinfo, + keywords={callspec.id: True}, + originalname=name, + ) + + +class Module(nodes.File, PyCollector): + """ Collector for test classes and functions. """ + + def _getobj(self): + return self._importtestmodule() + + def collect(self): + self._inject_setup_module_fixture() + self._inject_setup_function_fixture() + self.session._fixturemanager.parsefactories(self) + return super(Module, self).collect() + + def _inject_setup_module_fixture(self): + """Injects a hidden autouse, module scoped fixture into the collected module object + that invokes setUpModule/tearDownModule if either or both are available. + + Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with + other fixtures (#517). + """ + setup_module = _get_non_fixture_func(self.obj, "setUpModule") + if setup_module is None: + setup_module = _get_non_fixture_func(self.obj, "setup_module") + + teardown_module = _get_non_fixture_func(self.obj, "tearDownModule") + if teardown_module is None: + teardown_module = _get_non_fixture_func(self.obj, "teardown_module") + + if setup_module is None and teardown_module is None: + return + + @fixtures.fixture(autouse=True, scope="module") + def xunit_setup_module_fixture(request): + if setup_module is not None: + _call_with_optional_argument(setup_module, request.module) + yield + if teardown_module is not None: + _call_with_optional_argument(teardown_module, request.module) + + self.obj.__pytest_setup_module = xunit_setup_module_fixture + + def _inject_setup_function_fixture(self): + """Injects a hidden autouse, function scoped fixture into the collected module object + that invokes setup_function/teardown_function if either or both are available. + + Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with + other fixtures (#517). + """ + setup_function = _get_non_fixture_func(self.obj, "setup_function") + teardown_function = _get_non_fixture_func(self.obj, "teardown_function") + if setup_function is None and teardown_function is None: + return + + @fixtures.fixture(autouse=True, scope="function") + def xunit_setup_function_fixture(request): + if request.instance is not None: + # in this case we are bound to an instance, so we need to let + # setup_method handle this + yield + return + if setup_function is not None: + _call_with_optional_argument(setup_function, request.function) + yield + if teardown_function is not None: + _call_with_optional_argument(teardown_function, request.function) + + self.obj.__pytest_setup_function = xunit_setup_function_fixture + + def _importtestmodule(self): + # we assume we are only called once per module + importmode = self.config.getoption("--import-mode") + try: + mod = self.fspath.pyimport(ensuresyspath=importmode) + except SyntaxError: + raise self.CollectError( + _pytest._code.ExceptionInfo.from_current().getrepr(style="short") + ) + except self.fspath.ImportMismatchError: + e = sys.exc_info()[1] + raise self.CollectError( + "import file mismatch:\n" + "imported module %r has this __file__ attribute:\n" + " %s\n" + "which is not the same as the test file we want to collect:\n" + " %s\n" + "HINT: remove __pycache__ / .pyc files and/or use a " + "unique basename for your test file modules" % e.args + ) + except ImportError: + from _pytest._code.code import ExceptionInfo + + exc_info = ExceptionInfo.from_current() + if self.config.getoption("verbose") < 2: + exc_info.traceback = exc_info.traceback.filter(filter_traceback) + exc_repr = ( + exc_info.getrepr(style="short") + if exc_info.traceback + else exc_info.exconly() + ) + formatted_tb = safe_str(exc_repr) + raise self.CollectError( + "ImportError while importing test module '{fspath}'.\n" + "Hint: make sure your test modules/packages have valid Python names.\n" + "Traceback:\n" + "{traceback}".format(fspath=self.fspath, traceback=formatted_tb) + ) + except _pytest.runner.Skipped as e: + if e.allow_module_level: + raise + raise self.CollectError( + "Using pytest.skip outside of a test is not allowed. " + "To decorate a test function, use the @pytest.mark.skip " + "or @pytest.mark.skipif decorators instead, and to skip a " + "module use `pytestmark = pytest.mark.{skip,skipif}." + ) + self.config.pluginmanager.consider_module(mod) + return mod + + +class Package(Module): + def __init__(self, fspath, parent=None, config=None, session=None, nodeid=None): + session = parent.session + nodes.FSCollector.__init__( + self, fspath, parent=parent, config=config, session=session, nodeid=nodeid + ) + self.name = fspath.dirname + self.trace = session.trace + self._norecursepatterns = session._norecursepatterns + self.fspath = fspath + + def setup(self): + # not using fixtures to call setup_module here because autouse fixtures + # from packages are not called automatically (#4085) + setup_module = _get_non_fixture_func(self.obj, "setUpModule") + if setup_module is None: + setup_module = _get_non_fixture_func(self.obj, "setup_module") + if setup_module is not None: + _call_with_optional_argument(setup_module, self.obj) + + teardown_module = _get_non_fixture_func(self.obj, "tearDownModule") + if teardown_module is None: + teardown_module = _get_non_fixture_func(self.obj, "teardown_module") + if teardown_module is not None: + func = partial(_call_with_optional_argument, teardown_module, self.obj) + self.addfinalizer(func) + + def _recurse(self, dirpath): + if dirpath.basename == "__pycache__": + return False + ihook = self.gethookproxy(dirpath.dirpath()) + if ihook.pytest_ignore_collect(path=dirpath, config=self.config): + return + for pat in self._norecursepatterns: + if dirpath.check(fnmatch=pat): + return False + ihook = self.gethookproxy(dirpath) + ihook.pytest_collect_directory(path=dirpath, parent=self) + return True + + def gethookproxy(self, fspath): + # check if we have the common case of running + # hooks with all conftest.py filesall conftest.py + pm = self.config.pluginmanager + my_conftestmodules = pm._getconftestmodules(fspath) + remove_mods = pm._conftest_plugins.difference(my_conftestmodules) + if remove_mods: + # one or more conftests are not in use at this fspath + proxy = FSHookProxy(fspath, pm, remove_mods) + else: + # all plugis are active for this fspath + proxy = self.config.hook + return proxy + + def _collectfile(self, path, handle_dupes=True): + assert path.isfile(), "%r is not a file (isdir=%r, exists=%r, islink=%r)" % ( + path, + path.isdir(), + path.exists(), + path.islink(), + ) + ihook = self.gethookproxy(path) + if not self.isinitpath(path): + if ihook.pytest_ignore_collect(path=path, config=self.config): + return () + + if handle_dupes: + keepduplicates = self.config.getoption("keepduplicates") + if not keepduplicates: + duplicate_paths = self.config.pluginmanager._duplicatepaths + if path in duplicate_paths: + return () + else: + duplicate_paths.add(path) + + if self.fspath == path: # __init__.py + return [self] + + return ihook.pytest_collect_file(path=path, parent=self) + + def isinitpath(self, path): + return path in self.session._initialpaths + + def collect(self): + this_path = self.fspath.dirpath() + init_module = this_path.join("__init__.py") + if init_module.check(file=1) and path_matches_patterns( + init_module, self.config.getini("python_files") + ): + yield Module(init_module, self) + pkg_prefixes = set() + for path in this_path.visit(rec=self._recurse, bf=True, sort=True): + # We will visit our own __init__.py file, in which case we skip it. + is_file = path.isfile() + if is_file: + if path.basename == "__init__.py" and path.dirpath() == this_path: + continue + + parts_ = parts(path.strpath) + if any( + pkg_prefix in parts_ and pkg_prefix.join("__init__.py") != path + for pkg_prefix in pkg_prefixes + ): + continue + + if is_file: + for x in self._collectfile(path): + yield x + elif not path.isdir(): + # Broken symlink or invalid/missing file. + continue + elif path.join("__init__.py").check(file=1): + pkg_prefixes.add(path) + + +def _get_xunit_setup_teardown(holder, attr_name, param_obj=None): + """ + Return a callable to perform xunit-style setup or teardown if + the function exists in the ``holder`` object. + The ``param_obj`` parameter is the parameter which will be passed to the function + when the callable is called without arguments, defaults to the ``holder`` object. + Return ``None`` if a suitable callable is not found. + """ + # TODO: only needed because of Package! + param_obj = param_obj if param_obj is not None else holder + result = _get_non_fixture_func(holder, attr_name) + if result is not None: + arg_count = result.__code__.co_argcount + if inspect.ismethod(result): + arg_count -= 1 + if arg_count: + return lambda: result(param_obj) + else: + return result + + +def _call_with_optional_argument(func, arg): + """Call the given function with the given argument if func accepts one argument, otherwise + calls func without arguments""" + arg_count = func.__code__.co_argcount + if inspect.ismethod(func): + arg_count -= 1 + if arg_count: + func(arg) + else: + func() + + +def _get_non_fixture_func(obj, name): + """Return the attribute from the given object to be used as a setup/teardown + xunit-style function, but only if not marked as a fixture to + avoid calling it twice. + """ + meth = getattr(obj, name, None) + if fixtures.getfixturemarker(meth) is None: + return meth + + +class Class(PyCollector): + """ Collector for test methods. """ + + def collect(self): + if not safe_getattr(self.obj, "__test__", True): + return [] + if hasinit(self.obj): + self.warn( + PytestCollectionWarning( + "cannot collect test class %r because it has a " + "__init__ constructor (from: %s)" + % (self.obj.__name__, self.parent.nodeid) + ) + ) + return [] + elif hasnew(self.obj): + self.warn( + PytestCollectionWarning( + "cannot collect test class %r because it has a " + "__new__ constructor (from: %s)" + % (self.obj.__name__, self.parent.nodeid) + ) + ) + return [] + + self._inject_setup_class_fixture() + self._inject_setup_method_fixture() + + return [Instance(name="()", parent=self)] + + def _inject_setup_class_fixture(self): + """Injects a hidden autouse, class scoped fixture into the collected class object + that invokes setup_class/teardown_class if either or both are available. + + Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with + other fixtures (#517). + """ + setup_class = _get_non_fixture_func(self.obj, "setup_class") + teardown_class = getattr(self.obj, "teardown_class", None) + if setup_class is None and teardown_class is None: + return + + @fixtures.fixture(autouse=True, scope="class") + def xunit_setup_class_fixture(cls): + if setup_class is not None: + func = getimfunc(setup_class) + _call_with_optional_argument(func, self.obj) + yield + if teardown_class is not None: + func = getimfunc(teardown_class) + _call_with_optional_argument(func, self.obj) + + self.obj.__pytest_setup_class = xunit_setup_class_fixture + + def _inject_setup_method_fixture(self): + """Injects a hidden autouse, function scoped fixture into the collected class object + that invokes setup_method/teardown_method if either or both are available. + + Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with + other fixtures (#517). + """ + setup_method = _get_non_fixture_func(self.obj, "setup_method") + teardown_method = getattr(self.obj, "teardown_method", None) + if setup_method is None and teardown_method is None: + return + + @fixtures.fixture(autouse=True, scope="function") + def xunit_setup_method_fixture(self, request): + method = request.function + if setup_method is not None: + func = getattr(self, "setup_method") + _call_with_optional_argument(func, method) + yield + if teardown_method is not None: + func = getattr(self, "teardown_method") + _call_with_optional_argument(func, method) + + self.obj.__pytest_setup_method = xunit_setup_method_fixture + + +class Instance(PyCollector): + _ALLOW_MARKERS = False # hack, destroy later + # instances share the object with their parents in a way + # that duplicates markers instances if not taken out + # can be removed at node structure reorganization time + + def _getobj(self): + return self.parent.obj() + + def collect(self): + self.session._fixturemanager.parsefactories(self) + return super(Instance, self).collect() + + def newinstance(self): + self.obj = self._getobj() + return self.obj + + +class FunctionMixin(PyobjMixin): + """ mixin for the code common to Function and Generator. + """ + + def setup(self): + """ perform setup for this test function. """ + if isinstance(self.parent, Instance): + self.parent.newinstance() + self.obj = self._getobj() + + def _prunetraceback(self, excinfo): + if hasattr(self, "_obj") and not self.config.getoption("fulltrace", False): + code = _pytest._code.Code(get_real_func(self.obj)) + path, firstlineno = code.path, code.firstlineno + traceback = excinfo.traceback + ntraceback = traceback.cut(path=path, firstlineno=firstlineno) + if ntraceback == traceback: + ntraceback = ntraceback.cut(path=path) + if ntraceback == traceback: + ntraceback = ntraceback.filter(filter_traceback) + if not ntraceback: + ntraceback = traceback + + excinfo.traceback = ntraceback.filter() + # issue364: mark all but first and last frames to + # only show a single-line message for each frame + if self.config.getoption("tbstyle", "auto") == "auto": + if len(excinfo.traceback) > 2: + for entry in excinfo.traceback[1:-1]: + entry.set_repr_style("short") + + def repr_failure(self, excinfo, outerr=None): + assert outerr is None, "XXX outerr usage is deprecated" + style = self.config.getoption("tbstyle", "auto") + if style == "auto": + style = "long" + return self._repr_failure_py(excinfo, style=style) + + +def hasinit(obj): + init = getattr(obj, "__init__", None) + if init: + return init != object.__init__ + + +def hasnew(obj): + new = getattr(obj, "__new__", None) + if new: + return new != object.__new__ + + +class CallSpec2(object): + def __init__(self, metafunc): + self.metafunc = metafunc + self.funcargs = {} + self._idlist = [] + self.params = {} + self._globalid = NOTSET + self._globalparam = NOTSET + self._arg2scopenum = {} # used for sorting parametrized resources + self.marks = [] + self.indices = {} + + def copy(self): + cs = CallSpec2(self.metafunc) + cs.funcargs.update(self.funcargs) + cs.params.update(self.params) + cs.marks.extend(self.marks) + cs.indices.update(self.indices) + cs._arg2scopenum.update(self._arg2scopenum) + cs._idlist = list(self._idlist) + cs._globalid = self._globalid + cs._globalparam = self._globalparam + return cs + + def _checkargnotcontained(self, arg): + if arg in self.params or arg in self.funcargs: + raise ValueError("duplicate %r" % (arg,)) + + def getparam(self, name): + try: + return self.params[name] + except KeyError: + if self._globalparam is NOTSET: + raise ValueError(name) + return self._globalparam + + @property + def id(self): + return "-".join(map(str, filter(None, self._idlist))) + + def setmulti2(self, valtypes, argnames, valset, id, marks, scopenum, param_index): + for arg, val in zip(argnames, valset): + self._checkargnotcontained(arg) + valtype_for_arg = valtypes[arg] + getattr(self, valtype_for_arg)[arg] = val + self.indices[arg] = param_index + self._arg2scopenum[arg] = scopenum + self._idlist.append(id) + self.marks.extend(normalize_mark_list(marks)) + + def setall(self, funcargs, id, param): + for x in funcargs: + self._checkargnotcontained(x) + self.funcargs.update(funcargs) + if id is not NOTSET: + self._idlist.append(id) + if param is not NOTSET: + assert self._globalparam is NOTSET + self._globalparam = param + for arg in funcargs: + self._arg2scopenum[arg] = fixtures.scopenum_function + + +class Metafunc(fixtures.FuncargnamesCompatAttr): + """ + Metafunc objects are passed to the :func:`pytest_generate_tests <_pytest.hookspec.pytest_generate_tests>` hook. + They help to inspect a test function and to generate tests according to + test configuration or values specified in the class or module where a + test function is defined. + """ + + def __init__(self, definition, fixtureinfo, config, cls=None, module=None): + assert ( + isinstance(definition, FunctionDefinition) + or type(definition).__name__ == "DefinitionMock" + ) + self.definition = definition + + #: access to the :class:`_pytest.config.Config` object for the test session + self.config = config + + #: the module object where the test function is defined in. + self.module = module + + #: underlying python test function + self.function = definition.obj + + #: set of fixture names required by the test function + self.fixturenames = fixtureinfo.names_closure + + #: class object where the test function is defined in or ``None``. + self.cls = cls + + self._calls = [] + self._ids = set() + self._arg2fixturedefs = fixtureinfo.name2fixturedefs + + def parametrize(self, argnames, argvalues, indirect=False, ids=None, scope=None): + """ Add new invocations to the underlying test function using the list + of argvalues for the given argnames. Parametrization is performed + during the collection phase. If you need to setup expensive resources + see about setting indirect to do it rather at test setup time. + + :arg argnames: a comma-separated string denoting one or more argument + names, or a list/tuple of argument strings. + + :arg argvalues: The list of argvalues determines how often a + test is invoked with different argument values. If only one + argname was specified argvalues is a list of values. If N + argnames were specified, argvalues must be a list of N-tuples, + where each tuple-element specifies a value for its respective + argname. + + :arg indirect: The list of argnames or boolean. A list of arguments' + names (subset of argnames). If True the list contains all names from + the argnames. Each argvalue corresponding to an argname in this list will + be passed as request.param to its respective argname fixture + function so that it can perform more expensive setups during the + setup phase of a test rather than at collection time. + + :arg ids: list of string ids, or a callable. + If strings, each is corresponding to the argvalues so that they are + part of the test id. If None is given as id of specific test, the + automatically generated id for that argument will be used. + If callable, it should take one argument (a single argvalue) and return + a string or return None. If None, the automatically generated id for that + argument will be used. + If no ids are provided they will be generated automatically from + the argvalues. + + :arg scope: if specified it denotes the scope of the parameters. + The scope is used for grouping tests by parameter instances. + It will also override any fixture-function defined scope, allowing + to set a dynamic scope using test context or configuration. + """ + from _pytest.fixtures import scope2index + from _pytest.mark import ParameterSet + + argnames, parameters = ParameterSet._for_parametrize( + argnames, + argvalues, + self.function, + self.config, + function_definition=self.definition, + ) + del argvalues + + if scope is None: + scope = _find_parametrized_scope(argnames, self._arg2fixturedefs, indirect) + + self._validate_if_using_arg_names(argnames, indirect) + + arg_values_types = self._resolve_arg_value_types(argnames, indirect) + + ids = self._resolve_arg_ids(argnames, ids, parameters, item=self.definition) + + scopenum = scope2index( + scope, descr="parametrize() call in {}".format(self.function.__name__) + ) + + # create the new calls: if we are parametrize() multiple times (by applying the decorator + # more than once) then we accumulate those calls generating the cartesian product + # of all calls + newcalls = [] + for callspec in self._calls or [CallSpec2(self)]: + for param_index, (param_id, param_set) in enumerate(zip(ids, parameters)): + newcallspec = callspec.copy() + newcallspec.setmulti2( + arg_values_types, + argnames, + param_set.values, + param_id, + param_set.marks, + scopenum, + param_index, + ) + newcalls.append(newcallspec) + self._calls = newcalls + + def _resolve_arg_ids(self, argnames, ids, parameters, item): + """Resolves the actual ids for the given argnames, based on the ``ids`` parameter given + to ``parametrize``. + + :param List[str] argnames: list of argument names passed to ``parametrize()``. + :param ids: the ids parameter of the parametrized call (see docs). + :param List[ParameterSet] parameters: the list of parameter values, same size as ``argnames``. + :param Item item: the item that generated this parametrized call. + :rtype: List[str] + :return: the list of ids for each argname given + """ + from _pytest._io.saferepr import saferepr + + idfn = None + if callable(ids): + idfn = ids + ids = None + if ids: + func_name = self.function.__name__ + if len(ids) != len(parameters): + msg = "In {}: {} parameter sets specified, with different number of ids: {}" + fail(msg.format(func_name, len(parameters), len(ids)), pytrace=False) + for id_value in ids: + if id_value is not None and not isinstance(id_value, six.string_types): + msg = "In {}: ids must be list of strings, found: {} (type: {!r})" + fail( + msg.format(func_name, saferepr(id_value), type(id_value)), + pytrace=False, + ) + ids = idmaker(argnames, parameters, idfn, ids, self.config, item=item) + return ids + + def _resolve_arg_value_types(self, argnames, indirect): + """Resolves if each parametrized argument must be considered a parameter to a fixture or a "funcarg" + to the function, based on the ``indirect`` parameter of the parametrized() call. + + :param List[str] argnames: list of argument names passed to ``parametrize()``. + :param indirect: same ``indirect`` parameter of ``parametrize()``. + :rtype: Dict[str, str] + A dict mapping each arg name to either: + * "params" if the argname should be the parameter of a fixture of the same name. + * "funcargs" if the argname should be a parameter to the parametrized test function. + """ + valtypes = {} + if indirect is True: + valtypes = dict.fromkeys(argnames, "params") + elif indirect is False: + valtypes = dict.fromkeys(argnames, "funcargs") + elif isinstance(indirect, (tuple, list)): + valtypes = dict.fromkeys(argnames, "funcargs") + for arg in indirect: + if arg not in argnames: + fail( + "In {}: indirect fixture '{}' doesn't exist".format( + self.function.__name__, arg + ), + pytrace=False, + ) + valtypes[arg] = "params" + return valtypes + + def _validate_if_using_arg_names(self, argnames, indirect): + """ + Check if all argnames are being used, by default values, or directly/indirectly. + + :param List[str] argnames: list of argument names passed to ``parametrize()``. + :param indirect: same ``indirect`` parameter of ``parametrize()``. + :raise ValueError: if validation fails. + """ + default_arg_names = set(get_default_arg_names(self.function)) + func_name = self.function.__name__ + for arg in argnames: + if arg not in self.fixturenames: + if arg in default_arg_names: + fail( + "In {}: function already takes an argument '{}' with a default value".format( + func_name, arg + ), + pytrace=False, + ) + else: + if isinstance(indirect, (tuple, list)): + name = "fixture" if arg in indirect else "argument" + else: + name = "fixture" if indirect else "argument" + fail( + "In {}: function uses no {} '{}'".format(func_name, name, arg), + pytrace=False, + ) + + +def _find_parametrized_scope(argnames, arg2fixturedefs, indirect): + """Find the most appropriate scope for a parametrized call based on its arguments. + + When there's at least one direct argument, always use "function" scope. + + When a test function is parametrized and all its arguments are indirect + (e.g. fixtures), return the most narrow scope based on the fixtures used. + + Related to issue #1832, based on code posted by @Kingdread. + """ + from _pytest.fixtures import scopes + + if isinstance(indirect, (list, tuple)): + all_arguments_are_fixtures = len(indirect) == len(argnames) + else: + all_arguments_are_fixtures = bool(indirect) + + if all_arguments_are_fixtures: + fixturedefs = arg2fixturedefs or {} + used_scopes = [ + fixturedef[0].scope + for name, fixturedef in fixturedefs.items() + if name in argnames + ] + if used_scopes: + # Takes the most narrow scope from used fixtures + for scope in reversed(scopes): + if scope in used_scopes: + return scope + + return "function" + + +def _ascii_escaped_by_config(val, config): + if config is None: + escape_option = False + else: + escape_option = config.getini( + "disable_test_id_escaping_and_forfeit_all_rights_to_community_support" + ) + return val if escape_option else ascii_escaped(val) + + +def _idval(val, argname, idx, idfn, item, config): + if idfn: + try: + generated_id = idfn(val) + if generated_id is not None: + val = generated_id + except Exception as e: + # See issue https://github.com/pytest-dev/pytest/issues/2169 + msg = "{}: error raised while trying to determine id of parameter '{}' at position {}\n" + msg = msg.format(item.nodeid, argname, idx) + # we only append the exception type and message because on Python 2 reraise does nothing + msg += " {}: {}\n".format(type(e).__name__, e) + six.raise_from(ValueError(msg), e) + elif config: + hook_id = config.hook.pytest_make_parametrize_id( + config=config, val=val, argname=argname + ) + if hook_id: + return hook_id + + if isinstance(val, STRING_TYPES): + return _ascii_escaped_by_config(val, config) + elif val is None or isinstance(val, (float, int, bool)): + return str(val) + elif isinstance(val, REGEX_TYPE): + return ascii_escaped(val.pattern) + elif enum is not None and isinstance(val, enum.Enum): + return str(val) + elif (isclass(val) or isfunction(val)) and hasattr(val, "__name__"): + return val.__name__ + return str(argname) + str(idx) + + +def _idvalset(idx, parameterset, argnames, idfn, ids, item, config): + if parameterset.id is not None: + return parameterset.id + if ids is None or (idx >= len(ids) or ids[idx] is None): + this_id = [ + _idval(val, argname, idx, idfn, item=item, config=config) + for val, argname in zip(parameterset.values, argnames) + ] + return "-".join(this_id) + else: + return _ascii_escaped_by_config(ids[idx], config) + + +def idmaker(argnames, parametersets, idfn=None, ids=None, config=None, item=None): + ids = [ + _idvalset(valindex, parameterset, argnames, idfn, ids, config=config, item=item) + for valindex, parameterset in enumerate(parametersets) + ] + if len(set(ids)) != len(ids): + # The ids are not unique + duplicates = [testid for testid in ids if ids.count(testid) > 1] + counters = collections.defaultdict(lambda: 0) + for index, testid in enumerate(ids): + if testid in duplicates: + ids[index] = testid + str(counters[testid]) + counters[testid] += 1 + return ids + + +def show_fixtures_per_test(config): + from _pytest.main import wrap_session + + return wrap_session(config, _show_fixtures_per_test) + + +def _show_fixtures_per_test(config, session): + import _pytest.config + + session.perform_collect() + curdir = py.path.local() + tw = _pytest.config.create_terminal_writer(config) + verbose = config.getvalue("verbose") + + def get_best_relpath(func): + loc = getlocation(func, curdir) + return curdir.bestrelpath(loc) + + def write_fixture(fixture_def): + argname = fixture_def.argname + if verbose <= 0 and argname.startswith("_"): + return + if verbose > 0: + bestrel = get_best_relpath(fixture_def.func) + funcargspec = "{} -- {}".format(argname, bestrel) + else: + funcargspec = argname + tw.line(funcargspec, green=True) + fixture_doc = fixture_def.func.__doc__ + if fixture_doc: + write_docstring(tw, fixture_doc) + else: + tw.line(" no docstring available", red=True) + + def write_item(item): + try: + info = item._fixtureinfo + except AttributeError: + # doctests items have no _fixtureinfo attribute + return + if not info.name2fixturedefs: + # this test item does not use any fixtures + return + tw.line() + tw.sep("-", "fixtures used by {}".format(item.name)) + tw.sep("-", "({})".format(get_best_relpath(item.function))) + # dict key not used in loop but needed for sorting + for _, fixturedefs in sorted(info.name2fixturedefs.items()): + assert fixturedefs is not None + if not fixturedefs: + continue + # last item is expected to be the one used by the test item + write_fixture(fixturedefs[-1]) + + for session_item in session.items: + write_item(session_item) + + +def showfixtures(config): + from _pytest.main import wrap_session + + return wrap_session(config, _showfixtures_main) + + +def _showfixtures_main(config, session): + import _pytest.config + + session.perform_collect() + curdir = py.path.local() + tw = _pytest.config.create_terminal_writer(config) + verbose = config.getvalue("verbose") + + fm = session._fixturemanager + + available = [] + seen = set() + + for argname, fixturedefs in fm._arg2fixturedefs.items(): + assert fixturedefs is not None + if not fixturedefs: + continue + for fixturedef in fixturedefs: + loc = getlocation(fixturedef.func, curdir) + if (fixturedef.argname, loc) in seen: + continue + seen.add((fixturedef.argname, loc)) + available.append( + ( + len(fixturedef.baseid), + fixturedef.func.__module__, + curdir.bestrelpath(loc), + fixturedef.argname, + fixturedef, + ) + ) + + available.sort() + currentmodule = None + for baseid, module, bestrel, argname, fixturedef in available: + if currentmodule != module: + if not module.startswith("_pytest."): + tw.line() + tw.sep("-", "fixtures defined from %s" % (module,)) + currentmodule = module + if verbose <= 0 and argname[0] == "_": + continue + tw.write(argname, green=True) + if fixturedef.scope != "function": + tw.write(" [%s scope]" % fixturedef.scope, cyan=True) + if verbose > 0: + tw.write(" -- %s" % bestrel, yellow=True) + tw.write("\n") + loc = getlocation(fixturedef.func, curdir) + doc = fixturedef.func.__doc__ or "" + if doc: + write_docstring(tw, doc) + else: + tw.line(" %s: no docstring available" % (loc,), red=True) + tw.line() + + +def write_docstring(tw, doc, indent=" "): + doc = doc.rstrip() + if "\n" in doc: + firstline, rest = doc.split("\n", 1) + else: + firstline, rest = doc, "" + + if firstline.strip(): + tw.line(indent + firstline.strip()) + + if rest: + for line in dedent(rest).split("\n"): + tw.write(indent + line + "\n") + + +class Function(FunctionMixin, nodes.Item, fixtures.FuncargnamesCompatAttr): + """ a Function Item is responsible for setting up and executing a + Python test function. + """ + + # disable since functions handle it themselves + _ALLOW_MARKERS = False + + def __init__( + self, + name, + parent, + args=None, + config=None, + callspec=None, + callobj=NOTSET, + keywords=None, + session=None, + fixtureinfo=None, + originalname=None, + ): + super(Function, self).__init__(name, parent, config=config, session=session) + self._args = args + if callobj is not NOTSET: + self.obj = callobj + + self.keywords.update(self.obj.__dict__) + self.own_markers.extend(get_unpacked_marks(self.obj)) + if callspec: + self.callspec = callspec + # this is total hostile and a mess + # keywords are broken by design by now + # this will be redeemed later + for mark in callspec.marks: + # feel free to cry, this was broken for years before + # and keywords cant fix it per design + self.keywords[mark.name] = mark + self.own_markers.extend(normalize_mark_list(callspec.marks)) + if keywords: + self.keywords.update(keywords) + + # todo: this is a hell of a hack + # https://github.com/pytest-dev/pytest/issues/4569 + + self.keywords.update( + dict.fromkeys( + [ + mark.name + for mark in self.iter_markers() + if mark.name not in self.keywords + ], + True, + ) + ) + + if fixtureinfo is None: + fixtureinfo = self.session._fixturemanager.getfixtureinfo( + self, self.obj, self.cls, funcargs=True + ) + self._fixtureinfo = fixtureinfo + self.fixturenames = fixtureinfo.names_closure + self._initrequest() + + #: original function name, without any decorations (for example + #: parametrization adds a ``"[...]"`` suffix to function names). + #: + #: .. versionadded:: 3.0 + self.originalname = originalname + + def _initrequest(self): + self.funcargs = {} + self._request = fixtures.FixtureRequest(self) + + @property + def function(self): + "underlying python 'function' object" + return getimfunc(self.obj) + + def _getobj(self): + name = self.name + i = name.find("[") # parametrization + if i != -1: + name = name[:i] + return getattr(self.parent.obj, name) + + @property + def _pyfuncitem(self): + "(compatonly) for code expecting pytest-2.2 style request objects" + return self + + def runtest(self): + """ execute the underlying test function. """ + self.ihook.pytest_pyfunc_call(pyfuncitem=self) + + def setup(self): + super(Function, self).setup() + fixtures.fillfixtures(self) + + +class FunctionDefinition(Function): + """ + internal hack until we get actual definition nodes instead of the + crappy metafunc hack + """ + + def runtest(self): + raise RuntimeError("function definitions are not supposed to be used") + + setup = runtest diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/python_api.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/python_api.py new file mode 100644 index 0000000000000000000000000000000000000000..df09aa32d8ffc6646686d26a296dd59c58197d3f --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/python_api.py @@ -0,0 +1,743 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import + +import math +import pprint +import sys +import warnings +from decimal import Decimal +from numbers import Number + +from more_itertools.more import always_iterable +from six.moves import filterfalse +from six.moves import zip + +import _pytest._code +from _pytest import deprecated +from _pytest.compat import isclass +from _pytest.compat import Iterable +from _pytest.compat import Mapping +from _pytest.compat import Sized +from _pytest.compat import STRING_TYPES +from _pytest.outcomes import fail + +BASE_TYPE = (type, STRING_TYPES) + + +def _cmp_raises_type_error(self, other): + """__cmp__ implementation which raises TypeError. Used + by Approx base classes to implement only == and != and raise a + TypeError for other comparisons. + + Needed in Python 2 only, Python 3 all it takes is not implementing the + other operators at all. + """ + __tracebackhide__ = True + raise TypeError( + "Comparison operators other than == and != not supported by approx objects" + ) + + +def _non_numeric_type_error(value, at): + at_str = " at {}".format(at) if at else "" + return TypeError( + "cannot make approximate comparisons to non-numeric values: {!r} {}".format( + value, at_str + ) + ) + + +# builtin pytest.approx helper + + +class ApproxBase(object): + """ + Provide shared utilities for making approximate comparisons between numbers + or sequences of numbers. + """ + + # Tell numpy to use our `__eq__` operator instead of its. + __array_ufunc__ = None + __array_priority__ = 100 + + def __init__(self, expected, rel=None, abs=None, nan_ok=False): + __tracebackhide__ = True + self.expected = expected + self.abs = abs + self.rel = rel + self.nan_ok = nan_ok + self._check_type() + + def __repr__(self): + raise NotImplementedError + + def __eq__(self, actual): + return all( + a == self._approx_scalar(x) for a, x in self._yield_comparisons(actual) + ) + + __hash__ = None + + def __ne__(self, actual): + return not (actual == self) + + if sys.version_info[0] == 2: + __cmp__ = _cmp_raises_type_error + + def _approx_scalar(self, x): + return ApproxScalar(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok) + + def _yield_comparisons(self, actual): + """ + Yield all the pairs of numbers to be compared. This is used to + implement the `__eq__` method. + """ + raise NotImplementedError + + def _check_type(self): + """ + Raise a TypeError if the expected value is not a valid type. + """ + # This is only a concern if the expected value is a sequence. In every + # other case, the approx() function ensures that the expected value has + # a numeric type. For this reason, the default is to do nothing. The + # classes that deal with sequences should reimplement this method to + # raise if there are any non-numeric elements in the sequence. + pass + + +def _recursive_list_map(f, x): + if isinstance(x, list): + return list(_recursive_list_map(f, xi) for xi in x) + else: + return f(x) + + +class ApproxNumpy(ApproxBase): + """ + Perform approximate comparisons where the expected value is numpy array. + """ + + def __repr__(self): + list_scalars = _recursive_list_map(self._approx_scalar, self.expected.tolist()) + return "approx({!r})".format(list_scalars) + + if sys.version_info[0] == 2: + __cmp__ = _cmp_raises_type_error + + def __eq__(self, actual): + import numpy as np + + # self.expected is supposed to always be an array here + + if not np.isscalar(actual): + try: + actual = np.asarray(actual) + except: # noqa + raise TypeError("cannot compare '{}' to numpy.ndarray".format(actual)) + + if not np.isscalar(actual) and actual.shape != self.expected.shape: + return False + + return ApproxBase.__eq__(self, actual) + + def _yield_comparisons(self, actual): + import numpy as np + + # `actual` can either be a numpy array or a scalar, it is treated in + # `__eq__` before being passed to `ApproxBase.__eq__`, which is the + # only method that calls this one. + + if np.isscalar(actual): + for i in np.ndindex(self.expected.shape): + yield actual, self.expected[i].item() + else: + for i in np.ndindex(self.expected.shape): + yield actual[i].item(), self.expected[i].item() + + +class ApproxMapping(ApproxBase): + """ + Perform approximate comparisons where the expected value is a mapping with + numeric values (the keys can be anything). + """ + + def __repr__(self): + return "approx({!r})".format( + {k: self._approx_scalar(v) for k, v in self.expected.items()} + ) + + def __eq__(self, actual): + if set(actual.keys()) != set(self.expected.keys()): + return False + + return ApproxBase.__eq__(self, actual) + + def _yield_comparisons(self, actual): + for k in self.expected.keys(): + yield actual[k], self.expected[k] + + def _check_type(self): + __tracebackhide__ = True + for key, value in self.expected.items(): + if isinstance(value, type(self.expected)): + msg = "pytest.approx() does not support nested dictionaries: key={!r} value={!r}\n full mapping={}" + raise TypeError(msg.format(key, value, pprint.pformat(self.expected))) + elif not isinstance(value, Number): + raise _non_numeric_type_error(self.expected, at="key={!r}".format(key)) + + +class ApproxSequencelike(ApproxBase): + """ + Perform approximate comparisons where the expected value is a sequence of + numbers. + """ + + def __repr__(self): + seq_type = type(self.expected) + if seq_type not in (tuple, list, set): + seq_type = list + return "approx({!r})".format( + seq_type(self._approx_scalar(x) for x in self.expected) + ) + + def __eq__(self, actual): + if len(actual) != len(self.expected): + return False + return ApproxBase.__eq__(self, actual) + + def _yield_comparisons(self, actual): + return zip(actual, self.expected) + + def _check_type(self): + __tracebackhide__ = True + for index, x in enumerate(self.expected): + if isinstance(x, type(self.expected)): + msg = "pytest.approx() does not support nested data structures: {!r} at index {}\n full sequence: {}" + raise TypeError(msg.format(x, index, pprint.pformat(self.expected))) + elif not isinstance(x, Number): + raise _non_numeric_type_error( + self.expected, at="index {}".format(index) + ) + + +class ApproxScalar(ApproxBase): + """ + Perform approximate comparisons where the expected value is a single number. + """ + + DEFAULT_ABSOLUTE_TOLERANCE = 1e-12 + DEFAULT_RELATIVE_TOLERANCE = 1e-6 + + def __repr__(self): + """ + Return a string communicating both the expected value and the tolerance + for the comparison being made, e.g. '1.0 +- 1e-6'. Use the unicode + plus/minus symbol if this is python3 (it's too hard to get right for + python2). + """ + if isinstance(self.expected, complex): + return str(self.expected) + + # Infinities aren't compared using tolerances, so don't show a + # tolerance. + if math.isinf(self.expected): + return str(self.expected) + + # If a sensible tolerance can't be calculated, self.tolerance will + # raise a ValueError. In this case, display '???'. + try: + vetted_tolerance = "{:.1e}".format(self.tolerance) + except ValueError: + vetted_tolerance = "???" + + if sys.version_info[0] == 2: + return "{} +- {}".format(self.expected, vetted_tolerance) + else: + return u"{} \u00b1 {}".format(self.expected, vetted_tolerance) + + def __eq__(self, actual): + """ + Return true if the given value is equal to the expected value within + the pre-specified tolerance. + """ + if _is_numpy_array(actual): + # Call ``__eq__()`` manually to prevent infinite-recursion with + # numpy<1.13. See #3748. + return all(self.__eq__(a) for a in actual.flat) + + # Short-circuit exact equality. + if actual == self.expected: + return True + + # Allow the user to control whether NaNs are considered equal to each + # other or not. The abs() calls are for compatibility with complex + # numbers. + if math.isnan(abs(self.expected)): + return self.nan_ok and math.isnan(abs(actual)) + + # Infinity shouldn't be approximately equal to anything but itself, but + # if there's a relative tolerance, it will be infinite and infinity + # will seem approximately equal to everything. The equal-to-itself + # case would have been short circuited above, so here we can just + # return false if the expected value is infinite. The abs() call is + # for compatibility with complex numbers. + if math.isinf(abs(self.expected)): + return False + + # Return true if the two numbers are within the tolerance. + return abs(self.expected - actual) <= self.tolerance + + __hash__ = None + + @property + def tolerance(self): + """ + Return the tolerance for the comparison. This could be either an + absolute tolerance or a relative tolerance, depending on what the user + specified or which would be larger. + """ + + def set_default(x, default): + return x if x is not None else default + + # Figure out what the absolute tolerance should be. ``self.abs`` is + # either None or a value specified by the user. + absolute_tolerance = set_default(self.abs, self.DEFAULT_ABSOLUTE_TOLERANCE) + + if absolute_tolerance < 0: + raise ValueError( + "absolute tolerance can't be negative: {}".format(absolute_tolerance) + ) + if math.isnan(absolute_tolerance): + raise ValueError("absolute tolerance can't be NaN.") + + # If the user specified an absolute tolerance but not a relative one, + # just return the absolute tolerance. + if self.rel is None: + if self.abs is not None: + return absolute_tolerance + + # Figure out what the relative tolerance should be. ``self.rel`` is + # either None or a value specified by the user. This is done after + # we've made sure the user didn't ask for an absolute tolerance only, + # because we don't want to raise errors about the relative tolerance if + # we aren't even going to use it. + relative_tolerance = set_default( + self.rel, self.DEFAULT_RELATIVE_TOLERANCE + ) * abs(self.expected) + + if relative_tolerance < 0: + raise ValueError( + "relative tolerance can't be negative: {}".format(absolute_tolerance) + ) + if math.isnan(relative_tolerance): + raise ValueError("relative tolerance can't be NaN.") + + # Return the larger of the relative and absolute tolerances. + return max(relative_tolerance, absolute_tolerance) + + +class ApproxDecimal(ApproxScalar): + """ + Perform approximate comparisons where the expected value is a decimal. + """ + + DEFAULT_ABSOLUTE_TOLERANCE = Decimal("1e-12") + DEFAULT_RELATIVE_TOLERANCE = Decimal("1e-6") + + +def approx(expected, rel=None, abs=None, nan_ok=False): + """ + Assert that two numbers (or two sets of numbers) are equal to each other + within some tolerance. + + Due to the `intricacies of floating-point arithmetic`__, numbers that we + would intuitively expect to be equal are not always so:: + + >>> 0.1 + 0.2 == 0.3 + False + + __ https://docs.python.org/3/tutorial/floatingpoint.html + + This problem is commonly encountered when writing tests, e.g. when making + sure that floating-point values are what you expect them to be. One way to + deal with this problem is to assert that two floating-point numbers are + equal to within some appropriate tolerance:: + + >>> abs((0.1 + 0.2) - 0.3) < 1e-6 + True + + However, comparisons like this are tedious to write and difficult to + understand. Furthermore, absolute comparisons like the one above are + usually discouraged because there's no tolerance that works well for all + situations. ``1e-6`` is good for numbers around ``1``, but too small for + very big numbers and too big for very small ones. It's better to express + the tolerance as a fraction of the expected value, but relative comparisons + like that are even more difficult to write correctly and concisely. + + The ``approx`` class performs floating-point comparisons using a syntax + that's as intuitive as possible:: + + >>> from pytest import approx + >>> 0.1 + 0.2 == approx(0.3) + True + + The same syntax also works for sequences of numbers:: + + >>> (0.1 + 0.2, 0.2 + 0.4) == approx((0.3, 0.6)) + True + + Dictionary *values*:: + + >>> {'a': 0.1 + 0.2, 'b': 0.2 + 0.4} == approx({'a': 0.3, 'b': 0.6}) + True + + ``numpy`` arrays:: + + >>> import numpy as np # doctest: +SKIP + >>> np.array([0.1, 0.2]) + np.array([0.2, 0.4]) == approx(np.array([0.3, 0.6])) # doctest: +SKIP + True + + And for a ``numpy`` array against a scalar:: + + >>> import numpy as np # doctest: +SKIP + >>> np.array([0.1, 0.2]) + np.array([0.2, 0.1]) == approx(0.3) # doctest: +SKIP + True + + By default, ``approx`` considers numbers within a relative tolerance of + ``1e-6`` (i.e. one part in a million) of its expected value to be equal. + This treatment would lead to surprising results if the expected value was + ``0.0``, because nothing but ``0.0`` itself is relatively close to ``0.0``. + To handle this case less surprisingly, ``approx`` also considers numbers + within an absolute tolerance of ``1e-12`` of its expected value to be + equal. Infinity and NaN are special cases. Infinity is only considered + equal to itself, regardless of the relative tolerance. NaN is not + considered equal to anything by default, but you can make it be equal to + itself by setting the ``nan_ok`` argument to True. (This is meant to + facilitate comparing arrays that use NaN to mean "no data".) + + Both the relative and absolute tolerances can be changed by passing + arguments to the ``approx`` constructor:: + + >>> 1.0001 == approx(1) + False + >>> 1.0001 == approx(1, rel=1e-3) + True + >>> 1.0001 == approx(1, abs=1e-3) + True + + If you specify ``abs`` but not ``rel``, the comparison will not consider + the relative tolerance at all. In other words, two numbers that are within + the default relative tolerance of ``1e-6`` will still be considered unequal + if they exceed the specified absolute tolerance. If you specify both + ``abs`` and ``rel``, the numbers will be considered equal if either + tolerance is met:: + + >>> 1 + 1e-8 == approx(1) + True + >>> 1 + 1e-8 == approx(1, abs=1e-12) + False + >>> 1 + 1e-8 == approx(1, rel=1e-6, abs=1e-12) + True + + If you're thinking about using ``approx``, then you might want to know how + it compares to other good ways of comparing floating-point numbers. All of + these algorithms are based on relative and absolute tolerances and should + agree for the most part, but they do have meaningful differences: + + - ``math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)``: True if the relative + tolerance is met w.r.t. either ``a`` or ``b`` or if the absolute + tolerance is met. Because the relative tolerance is calculated w.r.t. + both ``a`` and ``b``, this test is symmetric (i.e. neither ``a`` nor + ``b`` is a "reference value"). You have to specify an absolute tolerance + if you want to compare to ``0.0`` because there is no tolerance by + default. Only available in python>=3.5. `More information...`__ + + __ https://docs.python.org/3/library/math.html#math.isclose + + - ``numpy.isclose(a, b, rtol=1e-5, atol=1e-8)``: True if the difference + between ``a`` and ``b`` is less that the sum of the relative tolerance + w.r.t. ``b`` and the absolute tolerance. Because the relative tolerance + is only calculated w.r.t. ``b``, this test is asymmetric and you can + think of ``b`` as the reference value. Support for comparing sequences + is provided by ``numpy.allclose``. `More information...`__ + + __ http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.isclose.html + + - ``unittest.TestCase.assertAlmostEqual(a, b)``: True if ``a`` and ``b`` + are within an absolute tolerance of ``1e-7``. No relative tolerance is + considered and the absolute tolerance cannot be changed, so this function + is not appropriate for very large or very small numbers. Also, it's only + available in subclasses of ``unittest.TestCase`` and it's ugly because it + doesn't follow PEP8. `More information...`__ + + __ https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertAlmostEqual + + - ``a == pytest.approx(b, rel=1e-6, abs=1e-12)``: True if the relative + tolerance is met w.r.t. ``b`` or if the absolute tolerance is met. + Because the relative tolerance is only calculated w.r.t. ``b``, this test + is asymmetric and you can think of ``b`` as the reference value. In the + special case that you explicitly specify an absolute tolerance but not a + relative tolerance, only the absolute tolerance is considered. + + .. warning:: + + .. versionchanged:: 3.2 + + In order to avoid inconsistent behavior, ``TypeError`` is + raised for ``>``, ``>=``, ``<`` and ``<=`` comparisons. + The example below illustrates the problem:: + + assert approx(0.1) > 0.1 + 1e-10 # calls approx(0.1).__gt__(0.1 + 1e-10) + assert 0.1 + 1e-10 > approx(0.1) # calls approx(0.1).__lt__(0.1 + 1e-10) + + In the second example one expects ``approx(0.1).__le__(0.1 + 1e-10)`` + to be called. But instead, ``approx(0.1).__lt__(0.1 + 1e-10)`` is used to + comparison. This is because the call hierarchy of rich comparisons + follows a fixed behavior. `More information...`__ + + __ https://docs.python.org/3/reference/datamodel.html#object.__ge__ + """ + + # Delegate the comparison to a class that knows how to deal with the type + # of the expected value (e.g. int, float, list, dict, numpy.array, etc). + # + # The primary responsibility of these classes is to implement ``__eq__()`` + # and ``__repr__()``. The former is used to actually check if some + # "actual" value is equivalent to the given expected value within the + # allowed tolerance. The latter is used to show the user the expected + # value and tolerance, in the case that a test failed. + # + # The actual logic for making approximate comparisons can be found in + # ApproxScalar, which is used to compare individual numbers. All of the + # other Approx classes eventually delegate to this class. The ApproxBase + # class provides some convenient methods and overloads, but isn't really + # essential. + + __tracebackhide__ = True + + if isinstance(expected, Decimal): + cls = ApproxDecimal + elif isinstance(expected, Number): + cls = ApproxScalar + elif isinstance(expected, Mapping): + cls = ApproxMapping + elif _is_numpy_array(expected): + cls = ApproxNumpy + elif ( + isinstance(expected, Iterable) + and isinstance(expected, Sized) + and not isinstance(expected, STRING_TYPES) + ): + cls = ApproxSequencelike + else: + raise _non_numeric_type_error(expected, at=None) + + return cls(expected, rel, abs, nan_ok) + + +def _is_numpy_array(obj): + """ + Return true if the given object is a numpy array. Make a special effort to + avoid importing numpy unless it's really necessary. + """ + import sys + + np = sys.modules.get("numpy") + if np is not None: + return isinstance(obj, np.ndarray) + return False + + +# builtin pytest.raises helper + + +def raises(expected_exception, *args, **kwargs): + r""" + Assert that a code block/function call raises ``expected_exception`` + or raise a failure exception otherwise. + + :kwparam match: if specified, a string containing a regular expression, + or a regular expression object, that is tested against the string + representation of the exception using ``re.search``. To match a literal + string that may contain `special characters`__, the pattern can + first be escaped with ``re.escape``. + + __ https://docs.python.org/3/library/re.html#regular-expression-syntax + + :kwparam message: **(deprecated since 4.1)** if specified, provides a custom failure message + if the exception is not raised. See :ref:`the deprecation docs ` for a workaround. + + .. currentmodule:: _pytest._code + + Use ``pytest.raises`` as a context manager, which will capture the exception of the given + type:: + + >>> with raises(ZeroDivisionError): + ... 1/0 + + If the code block does not raise the expected exception (``ZeroDivisionError`` in the example + above), or no exception at all, the check will fail instead. + + You can also use the keyword argument ``match`` to assert that the + exception matches a text or regex:: + + >>> with raises(ValueError, match='must be 0 or None'): + ... raise ValueError("value must be 0 or None") + + >>> with raises(ValueError, match=r'must be \d+$'): + ... raise ValueError("value must be 42") + + The context manager produces an :class:`ExceptionInfo` object which can be used to inspect the + details of the captured exception:: + + >>> with raises(ValueError) as exc_info: + ... raise ValueError("value must be 42") + >>> assert exc_info.type is ValueError + >>> assert exc_info.value.args[0] == "value must be 42" + + .. deprecated:: 4.1 + + In the context manager form you may use the keyword argument + ``message`` to specify a custom failure message that will be displayed + in case the ``pytest.raises`` check fails. This has been deprecated as it + is considered error prone as users often mean to use ``match`` instead. + See :ref:`the deprecation docs ` for a workaround. + + .. note:: + + When using ``pytest.raises`` as a context manager, it's worthwhile to + note that normal context manager rules apply and that the exception + raised *must* be the final line in the scope of the context manager. + Lines of code after that, within the scope of the context manager will + not be executed. For example:: + + >>> value = 15 + >>> with raises(ValueError) as exc_info: + ... if value > 10: + ... raise ValueError("value must be <= 10") + ... assert exc_info.type is ValueError # this will not execute + + Instead, the following approach must be taken (note the difference in + scope):: + + >>> with raises(ValueError) as exc_info: + ... if value > 10: + ... raise ValueError("value must be <= 10") + ... + >>> assert exc_info.type is ValueError + + **Using with** ``pytest.mark.parametrize`` + + When using :ref:`pytest.mark.parametrize ref` + it is possible to parametrize tests such that + some runs raise an exception and others do not. + + See :ref:`parametrizing_conditional_raising` for an example. + + **Legacy form** + + It is possible to specify a callable by passing a to-be-called lambda:: + + >>> raises(ZeroDivisionError, lambda: 1/0) + + + or you can specify an arbitrary callable with arguments:: + + >>> def f(x): return 1/x + ... + >>> raises(ZeroDivisionError, f, 0) + + >>> raises(ZeroDivisionError, f, x=0) + + + The form above is fully supported but discouraged for new code because the + context manager form is regarded as more readable and less error-prone. + + .. note:: + Similar to caught exception objects in Python, explicitly clearing + local references to returned ``ExceptionInfo`` objects can + help the Python interpreter speed up its garbage collection. + + Clearing those references breaks a reference cycle + (``ExceptionInfo`` --> caught exception --> frame stack raising + the exception --> current frame stack --> local variables --> + ``ExceptionInfo``) which makes Python keep all objects referenced + from that cycle (including all local variables in the current + frame) alive until the next cyclic garbage collection run. See the + official Python ``try`` statement documentation for more detailed + information. + + """ + __tracebackhide__ = True + for exc in filterfalse(isclass, always_iterable(expected_exception, BASE_TYPE)): + msg = ( + "exceptions must be old-style classes or" + " derived from BaseException, not %s" + ) + raise TypeError(msg % type(exc)) + + message = "DID NOT RAISE {}".format(expected_exception) + match_expr = None + + if not args: + if "message" in kwargs: + message = kwargs.pop("message") + warnings.warn(deprecated.RAISES_MESSAGE_PARAMETER, stacklevel=2) + if "match" in kwargs: + match_expr = kwargs.pop("match") + if kwargs: + msg = "Unexpected keyword arguments passed to pytest.raises: " + msg += ", ".join(sorted(kwargs)) + raise TypeError(msg) + return RaisesContext(expected_exception, message, match_expr) + elif isinstance(args[0], str): + warnings.warn(deprecated.RAISES_EXEC, stacklevel=2) + code, = args + assert isinstance(code, str) + frame = sys._getframe(1) + loc = frame.f_locals.copy() + loc.update(kwargs) + # print "raises frame scope: %r" % frame.f_locals + try: + code = _pytest._code.Source(code).compile(_genframe=frame) + exec(code, frame.f_globals, loc) + # XXX didn't mean f_globals == f_locals something special? + # this is destroyed here ... + except expected_exception: + return _pytest._code.ExceptionInfo.from_current() + else: + func = args[0] + try: + func(*args[1:], **kwargs) + except expected_exception: + return _pytest._code.ExceptionInfo.from_current() + fail(message) + + +raises.Exception = fail.Exception + + +class RaisesContext(object): + def __init__(self, expected_exception, message, match_expr): + self.expected_exception = expected_exception + self.message = message + self.match_expr = match_expr + self.excinfo = None + + def __enter__(self): + self.excinfo = _pytest._code.ExceptionInfo.for_later() + return self.excinfo + + def __exit__(self, *tp): + __tracebackhide__ = True + if tp[0] is None: + fail(self.message) + self.excinfo.__init__(tp) + suppress_exception = issubclass(self.excinfo.type, self.expected_exception) + if sys.version_info[0] == 2 and suppress_exception: + sys.exc_clear() + if self.match_expr is not None and suppress_exception: + self.excinfo.match(self.match_expr) + return suppress_exception diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/recwarn.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/recwarn.py new file mode 100644 index 0000000000000000000000000000000000000000..574c6a1cced01fc2551fec02d4765c92b7203920 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/recwarn.py @@ -0,0 +1,251 @@ +# -*- coding: utf-8 -*- +""" recording warnings during test function execution. """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import inspect +import re +import sys +import warnings + +import six + +import _pytest._code +from _pytest.deprecated import PYTEST_WARNS_UNKNOWN_KWARGS +from _pytest.deprecated import WARNS_EXEC +from _pytest.fixtures import yield_fixture +from _pytest.outcomes import fail + + +@yield_fixture +def recwarn(): + """Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions. + + See http://docs.python.org/library/warnings.html for information + on warning categories. + """ + wrec = WarningsRecorder() + with wrec: + warnings.simplefilter("default") + yield wrec + + +def deprecated_call(func=None, *args, **kwargs): + """context manager that can be used to ensure a block of code triggers a + ``DeprecationWarning`` or ``PendingDeprecationWarning``:: + + >>> import warnings + >>> def api_call_v2(): + ... warnings.warn('use v3 of this api', DeprecationWarning) + ... return 200 + + >>> with deprecated_call(): + ... assert api_call_v2() == 200 + + ``deprecated_call`` can also be used by passing a function and ``*args`` and ``*kwargs``, + in which case it will ensure calling ``func(*args, **kwargs)`` produces one of the warnings + types above. + """ + __tracebackhide__ = True + if func is not None: + args = (func,) + args + return warns((DeprecationWarning, PendingDeprecationWarning), *args, **kwargs) + + +def warns(expected_warning, *args, **kwargs): + r"""Assert that code raises a particular class of warning. + + Specifically, the parameter ``expected_warning`` can be a warning class or + sequence of warning classes, and the inside the ``with`` block must issue a warning of that class or + classes. + + This helper produces a list of :class:`warnings.WarningMessage` objects, + one for each warning raised. + + This function can be used as a context manager, or any of the other ways + ``pytest.raises`` can be used:: + + >>> with warns(RuntimeWarning): + ... warnings.warn("my warning", RuntimeWarning) + + In the context manager form you may use the keyword argument ``match`` to assert + that the exception matches a text or regex:: + + >>> with warns(UserWarning, match='must be 0 or None'): + ... warnings.warn("value must be 0 or None", UserWarning) + + >>> with warns(UserWarning, match=r'must be \d+$'): + ... warnings.warn("value must be 42", UserWarning) + + >>> with warns(UserWarning, match=r'must be \d+$'): + ... warnings.warn("this is not here", UserWarning) + Traceback (most recent call last): + ... + Failed: DID NOT WARN. No warnings of type ...UserWarning... was emitted... + + """ + __tracebackhide__ = True + if not args: + match_expr = kwargs.pop("match", None) + if kwargs: + warnings.warn( + PYTEST_WARNS_UNKNOWN_KWARGS.format(args=sorted(kwargs)), stacklevel=2 + ) + return WarningsChecker(expected_warning, match_expr=match_expr) + elif isinstance(args[0], str): + warnings.warn(WARNS_EXEC, stacklevel=2) + code, = args + assert isinstance(code, str) + frame = sys._getframe(1) + loc = frame.f_locals.copy() + loc.update(kwargs) + + with WarningsChecker(expected_warning): + code = _pytest._code.Source(code).compile() + exec(code, frame.f_globals, loc) + else: + func = args[0] + with WarningsChecker(expected_warning): + return func(*args[1:], **kwargs) + + +class WarningsRecorder(warnings.catch_warnings): + """A context manager to record raised warnings. + + Adapted from `warnings.catch_warnings`. + """ + + def __init__(self): + super(WarningsRecorder, self).__init__(record=True) + self._entered = False + self._list = [] + + @property + def list(self): + """The list of recorded warnings.""" + return self._list + + def __getitem__(self, i): + """Get a recorded warning by index.""" + return self._list[i] + + def __iter__(self): + """Iterate through the recorded warnings.""" + return iter(self._list) + + def __len__(self): + """The number of recorded warnings.""" + return len(self._list) + + def pop(self, cls=Warning): + """Pop the first recorded warning, raise exception if not exists.""" + for i, w in enumerate(self._list): + if issubclass(w.category, cls): + return self._list.pop(i) + __tracebackhide__ = True + raise AssertionError("%r not found in warning list" % cls) + + def clear(self): + """Clear the list of recorded warnings.""" + self._list[:] = [] + + def __enter__(self): + if self._entered: + __tracebackhide__ = True + raise RuntimeError("Cannot enter %r twice" % self) + self._list = super(WarningsRecorder, self).__enter__() + warnings.simplefilter("always") + # python3 keeps track of a "filter version", when the filters are + # updated previously seen warnings can be re-warned. python2 has no + # concept of this so we must reset the warnings registry manually. + # trivial patching of `warnings.warn` seems to be enough somehow? + if six.PY2: + + def warn(message, category=None, stacklevel=1): + # duplicate the stdlib logic due to + # bad handing in the c version of warnings + if isinstance(message, Warning): + category = message.__class__ + # Check category argument + if category is None: + category = UserWarning + assert issubclass(category, Warning) + + # emulate resetting the warn registry + f_globals = sys._getframe(stacklevel).f_globals + if "__warningregistry__" in f_globals: + orig = f_globals["__warningregistry__"] + f_globals["__warningregistry__"] = None + try: + return self._saved_warn(message, category, stacklevel + 1) + finally: + f_globals["__warningregistry__"] = orig + else: + return self._saved_warn(message, category, stacklevel + 1) + + warnings.warn, self._saved_warn = warn, warnings.warn + return self + + def __exit__(self, *exc_info): + if not self._entered: + __tracebackhide__ = True + raise RuntimeError("Cannot exit %r without entering first" % self) + # see above where `self._saved_warn` is assigned + if six.PY2: + warnings.warn = self._saved_warn + super(WarningsRecorder, self).__exit__(*exc_info) + + # Built-in catch_warnings does not reset entered state so we do it + # manually here for this context manager to become reusable. + self._entered = False + + +class WarningsChecker(WarningsRecorder): + def __init__(self, expected_warning=None, match_expr=None): + super(WarningsChecker, self).__init__() + + msg = "exceptions must be old-style classes or derived from Warning, not %s" + if isinstance(expected_warning, tuple): + for exc in expected_warning: + if not inspect.isclass(exc): + raise TypeError(msg % type(exc)) + elif inspect.isclass(expected_warning): + expected_warning = (expected_warning,) + elif expected_warning is not None: + raise TypeError(msg % type(expected_warning)) + + self.expected_warning = expected_warning + self.match_expr = match_expr + + def __exit__(self, *exc_info): + super(WarningsChecker, self).__exit__(*exc_info) + + __tracebackhide__ = True + + # only check if we're not currently handling an exception + if all(a is None for a in exc_info): + if self.expected_warning is not None: + if not any(issubclass(r.category, self.expected_warning) for r in self): + __tracebackhide__ = True + fail( + "DID NOT WARN. No warnings of type {} was emitted. " + "The list of emitted warnings is: {}.".format( + self.expected_warning, [each.message for each in self] + ) + ) + elif self.match_expr is not None: + for r in self: + if issubclass(r.category, self.expected_warning): + if re.compile(self.match_expr).search(str(r.message)): + break + else: + fail( + "DID NOT WARN. No warnings of type {} matching" + " ('{}') was emitted. The list of emitted warnings" + " is: {}.".format( + self.expected_warning, + self.match_expr, + [each.message for each in self], + ) + ) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/reports.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/reports.py new file mode 100644 index 0000000000000000000000000000000000000000..0bba6762c33a75ea7891b3e3fe6fe7bad53289f9 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/reports.py @@ -0,0 +1,435 @@ +# -*- coding: utf-8 -*- +from pprint import pprint + +import py +import six + +from _pytest._code.code import ExceptionInfo +from _pytest._code.code import ReprEntry +from _pytest._code.code import ReprEntryNative +from _pytest._code.code import ReprExceptionInfo +from _pytest._code.code import ReprFileLocation +from _pytest._code.code import ReprFuncArgs +from _pytest._code.code import ReprLocals +from _pytest._code.code import ReprTraceback +from _pytest._code.code import TerminalRepr +from _pytest.outcomes import skip +from _pytest.pathlib import Path + + +def getslaveinfoline(node): + try: + return node._slaveinfocache + except AttributeError: + d = node.slaveinfo + ver = "%s.%s.%s" % d["version_info"][:3] + node._slaveinfocache = s = "[%s] %s -- Python %s %s" % ( + d["id"], + d["sysplatform"], + ver, + d["executable"], + ) + return s + + +class BaseReport(object): + when = None + location = None + + def __init__(self, **kw): + self.__dict__.update(kw) + + def toterminal(self, out): + if hasattr(self, "node"): + out.line(getslaveinfoline(self.node)) + + longrepr = self.longrepr + if longrepr is None: + return + + if hasattr(longrepr, "toterminal"): + longrepr.toterminal(out) + else: + try: + out.line(longrepr) + except UnicodeEncodeError: + out.line("") + + def get_sections(self, prefix): + for name, content in self.sections: + if name.startswith(prefix): + yield prefix, content + + @property + def longreprtext(self): + """ + Read-only property that returns the full string representation + of ``longrepr``. + + .. versionadded:: 3.0 + """ + tw = py.io.TerminalWriter(stringio=True) + tw.hasmarkup = False + self.toterminal(tw) + exc = tw.stringio.getvalue() + return exc.strip() + + @property + def caplog(self): + """Return captured log lines, if log capturing is enabled + + .. versionadded:: 3.5 + """ + return "\n".join( + content for (prefix, content) in self.get_sections("Captured log") + ) + + @property + def capstdout(self): + """Return captured text from stdout, if capturing is enabled + + .. versionadded:: 3.0 + """ + return "".join( + content for (prefix, content) in self.get_sections("Captured stdout") + ) + + @property + def capstderr(self): + """Return captured text from stderr, if capturing is enabled + + .. versionadded:: 3.0 + """ + return "".join( + content for (prefix, content) in self.get_sections("Captured stderr") + ) + + passed = property(lambda x: x.outcome == "passed") + failed = property(lambda x: x.outcome == "failed") + skipped = property(lambda x: x.outcome == "skipped") + + @property + def fspath(self): + return self.nodeid.split("::")[0] + + @property + def count_towards_summary(self): + """ + **Experimental** + + Returns True if this report should be counted towards the totals shown at the end of the + test session: "1 passed, 1 failure, etc". + + .. note:: + + This function is considered **experimental**, so beware that it is subject to changes + even in patch releases. + """ + return True + + @property + def head_line(self): + """ + **Experimental** + + Returns the head line shown with longrepr output for this report, more commonly during + traceback representation during failures:: + + ________ Test.foo ________ + + + In the example above, the head_line is "Test.foo". + + .. note:: + + This function is considered **experimental**, so beware that it is subject to changes + even in patch releases. + """ + if self.location is not None: + fspath, lineno, domain = self.location + return domain + + def _get_verbose_word(self, config): + _category, _short, verbose = config.hook.pytest_report_teststatus( + report=self, config=config + ) + return verbose + + def _to_json(self): + """ + This was originally the serialize_report() function from xdist (ca03269). + + Returns the contents of this report as a dict of builtin entries, suitable for + serialization. + + Experimental method. + """ + + def disassembled_report(rep): + reprtraceback = rep.longrepr.reprtraceback.__dict__.copy() + reprcrash = rep.longrepr.reprcrash.__dict__.copy() + + new_entries = [] + for entry in reprtraceback["reprentries"]: + entry_data = { + "type": type(entry).__name__, + "data": entry.__dict__.copy(), + } + for key, value in entry_data["data"].items(): + if hasattr(value, "__dict__"): + entry_data["data"][key] = value.__dict__.copy() + new_entries.append(entry_data) + + reprtraceback["reprentries"] = new_entries + + return { + "reprcrash": reprcrash, + "reprtraceback": reprtraceback, + "sections": rep.longrepr.sections, + } + + d = self.__dict__.copy() + if hasattr(self.longrepr, "toterminal"): + if hasattr(self.longrepr, "reprtraceback") and hasattr( + self.longrepr, "reprcrash" + ): + d["longrepr"] = disassembled_report(self) + else: + d["longrepr"] = six.text_type(self.longrepr) + else: + d["longrepr"] = self.longrepr + for name in d: + if isinstance(d[name], (py.path.local, Path)): + d[name] = str(d[name]) + elif name == "result": + d[name] = None # for now + return d + + @classmethod + def _from_json(cls, reportdict): + """ + This was originally the serialize_report() function from xdist (ca03269). + + Factory method that returns either a TestReport or CollectReport, depending on the calling + class. It's the callers responsibility to know which class to pass here. + + Experimental method. + """ + if reportdict["longrepr"]: + if ( + "reprcrash" in reportdict["longrepr"] + and "reprtraceback" in reportdict["longrepr"] + ): + + reprtraceback = reportdict["longrepr"]["reprtraceback"] + reprcrash = reportdict["longrepr"]["reprcrash"] + + unserialized_entries = [] + reprentry = None + for entry_data in reprtraceback["reprentries"]: + data = entry_data["data"] + entry_type = entry_data["type"] + if entry_type == "ReprEntry": + reprfuncargs = None + reprfileloc = None + reprlocals = None + if data["reprfuncargs"]: + reprfuncargs = ReprFuncArgs(**data["reprfuncargs"]) + if data["reprfileloc"]: + reprfileloc = ReprFileLocation(**data["reprfileloc"]) + if data["reprlocals"]: + reprlocals = ReprLocals(data["reprlocals"]["lines"]) + + reprentry = ReprEntry( + lines=data["lines"], + reprfuncargs=reprfuncargs, + reprlocals=reprlocals, + filelocrepr=reprfileloc, + style=data["style"], + ) + elif entry_type == "ReprEntryNative": + reprentry = ReprEntryNative(data["lines"]) + else: + _report_unserialization_failure(entry_type, cls, reportdict) + unserialized_entries.append(reprentry) + reprtraceback["reprentries"] = unserialized_entries + + exception_info = ReprExceptionInfo( + reprtraceback=ReprTraceback(**reprtraceback), + reprcrash=ReprFileLocation(**reprcrash), + ) + + for section in reportdict["longrepr"]["sections"]: + exception_info.addsection(*section) + reportdict["longrepr"] = exception_info + + return cls(**reportdict) + + +def _report_unserialization_failure(type_name, report_class, reportdict): + url = "https://github.com/pytest-dev/pytest/issues" + stream = py.io.TextIO() + pprint("-" * 100, stream=stream) + pprint("INTERNALERROR: Unknown entry type returned: %s" % type_name, stream=stream) + pprint("report_name: %s" % report_class, stream=stream) + pprint(reportdict, stream=stream) + pprint("Please report this bug at %s" % url, stream=stream) + pprint("-" * 100, stream=stream) + raise RuntimeError(stream.getvalue()) + + +class TestReport(BaseReport): + """ Basic test report object (also used for setup and teardown calls if + they fail). + """ + + __test__ = False + + def __init__( + self, + nodeid, + location, + keywords, + outcome, + longrepr, + when, + sections=(), + duration=0, + user_properties=None, + **extra + ): + #: normalized collection node id + self.nodeid = nodeid + + #: a (filesystempath, lineno, domaininfo) tuple indicating the + #: actual location of a test item - it might be different from the + #: collected one e.g. if a method is inherited from a different module. + self.location = location + + #: a name -> value dictionary containing all keywords and + #: markers associated with a test invocation. + self.keywords = keywords + + #: test outcome, always one of "passed", "failed", "skipped". + self.outcome = outcome + + #: None or a failure representation. + self.longrepr = longrepr + + #: one of 'setup', 'call', 'teardown' to indicate runtest phase. + self.when = when + + #: user properties is a list of tuples (name, value) that holds user + #: defined properties of the test + self.user_properties = list(user_properties or []) + + #: list of pairs ``(str, str)`` of extra information which needs to + #: marshallable. Used by pytest to add captured text + #: from ``stdout`` and ``stderr``, but may be used by other plugins + #: to add arbitrary information to reports. + self.sections = list(sections) + + #: time it took to run just the test + self.duration = duration + + self.__dict__.update(extra) + + def __repr__(self): + return "<%s %r when=%r outcome=%r>" % ( + self.__class__.__name__, + self.nodeid, + self.when, + self.outcome, + ) + + @classmethod + def from_item_and_call(cls, item, call): + """ + Factory method to create and fill a TestReport with standard item and call info. + """ + when = call.when + duration = call.stop - call.start + keywords = {x: 1 for x in item.keywords} + excinfo = call.excinfo + sections = [] + if not call.excinfo: + outcome = "passed" + longrepr = None + else: + if not isinstance(excinfo, ExceptionInfo): + outcome = "failed" + longrepr = excinfo + elif excinfo.errisinstance(skip.Exception): + outcome = "skipped" + r = excinfo._getreprcrash() + longrepr = (str(r.path), r.lineno, r.message) + else: + outcome = "failed" + if call.when == "call": + longrepr = item.repr_failure(excinfo) + else: # exception in setup or teardown + longrepr = item._repr_failure_py( + excinfo, style=item.config.getoption("tbstyle", "auto") + ) + for rwhen, key, content in item._report_sections: + sections.append(("Captured %s %s" % (key, rwhen), content)) + return cls( + item.nodeid, + item.location, + keywords, + outcome, + longrepr, + when, + sections, + duration, + user_properties=item.user_properties, + ) + + +class CollectReport(BaseReport): + when = "collect" + + def __init__(self, nodeid, outcome, longrepr, result, sections=(), **extra): + self.nodeid = nodeid + self.outcome = outcome + self.longrepr = longrepr + self.result = result or [] + self.sections = list(sections) + self.__dict__.update(extra) + + @property + def location(self): + return (self.fspath, None, self.fspath) + + def __repr__(self): + return "" % ( + self.nodeid, + len(self.result), + self.outcome, + ) + + +class CollectErrorRepr(TerminalRepr): + def __init__(self, msg): + self.longrepr = msg + + def toterminal(self, out): + out.line(self.longrepr, red=True) + + +def pytest_report_to_serializable(report): + if isinstance(report, (TestReport, CollectReport)): + data = report._to_json() + data["_report_type"] = report.__class__.__name__ + return data + + +def pytest_report_from_serializable(data): + if "_report_type" in data: + if data["_report_type"] == "TestReport": + return TestReport._from_json(data) + elif data["_report_type"] == "CollectReport": + return CollectReport._from_json(data) + assert False, "Unknown report_type unserialize data: {}".format( + data["_report_type"] + ) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/resultlog.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/resultlog.py new file mode 100644 index 0000000000000000000000000000000000000000..bd30b5071e9f0f8d8584e79926265dcfca945b77 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/resultlog.py @@ -0,0 +1,102 @@ +# -*- coding: utf-8 -*- +""" log machine-parseable test session result information in a plain +text file. +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os + +import py + + +def pytest_addoption(parser): + group = parser.getgroup("terminal reporting", "resultlog plugin options") + group.addoption( + "--resultlog", + "--result-log", + action="store", + metavar="path", + default=None, + help="DEPRECATED path for machine-readable result log.", + ) + + +def pytest_configure(config): + resultlog = config.option.resultlog + # prevent opening resultlog on slave nodes (xdist) + if resultlog and not hasattr(config, "slaveinput"): + dirname = os.path.dirname(os.path.abspath(resultlog)) + if not os.path.isdir(dirname): + os.makedirs(dirname) + logfile = open(resultlog, "w", 1) # line buffered + config._resultlog = ResultLog(config, logfile) + config.pluginmanager.register(config._resultlog) + + from _pytest.deprecated import RESULT_LOG + from _pytest.warnings import _issue_warning_captured + + _issue_warning_captured(RESULT_LOG, config.hook, stacklevel=2) + + +def pytest_unconfigure(config): + resultlog = getattr(config, "_resultlog", None) + if resultlog: + resultlog.logfile.close() + del config._resultlog + config.pluginmanager.unregister(resultlog) + + +class ResultLog(object): + def __init__(self, config, logfile): + self.config = config + self.logfile = logfile # preferably line buffered + + def write_log_entry(self, testpath, lettercode, longrepr): + print("%s %s" % (lettercode, testpath), file=self.logfile) + for line in longrepr.splitlines(): + print(" %s" % line, file=self.logfile) + + def log_outcome(self, report, lettercode, longrepr): + testpath = getattr(report, "nodeid", None) + if testpath is None: + testpath = report.fspath + self.write_log_entry(testpath, lettercode, longrepr) + + def pytest_runtest_logreport(self, report): + if report.when != "call" and report.passed: + return + res = self.config.hook.pytest_report_teststatus( + report=report, config=self.config + ) + code = res[1] + if code == "x": + longrepr = str(report.longrepr) + elif code == "X": + longrepr = "" + elif report.passed: + longrepr = "" + elif report.failed: + longrepr = str(report.longrepr) + elif report.skipped: + longrepr = str(report.longrepr[2]) + self.log_outcome(report, code, longrepr) + + def pytest_collectreport(self, report): + if not report.passed: + if report.failed: + code = "F" + longrepr = str(report.longrepr) + else: + assert report.skipped + code = "S" + longrepr = "%s:%d: %s" % report.longrepr + self.log_outcome(report, code, longrepr) + + def pytest_internalerror(self, excrepr): + reprcrash = getattr(excrepr, "reprcrash", None) + path = getattr(reprcrash, "path", None) + if path is None: + path = "cwd:%s" % py.path.local() + self.write_log_entry(path, "!", str(excrepr)) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/runner.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/runner.py new file mode 100644 index 0000000000000000000000000000000000000000..d51e859f1d1bd62ea699d51513df794efdf32eef --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/runner.py @@ -0,0 +1,375 @@ +# -*- coding: utf-8 -*- +""" basic collect and runtest protocol implementations """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import bdb +import os +import sys +from time import time + +import attr +import six + +from .reports import CollectErrorRepr +from .reports import CollectReport +from .reports import TestReport +from _pytest._code.code import ExceptionInfo +from _pytest.outcomes import Exit +from _pytest.outcomes import Skipped +from _pytest.outcomes import TEST_OUTCOME + +# +# pytest plugin hooks + + +def pytest_addoption(parser): + group = parser.getgroup("terminal reporting", "reporting", after="general") + group.addoption( + "--durations", + action="store", + type=int, + default=None, + metavar="N", + help="show N slowest setup/test durations (N=0 for all).", + ), + + +def pytest_terminal_summary(terminalreporter): + durations = terminalreporter.config.option.durations + verbose = terminalreporter.config.getvalue("verbose") + if durations is None: + return + tr = terminalreporter + dlist = [] + for replist in tr.stats.values(): + for rep in replist: + if hasattr(rep, "duration"): + dlist.append(rep) + if not dlist: + return + dlist.sort(key=lambda x: x.duration) + dlist.reverse() + if not durations: + tr.write_sep("=", "slowest test durations") + else: + tr.write_sep("=", "slowest %s test durations" % durations) + dlist = dlist[:durations] + + for rep in dlist: + if verbose < 2 and rep.duration < 0.005: + tr.write_line("") + tr.write_line("(0.00 durations hidden. Use -vv to show these durations.)") + break + tr.write_line("%02.2fs %-8s %s" % (rep.duration, rep.when, rep.nodeid)) + + +def pytest_sessionstart(session): + session._setupstate = SetupState() + + +def pytest_sessionfinish(session): + session._setupstate.teardown_all() + + +def pytest_runtest_protocol(item, nextitem): + item.ihook.pytest_runtest_logstart(nodeid=item.nodeid, location=item.location) + runtestprotocol(item, nextitem=nextitem) + item.ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location) + return True + + +def runtestprotocol(item, log=True, nextitem=None): + hasrequest = hasattr(item, "_request") + if hasrequest and not item._request: + item._initrequest() + rep = call_and_report(item, "setup", log) + reports = [rep] + if rep.passed: + if item.config.getoption("setupshow", False): + show_test_item(item) + if not item.config.getoption("setuponly", False): + reports.append(call_and_report(item, "call", log)) + reports.append(call_and_report(item, "teardown", log, nextitem=nextitem)) + # after all teardown hooks have been called + # want funcargs and request info to go away + if hasrequest: + item._request = False + item.funcargs = None + return reports + + +def show_test_item(item): + """Show test function, parameters and the fixtures of the test item.""" + tw = item.config.get_terminal_writer() + tw.line() + tw.write(" " * 8) + tw.write(item._nodeid) + used_fixtures = sorted(item._fixtureinfo.name2fixturedefs.keys()) + if used_fixtures: + tw.write(" (fixtures used: {})".format(", ".join(used_fixtures))) + + +def pytest_runtest_setup(item): + _update_current_test_var(item, "setup") + item.session._setupstate.prepare(item) + + +def pytest_runtest_call(item): + _update_current_test_var(item, "call") + sys.last_type, sys.last_value, sys.last_traceback = (None, None, None) + try: + item.runtest() + except Exception: + # Store trace info to allow postmortem debugging + type, value, tb = sys.exc_info() + tb = tb.tb_next # Skip *this* frame + sys.last_type = type + sys.last_value = value + sys.last_traceback = tb + del type, value, tb # Get rid of these in this frame + raise + + +def pytest_runtest_teardown(item, nextitem): + _update_current_test_var(item, "teardown") + item.session._setupstate.teardown_exact(item, nextitem) + _update_current_test_var(item, None) + + +def _update_current_test_var(item, when): + """ + Update PYTEST_CURRENT_TEST to reflect the current item and stage. + + If ``when`` is None, delete PYTEST_CURRENT_TEST from the environment. + """ + var_name = "PYTEST_CURRENT_TEST" + if when: + value = "{} ({})".format(item.nodeid, when) + # don't allow null bytes on environment variables (see #2644, #2957) + value = value.replace("\x00", "(null)") + os.environ[var_name] = value + else: + os.environ.pop(var_name) + + +def pytest_report_teststatus(report): + if report.when in ("setup", "teardown"): + if report.failed: + # category, shortletter, verbose-word + return "error", "E", "ERROR" + elif report.skipped: + return "skipped", "s", "SKIPPED" + else: + return "", "", "" + + +# +# Implementation + + +def call_and_report(item, when, log=True, **kwds): + call = call_runtest_hook(item, when, **kwds) + hook = item.ihook + report = hook.pytest_runtest_makereport(item=item, call=call) + if log: + hook.pytest_runtest_logreport(report=report) + if check_interactive_exception(call, report): + hook.pytest_exception_interact(node=item, call=call, report=report) + return report + + +def check_interactive_exception(call, report): + return call.excinfo and not ( + hasattr(report, "wasxfail") + or call.excinfo.errisinstance(Skipped) + or call.excinfo.errisinstance(bdb.BdbQuit) + ) + + +def call_runtest_hook(item, when, **kwds): + hookname = "pytest_runtest_" + when + ihook = getattr(item.ihook, hookname) + reraise = (Exit,) + if not item.config.getoption("usepdb", False): + reraise += (KeyboardInterrupt,) + return CallInfo.from_call( + lambda: ihook(item=item, **kwds), when=when, reraise=reraise + ) + + +@attr.s(repr=False) +class CallInfo(object): + """ Result/Exception info a function invocation. """ + + _result = attr.ib() + # Optional[ExceptionInfo] + excinfo = attr.ib() + start = attr.ib() + stop = attr.ib() + when = attr.ib() + + @property + def result(self): + if self.excinfo is not None: + raise AttributeError("{!r} has no valid result".format(self)) + return self._result + + @classmethod + def from_call(cls, func, when, reraise=None): + #: context of invocation: one of "setup", "call", + #: "teardown", "memocollect" + start = time() + excinfo = None + try: + result = func() + except: # noqa + excinfo = ExceptionInfo.from_current() + if reraise is not None and excinfo.errisinstance(reraise): + raise + result = None + stop = time() + return cls(start=start, stop=stop, when=when, result=result, excinfo=excinfo) + + def __repr__(self): + if self.excinfo is not None: + status = "exception" + value = self.excinfo.value + else: + # TODO: investigate unification + value = repr(self._result) + status = "result" + return "".format( + when=self.when, value=value, status=status + ) + + +def pytest_runtest_makereport(item, call): + return TestReport.from_item_and_call(item, call) + + +def pytest_make_collect_report(collector): + call = CallInfo.from_call(lambda: list(collector.collect()), "collect") + longrepr = None + if not call.excinfo: + outcome = "passed" + else: + from _pytest import nose + + skip_exceptions = (Skipped,) + nose.get_skip_exceptions() + if call.excinfo.errisinstance(skip_exceptions): + outcome = "skipped" + r = collector._repr_failure_py(call.excinfo, "line").reprcrash + longrepr = (str(r.path), r.lineno, r.message) + else: + outcome = "failed" + errorinfo = collector.repr_failure(call.excinfo) + if not hasattr(errorinfo, "toterminal"): + errorinfo = CollectErrorRepr(errorinfo) + longrepr = errorinfo + rep = CollectReport( + collector.nodeid, outcome, longrepr, getattr(call, "result", None) + ) + rep.call = call # see collect_one_node + return rep + + +class SetupState(object): + """ shared state for setting up/tearing down test items or collectors. """ + + def __init__(self): + self.stack = [] + self._finalizers = {} + + def addfinalizer(self, finalizer, colitem): + """ attach a finalizer to the given colitem. + if colitem is None, this will add a finalizer that + is called at the end of teardown_all(). + """ + assert colitem and not isinstance(colitem, tuple) + assert callable(finalizer) + # assert colitem in self.stack # some unit tests don't setup stack :/ + self._finalizers.setdefault(colitem, []).append(finalizer) + + def _pop_and_teardown(self): + colitem = self.stack.pop() + self._teardown_with_finalization(colitem) + + def _callfinalizers(self, colitem): + finalizers = self._finalizers.pop(colitem, None) + exc = None + while finalizers: + fin = finalizers.pop() + try: + fin() + except TEST_OUTCOME: + # XXX Only first exception will be seen by user, + # ideally all should be reported. + if exc is None: + exc = sys.exc_info() + if exc: + six.reraise(*exc) + + def _teardown_with_finalization(self, colitem): + self._callfinalizers(colitem) + if hasattr(colitem, "teardown"): + colitem.teardown() + for colitem in self._finalizers: + assert ( + colitem is None or colitem in self.stack or isinstance(colitem, tuple) + ) + + def teardown_all(self): + while self.stack: + self._pop_and_teardown() + for key in list(self._finalizers): + self._teardown_with_finalization(key) + assert not self._finalizers + + def teardown_exact(self, item, nextitem): + needed_collectors = nextitem and nextitem.listchain() or [] + self._teardown_towards(needed_collectors) + + def _teardown_towards(self, needed_collectors): + exc = None + while self.stack: + if self.stack == needed_collectors[: len(self.stack)]: + break + try: + self._pop_and_teardown() + except TEST_OUTCOME: + # XXX Only first exception will be seen by user, + # ideally all should be reported. + if exc is None: + exc = sys.exc_info() + if exc: + six.reraise(*exc) + + def prepare(self, colitem): + """ setup objects along the collector chain to the test-method + and teardown previously setup objects.""" + needed_collectors = colitem.listchain() + self._teardown_towards(needed_collectors) + + # check if the last collection node has raised an error + for col in self.stack: + if hasattr(col, "_prepare_exc"): + six.reraise(*col._prepare_exc) + for col in needed_collectors[len(self.stack) :]: + self.stack.append(col) + try: + col.setup() + except TEST_OUTCOME: + col._prepare_exc = sys.exc_info() + raise + + +def collect_one_node(collector): + ihook = collector.ihook + ihook.pytest_collectstart(collector=collector) + rep = ihook.pytest_make_collect_report(collector=collector) + call = rep.__dict__.pop("call", None) + if call and check_interactive_exception(call, rep): + ihook.pytest_exception_interact(node=collector, call=call, report=rep) + return rep diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/setuponly.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/setuponly.py new file mode 100644 index 0000000000000000000000000000000000000000..0859011241a9cff3fc76c9c7ca9d78a42b2417ec --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/setuponly.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import sys + +import pytest + + +def pytest_addoption(parser): + group = parser.getgroup("debugconfig") + group.addoption( + "--setuponly", + "--setup-only", + action="store_true", + help="only setup fixtures, do not execute tests.", + ) + group.addoption( + "--setupshow", + "--setup-show", + action="store_true", + help="show setup of fixtures while executing tests.", + ) + + +@pytest.hookimpl(hookwrapper=True) +def pytest_fixture_setup(fixturedef, request): + yield + config = request.config + if config.option.setupshow: + if hasattr(request, "param"): + # Save the fixture parameter so ._show_fixture_action() can + # display it now and during the teardown (in .finish()). + if fixturedef.ids: + if callable(fixturedef.ids): + fixturedef.cached_param = fixturedef.ids(request.param) + else: + fixturedef.cached_param = fixturedef.ids[request.param_index] + else: + fixturedef.cached_param = request.param + _show_fixture_action(fixturedef, "SETUP") + + +def pytest_fixture_post_finalizer(fixturedef): + if hasattr(fixturedef, "cached_result"): + config = fixturedef._fixturemanager.config + if config.option.setupshow: + _show_fixture_action(fixturedef, "TEARDOWN") + if hasattr(fixturedef, "cached_param"): + del fixturedef.cached_param + + +def _show_fixture_action(fixturedef, msg): + config = fixturedef._fixturemanager.config + capman = config.pluginmanager.getplugin("capturemanager") + if capman: + capman.suspend_global_capture() + out, err = capman.read_global_capture() + + tw = config.get_terminal_writer() + tw.line() + tw.write(" " * 2 * fixturedef.scopenum) + tw.write( + "{step} {scope} {fixture}".format( + step=msg.ljust(8), # align the output to TEARDOWN + scope=fixturedef.scope[0].upper(), + fixture=fixturedef.argname, + ) + ) + + if msg == "SETUP": + deps = sorted(arg for arg in fixturedef.argnames if arg != "request") + if deps: + tw.write(" (fixtures used: {})".format(", ".join(deps))) + + if hasattr(fixturedef, "cached_param"): + tw.write("[{}]".format(fixturedef.cached_param)) + + if capman: + capman.resume_global_capture() + sys.stdout.write(out) + sys.stderr.write(err) + + +@pytest.hookimpl(tryfirst=True) +def pytest_cmdline_main(config): + if config.option.setuponly: + config.option.setupshow = True diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/setupplan.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/setupplan.py new file mode 100644 index 0000000000000000000000000000000000000000..47b0fe82ef6dbd3afeadec8bc369763e9f64a6cb --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/setupplan.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import pytest + + +def pytest_addoption(parser): + group = parser.getgroup("debugconfig") + group.addoption( + "--setupplan", + "--setup-plan", + action="store_true", + help="show what fixtures and tests would be executed but " + "don't execute anything.", + ) + + +@pytest.hookimpl(tryfirst=True) +def pytest_fixture_setup(fixturedef, request): + # Will return a dummy fixture if the setuponly option is provided. + if request.config.option.setupplan: + fixturedef.cached_result = (None, None, None) + return fixturedef.cached_result + + +@pytest.hookimpl(tryfirst=True) +def pytest_cmdline_main(config): + if config.option.setupplan: + config.option.setuponly = True + config.option.setupshow = True diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/skipping.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/skipping.py new file mode 100644 index 0000000000000000000000000000000000000000..bc8b88e7178d867e36f7579ce5af9c90110e4882 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/skipping.py @@ -0,0 +1,186 @@ +# -*- coding: utf-8 -*- +""" support for skip/xfail functions and markers. """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from _pytest.config import hookimpl +from _pytest.mark.evaluate import MarkEvaluator +from _pytest.outcomes import fail +from _pytest.outcomes import skip +from _pytest.outcomes import xfail + + +def pytest_addoption(parser): + group = parser.getgroup("general") + group.addoption( + "--runxfail", + action="store_true", + dest="runxfail", + default=False, + help="report the results of xfail tests as if they were not marked", + ) + + parser.addini( + "xfail_strict", + "default for the strict parameter of xfail " + "markers when not given explicitly (default: False)", + default=False, + type="bool", + ) + + +def pytest_configure(config): + if config.option.runxfail: + # yay a hack + import pytest + + old = pytest.xfail + config._cleanup.append(lambda: setattr(pytest, "xfail", old)) + + def nop(*args, **kwargs): + pass + + nop.Exception = xfail.Exception + setattr(pytest, "xfail", nop) + + config.addinivalue_line( + "markers", + "skip(reason=None): skip the given test function with an optional reason. " + 'Example: skip(reason="no way of currently testing this") skips the ' + "test.", + ) + config.addinivalue_line( + "markers", + "skipif(condition): skip the given test function if eval(condition) " + "results in a True value. Evaluation happens within the " + "module global context. Example: skipif('sys.platform == \"win32\"') " + "skips the test if we are on the win32 platform. see " + "https://docs.pytest.org/en/latest/skipping.html", + ) + config.addinivalue_line( + "markers", + "xfail(condition, reason=None, run=True, raises=None, strict=False): " + "mark the test function as an expected failure if eval(condition) " + "has a True value. Optionally specify a reason for better reporting " + "and run=False if you don't even want to execute the test function. " + "If only specific exception(s) are expected, you can list them in " + "raises, and if the test fails in other ways, it will be reported as " + "a true failure. See https://docs.pytest.org/en/latest/skipping.html", + ) + + +@hookimpl(tryfirst=True) +def pytest_runtest_setup(item): + # Check if skip or skipif are specified as pytest marks + item._skipped_by_mark = False + eval_skipif = MarkEvaluator(item, "skipif") + if eval_skipif.istrue(): + item._skipped_by_mark = True + skip(eval_skipif.getexplanation()) + + for skip_info in item.iter_markers(name="skip"): + item._skipped_by_mark = True + if "reason" in skip_info.kwargs: + skip(skip_info.kwargs["reason"]) + elif skip_info.args: + skip(skip_info.args[0]) + else: + skip("unconditional skip") + + item._evalxfail = MarkEvaluator(item, "xfail") + check_xfail_no_run(item) + + +@hookimpl(hookwrapper=True) +def pytest_pyfunc_call(pyfuncitem): + check_xfail_no_run(pyfuncitem) + outcome = yield + passed = outcome.excinfo is None + if passed: + check_strict_xfail(pyfuncitem) + + +def check_xfail_no_run(item): + """check xfail(run=False)""" + if not item.config.option.runxfail: + evalxfail = item._evalxfail + if evalxfail.istrue(): + if not evalxfail.get("run", True): + xfail("[NOTRUN] " + evalxfail.getexplanation()) + + +def check_strict_xfail(pyfuncitem): + """check xfail(strict=True) for the given PASSING test""" + evalxfail = pyfuncitem._evalxfail + if evalxfail.istrue(): + strict_default = pyfuncitem.config.getini("xfail_strict") + is_strict_xfail = evalxfail.get("strict", strict_default) + if is_strict_xfail: + del pyfuncitem._evalxfail + explanation = evalxfail.getexplanation() + fail("[XPASS(strict)] " + explanation, pytrace=False) + + +@hookimpl(hookwrapper=True) +def pytest_runtest_makereport(item, call): + outcome = yield + rep = outcome.get_result() + evalxfail = getattr(item, "_evalxfail", None) + # unitttest special case, see setting of _unexpectedsuccess + if hasattr(item, "_unexpectedsuccess") and rep.when == "call": + from _pytest.compat import _is_unittest_unexpected_success_a_failure + + if item._unexpectedsuccess: + rep.longrepr = "Unexpected success: {}".format(item._unexpectedsuccess) + else: + rep.longrepr = "Unexpected success" + if _is_unittest_unexpected_success_a_failure(): + rep.outcome = "failed" + else: + rep.outcome = "passed" + rep.wasxfail = rep.longrepr + elif item.config.option.runxfail: + pass # don't interefere + elif call.excinfo and call.excinfo.errisinstance(xfail.Exception): + rep.wasxfail = "reason: " + call.excinfo.value.msg + rep.outcome = "skipped" + elif evalxfail and not rep.skipped and evalxfail.wasvalid() and evalxfail.istrue(): + if call.excinfo: + if evalxfail.invalidraise(call.excinfo.value): + rep.outcome = "failed" + else: + rep.outcome = "skipped" + rep.wasxfail = evalxfail.getexplanation() + elif call.when == "call": + strict_default = item.config.getini("xfail_strict") + is_strict_xfail = evalxfail.get("strict", strict_default) + explanation = evalxfail.getexplanation() + if is_strict_xfail: + rep.outcome = "failed" + rep.longrepr = "[XPASS(strict)] {}".format(explanation) + else: + rep.outcome = "passed" + rep.wasxfail = explanation + elif ( + getattr(item, "_skipped_by_mark", False) + and rep.skipped + and type(rep.longrepr) is tuple + ): + # skipped by mark.skipif; change the location of the failure + # to point to the item definition, otherwise it will display + # the location of where the skip exception was raised within pytest + filename, line, reason = rep.longrepr + filename, line = item.location[:2] + rep.longrepr = filename, line, reason + + +# called by terminalreporter progress reporting + + +def pytest_report_teststatus(report): + if hasattr(report, "wasxfail"): + if report.skipped: + return "xfailed", "x", "XFAIL" + elif report.passed: + return "xpassed", "X", "XPASS" diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/stepwise.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/stepwise.py new file mode 100644 index 0000000000000000000000000000000000000000..8890259589698838ed264f0139b5774e2d230e39 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/stepwise.py @@ -0,0 +1,109 @@ +# -*- coding: utf-8 -*- +import pytest + + +def pytest_addoption(parser): + group = parser.getgroup("general") + group.addoption( + "--sw", + "--stepwise", + action="store_true", + dest="stepwise", + help="exit on test failure and continue from last failing test next time", + ) + group.addoption( + "--stepwise-skip", + action="store_true", + dest="stepwise_skip", + help="ignore the first failing test but stop on the next failing test", + ) + + +@pytest.hookimpl +def pytest_configure(config): + config.pluginmanager.register(StepwisePlugin(config), "stepwiseplugin") + + +class StepwisePlugin: + def __init__(self, config): + self.config = config + self.active = config.getvalue("stepwise") + self.session = None + self.report_status = "" + + if self.active: + self.lastfailed = config.cache.get("cache/stepwise", None) + self.skip = config.getvalue("stepwise_skip") + + def pytest_sessionstart(self, session): + self.session = session + + def pytest_collection_modifyitems(self, session, config, items): + if not self.active: + return + if not self.lastfailed: + self.report_status = "no previously failed tests, not skipping." + return + + already_passed = [] + found = False + + # Make a list of all tests that have been run before the last failing one. + for item in items: + if item.nodeid == self.lastfailed: + found = True + break + else: + already_passed.append(item) + + # If the previously failed test was not found among the test items, + # do not skip any tests. + if not found: + self.report_status = "previously failed test not found, not skipping." + already_passed = [] + else: + self.report_status = "skipping {} already passed items.".format( + len(already_passed) + ) + + for item in already_passed: + items.remove(item) + + config.hook.pytest_deselected(items=already_passed) + + def pytest_runtest_logreport(self, report): + if not self.active: + return + + if report.failed: + if self.skip: + # Remove test from the failed ones (if it exists) and unset the skip option + # to make sure the following tests will not be skipped. + if report.nodeid == self.lastfailed: + self.lastfailed = None + + self.skip = False + else: + # Mark test as the last failing and interrupt the test session. + self.lastfailed = report.nodeid + self.session.shouldstop = ( + "Test failed, continuing from this test next run." + ) + + else: + # If the test was actually run and did pass. + if report.when == "call": + # Remove test from the failed ones, if exists. + if report.nodeid == self.lastfailed: + self.lastfailed = None + + def pytest_report_collectionfinish(self): + if self.active and self.config.getoption("verbose") >= 0 and self.report_status: + return "stepwise: %s" % self.report_status + + def pytest_sessionfinish(self, session): + if self.active: + self.config.cache.set("cache/stepwise", self.lastfailed) + else: + # Clear the list of failing tests if the plugin is not active. + self.config.cache.set("cache/stepwise", []) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/terminal.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/terminal.py new file mode 100644 index 0000000000000000000000000000000000000000..eb1970d5103fd892c49c98c40809abd136e48af5 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/terminal.py @@ -0,0 +1,1085 @@ +# -*- coding: utf-8 -*- +""" terminal reporting of the full testing process. + +This is a good source for looking at the various reporting hooks. +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import argparse +import collections +import platform +import sys +import time +from functools import partial + +import attr +import pluggy +import py +import six +from more_itertools import collapse + +import pytest +from _pytest import nodes +from _pytest.main import EXIT_INTERRUPTED +from _pytest.main import EXIT_NOTESTSCOLLECTED +from _pytest.main import EXIT_OK +from _pytest.main import EXIT_TESTSFAILED +from _pytest.main import EXIT_USAGEERROR + +REPORT_COLLECTING_RESOLUTION = 0.5 + + +class MoreQuietAction(argparse.Action): + """ + a modified copy of the argparse count action which counts down and updates + the legacy quiet attribute at the same time + + used to unify verbosity handling + """ + + def __init__(self, option_strings, dest, default=None, required=False, help=None): + super(MoreQuietAction, self).__init__( + option_strings=option_strings, + dest=dest, + nargs=0, + default=default, + required=required, + help=help, + ) + + def __call__(self, parser, namespace, values, option_string=None): + new_count = getattr(namespace, self.dest, 0) - 1 + setattr(namespace, self.dest, new_count) + # todo Deprecate config.quiet + namespace.quiet = getattr(namespace, "quiet", 0) + 1 + + +def pytest_addoption(parser): + group = parser.getgroup("terminal reporting", "reporting", after="general") + group._addoption( + "-v", + "--verbose", + action="count", + default=0, + dest="verbose", + help="increase verbosity.", + ), + group._addoption( + "-q", + "--quiet", + action=MoreQuietAction, + default=0, + dest="verbose", + help="decrease verbosity.", + ), + group._addoption( + "--verbosity", dest="verbose", type=int, default=0, help="set verbosity" + ) + group._addoption( + "-r", + action="store", + dest="reportchars", + default="", + metavar="chars", + help="show extra test summary info as specified by chars: (f)ailed, " + "(E)rror, (s)kipped, (x)failed, (X)passed, " + "(p)assed, (P)assed with output, (a)ll except passed (p/P), or (A)ll. " + "Warnings are displayed at all times except when " + "--disable-warnings is set.", + ) + group._addoption( + "--disable-warnings", + "--disable-pytest-warnings", + default=False, + dest="disable_warnings", + action="store_true", + help="disable warnings summary", + ) + group._addoption( + "-l", + "--showlocals", + action="store_true", + dest="showlocals", + default=False, + help="show locals in tracebacks (disabled by default).", + ) + group._addoption( + "--tb", + metavar="style", + action="store", + dest="tbstyle", + default="auto", + choices=["auto", "long", "short", "no", "line", "native"], + help="traceback print mode (auto/long/short/line/native/no).", + ) + group._addoption( + "--show-capture", + action="store", + dest="showcapture", + choices=["no", "stdout", "stderr", "log", "all"], + default="all", + help="Controls how captured stdout/stderr/log is shown on failed tests. " + "Default is 'all'.", + ) + group._addoption( + "--fulltrace", + "--full-trace", + action="store_true", + default=False, + help="don't cut any tracebacks (default is to cut).", + ) + group._addoption( + "--color", + metavar="color", + action="store", + dest="color", + default="auto", + choices=["yes", "no", "auto"], + help="color terminal output (yes/no/auto).", + ) + + parser.addini( + "console_output_style", + help='console output: "classic", or with additional progress information ("progress" (percentage) | "count").', + default="progress", + ) + + +def pytest_configure(config): + reporter = TerminalReporter(config, sys.stdout) + config.pluginmanager.register(reporter, "terminalreporter") + if config.option.debug or config.option.traceconfig: + + def mywriter(tags, args): + msg = " ".join(map(str, args)) + reporter.write_line("[traceconfig] " + msg) + + config.trace.root.setprocessor("pytest:config", mywriter) + + +def getreportopt(config): + reportopts = "" + reportchars = config.option.reportchars + if not config.option.disable_warnings and "w" not in reportchars: + reportchars += "w" + elif config.option.disable_warnings and "w" in reportchars: + reportchars = reportchars.replace("w", "") + for char in reportchars: + if char == "a": + reportopts = "sxXwEf" + elif char == "A": + reportopts = "PpsxXwEf" + break + elif char not in reportopts: + reportopts += char + return reportopts + + +@pytest.hookimpl(trylast=True) # after _pytest.runner +def pytest_report_teststatus(report): + if report.passed: + letter = "." + elif report.skipped: + letter = "s" + elif report.failed: + letter = "F" + if report.when != "call": + letter = "f" + return report.outcome, letter, report.outcome.upper() + + +@attr.s +class WarningReport(object): + """ + Simple structure to hold warnings information captured by ``pytest_warning_captured``. + + :ivar str message: user friendly message about the warning + :ivar str|None nodeid: node id that generated the warning (see ``get_location``). + :ivar tuple|py.path.local fslocation: + file system location of the source of the warning (see ``get_location``). + """ + + message = attr.ib() + nodeid = attr.ib(default=None) + fslocation = attr.ib(default=None) + count_towards_summary = True + + def get_location(self, config): + """ + Returns the more user-friendly information about the location + of a warning, or None. + """ + if self.nodeid: + return self.nodeid + if self.fslocation: + if isinstance(self.fslocation, tuple) and len(self.fslocation) >= 2: + filename, linenum = self.fslocation[:2] + relpath = py.path.local(filename).relto(config.invocation_dir) + if not relpath: + relpath = str(filename) + return "%s:%s" % (relpath, linenum) + else: + return str(self.fslocation) + return None + + +class TerminalReporter(object): + def __init__(self, config, file=None): + import _pytest.config + + self.config = config + self._numcollected = 0 + self._session = None + self._showfspath = None + + self.stats = {} + self.startdir = config.invocation_dir + if file is None: + file = sys.stdout + self._tw = _pytest.config.create_terminal_writer(config, file) + # self.writer will be deprecated in pytest-3.4 + self.writer = self._tw + self._screen_width = self._tw.fullwidth + self.currentfspath = None + self.reportchars = getreportopt(config) + self.hasmarkup = self._tw.hasmarkup + self.isatty = file.isatty() + self._progress_nodeids_reported = set() + self._show_progress_info = self._determine_show_progress_info() + self._collect_report_last_write = None + + def _determine_show_progress_info(self): + """Return True if we should display progress information based on the current config""" + # do not show progress if we are not capturing output (#3038) + if self.config.getoption("capture", "no") == "no": + return False + # do not show progress if we are showing fixture setup/teardown + if self.config.getoption("setupshow", False): + return False + cfg = self.config.getini("console_output_style") + if cfg in ("progress", "count"): + return cfg + return False + + @property + def verbosity(self): + return self.config.option.verbose + + @property + def showheader(self): + return self.verbosity >= 0 + + @property + def showfspath(self): + if self._showfspath is None: + return self.verbosity >= 0 + return self._showfspath + + @showfspath.setter + def showfspath(self, value): + self._showfspath = value + + @property + def showlongtestinfo(self): + return self.verbosity > 0 + + def hasopt(self, char): + char = {"xfailed": "x", "skipped": "s"}.get(char, char) + return char in self.reportchars + + def write_fspath_result(self, nodeid, res, **markup): + fspath = self.config.rootdir.join(nodeid.split("::")[0]) + # NOTE: explicitly check for None to work around py bug, and for less + # overhead in general (https://github.com/pytest-dev/py/pull/207). + if self.currentfspath is None or fspath != self.currentfspath: + if self.currentfspath is not None and self._show_progress_info: + self._write_progress_information_filling_space() + self.currentfspath = fspath + fspath = self.startdir.bestrelpath(fspath) + self._tw.line() + self._tw.write(fspath + " ") + self._tw.write(res, **markup) + + def write_ensure_prefix(self, prefix, extra="", **kwargs): + if self.currentfspath != prefix: + self._tw.line() + self.currentfspath = prefix + self._tw.write(prefix) + if extra: + self._tw.write(extra, **kwargs) + self.currentfspath = -2 + + def ensure_newline(self): + if self.currentfspath: + self._tw.line() + self.currentfspath = None + + def write(self, content, **markup): + self._tw.write(content, **markup) + + def write_line(self, line, **markup): + if not isinstance(line, six.text_type): + line = six.text_type(line, errors="replace") + self.ensure_newline() + self._tw.line(line, **markup) + + def rewrite(self, line, **markup): + """ + Rewinds the terminal cursor to the beginning and writes the given line. + + :kwarg erase: if True, will also add spaces until the full terminal width to ensure + previous lines are properly erased. + + The rest of the keyword arguments are markup instructions. + """ + erase = markup.pop("erase", False) + if erase: + fill_count = self._tw.fullwidth - len(line) - 1 + fill = " " * fill_count + else: + fill = "" + line = str(line) + self._tw.write("\r" + line + fill, **markup) + + def write_sep(self, sep, title=None, **markup): + self.ensure_newline() + self._tw.sep(sep, title, **markup) + + def section(self, title, sep="=", **kw): + self._tw.sep(sep, title, **kw) + + def line(self, msg, **kw): + self._tw.line(msg, **kw) + + def pytest_internalerror(self, excrepr): + for line in six.text_type(excrepr).split("\n"): + self.write_line("INTERNALERROR> " + line) + return 1 + + def pytest_warning_captured(self, warning_message, item): + # from _pytest.nodes import get_fslocation_from_item + from _pytest.warnings import warning_record_to_str + + warnings = self.stats.setdefault("warnings", []) + fslocation = warning_message.filename, warning_message.lineno + message = warning_record_to_str(warning_message) + + nodeid = item.nodeid if item is not None else "" + warning_report = WarningReport( + fslocation=fslocation, message=message, nodeid=nodeid + ) + warnings.append(warning_report) + + def pytest_plugin_registered(self, plugin): + if self.config.option.traceconfig: + msg = "PLUGIN registered: %s" % (plugin,) + # XXX this event may happen during setup/teardown time + # which unfortunately captures our output here + # which garbles our output if we use self.write_line + self.write_line(msg) + + def pytest_deselected(self, items): + self.stats.setdefault("deselected", []).extend(items) + + def pytest_runtest_logstart(self, nodeid, location): + # ensure that the path is printed before the + # 1st test of a module starts running + if self.showlongtestinfo: + line = self._locationline(nodeid, *location) + self.write_ensure_prefix(line, "") + elif self.showfspath: + fsid = nodeid.split("::")[0] + self.write_fspath_result(fsid, "") + + def pytest_runtest_logreport(self, report): + self._tests_ran = True + rep = report + res = self.config.hook.pytest_report_teststatus(report=rep, config=self.config) + category, letter, word = res + if isinstance(word, tuple): + word, markup = word + else: + markup = None + self.stats.setdefault(category, []).append(rep) + if not letter and not word: + # probably passed setup/teardown + return + running_xdist = hasattr(rep, "node") + if markup is None: + was_xfail = hasattr(report, "wasxfail") + if rep.passed and not was_xfail: + markup = {"green": True} + elif rep.passed and was_xfail: + markup = {"yellow": True} + elif rep.failed: + markup = {"red": True} + elif rep.skipped: + markup = {"yellow": True} + else: + markup = {} + if self.verbosity <= 0: + if not running_xdist and self.showfspath: + self.write_fspath_result(rep.nodeid, letter, **markup) + else: + self._tw.write(letter, **markup) + else: + self._progress_nodeids_reported.add(rep.nodeid) + line = self._locationline(rep.nodeid, *rep.location) + if not running_xdist: + self.write_ensure_prefix(line, word, **markup) + if self._show_progress_info: + self._write_progress_information_filling_space() + else: + self.ensure_newline() + self._tw.write("[%s]" % rep.node.gateway.id) + if self._show_progress_info: + self._tw.write( + self._get_progress_information_message() + " ", cyan=True + ) + else: + self._tw.write(" ") + self._tw.write(word, **markup) + self._tw.write(" " + line) + self.currentfspath = -2 + + def pytest_runtest_logfinish(self, nodeid): + if self.verbosity <= 0 and self._show_progress_info: + if self._show_progress_info == "count": + num_tests = self._session.testscollected + progress_length = len(" [{}/{}]".format(str(num_tests), str(num_tests))) + else: + progress_length = len(" [100%]") + + self._progress_nodeids_reported.add(nodeid) + is_last_item = ( + len(self._progress_nodeids_reported) == self._session.testscollected + ) + if is_last_item: + self._write_progress_information_filling_space() + else: + w = self._width_of_current_line + past_edge = w + progress_length + 1 >= self._screen_width + if past_edge: + msg = self._get_progress_information_message() + self._tw.write(msg + "\n", cyan=True) + + def _get_progress_information_message(self): + collected = self._session.testscollected + if self._show_progress_info == "count": + if collected: + progress = self._progress_nodeids_reported + counter_format = "{{:{}d}}".format(len(str(collected))) + format_string = " [{}/{{}}]".format(counter_format) + return format_string.format(len(progress), collected) + return " [ {} / {} ]".format(collected, collected) + else: + if collected: + progress = len(self._progress_nodeids_reported) * 100 // collected + return " [{:3d}%]".format(progress) + return " [100%]" + + def _write_progress_information_filling_space(self): + msg = self._get_progress_information_message() + w = self._width_of_current_line + fill = self._tw.fullwidth - w - 1 + self.write(msg.rjust(fill), cyan=True) + + @property + def _width_of_current_line(self): + """Return the width of current line, using the superior implementation of py-1.6 when available""" + try: + return self._tw.width_of_current_line + except AttributeError: + # py < 1.6.0 + return self._tw.chars_on_current_line + + def pytest_collection(self): + if self.isatty: + if self.config.option.verbose >= 0: + self.write("collecting ... ", bold=True) + self._collect_report_last_write = time.time() + elif self.config.option.verbose >= 1: + self.write("collecting ... ", bold=True) + + def pytest_collectreport(self, report): + if report.failed: + self.stats.setdefault("error", []).append(report) + elif report.skipped: + self.stats.setdefault("skipped", []).append(report) + items = [x for x in report.result if isinstance(x, pytest.Item)] + self._numcollected += len(items) + if self.isatty: + self.report_collect() + + def report_collect(self, final=False): + if self.config.option.verbose < 0: + return + + if not final: + # Only write "collecting" report every 0.5s. + t = time.time() + if ( + self._collect_report_last_write is not None + and self._collect_report_last_write > t - REPORT_COLLECTING_RESOLUTION + ): + return + self._collect_report_last_write = t + + errors = len(self.stats.get("error", [])) + skipped = len(self.stats.get("skipped", [])) + deselected = len(self.stats.get("deselected", [])) + selected = self._numcollected - errors - skipped - deselected + if final: + line = "collected " + else: + line = "collecting " + line += ( + str(self._numcollected) + " item" + ("" if self._numcollected == 1 else "s") + ) + if errors: + line += " / %d errors" % errors + if deselected: + line += " / %d deselected" % deselected + if skipped: + line += " / %d skipped" % skipped + if self._numcollected > selected > 0: + line += " / %d selected" % selected + if self.isatty: + self.rewrite(line, bold=True, erase=True) + if final: + self.write("\n") + else: + self.write_line(line) + + @pytest.hookimpl(trylast=True) + def pytest_sessionstart(self, session): + self._session = session + self._sessionstarttime = time.time() + if not self.showheader: + return + self.write_sep("=", "test session starts", bold=True) + verinfo = platform.python_version() + msg = "platform %s -- Python %s" % (sys.platform, verinfo) + if hasattr(sys, "pypy_version_info"): + verinfo = ".".join(map(str, sys.pypy_version_info[:3])) + msg += "[pypy-%s-%s]" % (verinfo, sys.pypy_version_info[3]) + msg += ", pytest-%s, py-%s, pluggy-%s" % ( + pytest.__version__, + py.__version__, + pluggy.__version__, + ) + if ( + self.verbosity > 0 + or self.config.option.debug + or getattr(self.config.option, "pastebin", None) + ): + msg += " -- " + str(sys.executable) + self.write_line(msg) + lines = self.config.hook.pytest_report_header( + config=self.config, startdir=self.startdir + ) + self._write_report_lines_from_hooks(lines) + + def _write_report_lines_from_hooks(self, lines): + lines.reverse() + for line in collapse(lines): + self.write_line(line) + + def pytest_report_header(self, config): + line = "rootdir: %s" % config.rootdir + + if config.inifile: + line += ", inifile: " + config.rootdir.bestrelpath(config.inifile) + + testpaths = config.getini("testpaths") + if testpaths and config.args == testpaths: + rel_paths = [config.rootdir.bestrelpath(x) for x in testpaths] + line += ", testpaths: {}".format(", ".join(rel_paths)) + result = [line] + + plugininfo = config.pluginmanager.list_plugin_distinfo() + if plugininfo: + result.append("plugins: %s" % ", ".join(_plugin_nameversions(plugininfo))) + return result + + def pytest_collection_finish(self, session): + self.report_collect(True) + + if self.config.getoption("collectonly"): + self._printcollecteditems(session.items) + + lines = self.config.hook.pytest_report_collectionfinish( + config=self.config, startdir=self.startdir, items=session.items + ) + self._write_report_lines_from_hooks(lines) + + if self.config.getoption("collectonly"): + if self.stats.get("failed"): + self._tw.sep("!", "collection failures") + for rep in self.stats.get("failed"): + rep.toterminal(self._tw) + + def _printcollecteditems(self, items): + # to print out items and their parent collectors + # we take care to leave out Instances aka () + # because later versions are going to get rid of them anyway + if self.config.option.verbose < 0: + if self.config.option.verbose < -1: + counts = {} + for item in items: + name = item.nodeid.split("::", 1)[0] + counts[name] = counts.get(name, 0) + 1 + for name, count in sorted(counts.items()): + self._tw.line("%s: %d" % (name, count)) + else: + for item in items: + self._tw.line(item.nodeid) + return + stack = [] + indent = "" + for item in items: + needed_collectors = item.listchain()[1:] # strip root node + while stack: + if stack == needed_collectors[: len(stack)]: + break + stack.pop() + for col in needed_collectors[len(stack) :]: + stack.append(col) + if col.name == "()": # Skip Instances. + continue + indent = (len(stack) - 1) * " " + self._tw.line("%s%s" % (indent, col)) + if self.config.option.verbose >= 1: + if hasattr(col, "_obj") and col._obj.__doc__: + for line in col._obj.__doc__.strip().splitlines(): + self._tw.line("%s%s" % (indent + " ", line.strip())) + + @pytest.hookimpl(hookwrapper=True) + def pytest_sessionfinish(self, exitstatus): + outcome = yield + outcome.get_result() + self._tw.line("") + summary_exit_codes = ( + EXIT_OK, + EXIT_TESTSFAILED, + EXIT_INTERRUPTED, + EXIT_USAGEERROR, + EXIT_NOTESTSCOLLECTED, + ) + if exitstatus in summary_exit_codes: + self.config.hook.pytest_terminal_summary( + terminalreporter=self, exitstatus=exitstatus, config=self.config + ) + if exitstatus == EXIT_INTERRUPTED: + self._report_keyboardinterrupt() + del self._keyboardinterrupt_memo + self.summary_stats() + + @pytest.hookimpl(hookwrapper=True) + def pytest_terminal_summary(self): + self.summary_errors() + self.summary_failures() + self.summary_warnings() + self.summary_passes() + yield + self.short_test_summary() + # Display any extra warnings from teardown here (if any). + self.summary_warnings() + + def pytest_keyboard_interrupt(self, excinfo): + self._keyboardinterrupt_memo = excinfo.getrepr(funcargs=True) + + def pytest_unconfigure(self): + if hasattr(self, "_keyboardinterrupt_memo"): + self._report_keyboardinterrupt() + + def _report_keyboardinterrupt(self): + excrepr = self._keyboardinterrupt_memo + msg = excrepr.reprcrash.message + self.write_sep("!", msg) + if "KeyboardInterrupt" in msg: + if self.config.option.fulltrace: + excrepr.toterminal(self._tw) + else: + excrepr.reprcrash.toterminal(self._tw) + self._tw.line( + "(to show a full traceback on KeyboardInterrupt use --fulltrace)", + yellow=True, + ) + + def _locationline(self, nodeid, fspath, lineno, domain): + def mkrel(nodeid): + line = self.config.cwd_relative_nodeid(nodeid) + if domain and line.endswith(domain): + line = line[: -len(domain)] + values = domain.split("[") + values[0] = values[0].replace(".", "::") # don't replace '.' in params + line += "[".join(values) + return line + + # collect_fspath comes from testid which has a "/"-normalized path + + if fspath: + res = mkrel(nodeid) + if self.verbosity >= 2 and nodeid.split("::")[0] != fspath.replace( + "\\", nodes.SEP + ): + res += " <- " + self.startdir.bestrelpath(fspath) + else: + res = "[location]" + return res + " " + + def _getfailureheadline(self, rep): + head_line = rep.head_line + if head_line: + return head_line + return "test session" # XXX? + + def _getcrashline(self, rep): + try: + return str(rep.longrepr.reprcrash) + except AttributeError: + try: + return str(rep.longrepr)[:50] + except AttributeError: + return "" + + # + # summaries for sessionfinish + # + def getreports(self, name): + values = [] + for x in self.stats.get(name, []): + if not hasattr(x, "_pdbshown"): + values.append(x) + return values + + def summary_warnings(self): + if self.hasopt("w"): + all_warnings = self.stats.get("warnings") + if not all_warnings: + return + + final = hasattr(self, "_already_displayed_warnings") + if final: + warning_reports = all_warnings[self._already_displayed_warnings :] + else: + warning_reports = all_warnings + self._already_displayed_warnings = len(warning_reports) + if not warning_reports: + return + + reports_grouped_by_message = collections.OrderedDict() + for wr in warning_reports: + reports_grouped_by_message.setdefault(wr.message, []).append(wr) + + title = "warnings summary (final)" if final else "warnings summary" + self.write_sep("=", title, yellow=True, bold=False) + for message, warning_reports in reports_grouped_by_message.items(): + has_any_location = False + for w in warning_reports: + location = w.get_location(self.config) + if location: + self._tw.line(str(location)) + has_any_location = True + if has_any_location: + lines = message.splitlines() + indented = "\n".join(" " + x for x in lines) + message = indented.rstrip() + else: + message = message.rstrip() + self._tw.line(message) + self._tw.line() + self._tw.line("-- Docs: https://docs.pytest.org/en/latest/warnings.html") + + def summary_passes(self): + if self.config.option.tbstyle != "no": + if self.hasopt("P"): + reports = self.getreports("passed") + if not reports: + return + self.write_sep("=", "PASSES") + for rep in reports: + if rep.sections: + msg = self._getfailureheadline(rep) + self.write_sep("_", msg, green=True, bold=True) + self._outrep_summary(rep) + + def print_teardown_sections(self, rep): + showcapture = self.config.option.showcapture + if showcapture == "no": + return + for secname, content in rep.sections: + if showcapture != "all" and showcapture not in secname: + continue + if "teardown" in secname: + self._tw.sep("-", secname) + if content[-1:] == "\n": + content = content[:-1] + self._tw.line(content) + + def summary_failures(self): + if self.config.option.tbstyle != "no": + reports = self.getreports("failed") + if not reports: + return + self.write_sep("=", "FAILURES") + if self.config.option.tbstyle == "line": + for rep in reports: + line = self._getcrashline(rep) + self.write_line(line) + else: + teardown_sections = {} + for report in self.getreports(""): + if report.when == "teardown": + teardown_sections.setdefault(report.nodeid, []).append(report) + + for rep in reports: + msg = self._getfailureheadline(rep) + self.write_sep("_", msg, red=True, bold=True) + self._outrep_summary(rep) + for report in teardown_sections.get(rep.nodeid, []): + self.print_teardown_sections(report) + + def summary_errors(self): + if self.config.option.tbstyle != "no": + reports = self.getreports("error") + if not reports: + return + self.write_sep("=", "ERRORS") + for rep in self.stats["error"]: + msg = self._getfailureheadline(rep) + if rep.when == "collect": + msg = "ERROR collecting " + msg + else: + msg = "ERROR at %s of %s" % (rep.when, msg) + self.write_sep("_", msg, red=True, bold=True) + self._outrep_summary(rep) + + def _outrep_summary(self, rep): + rep.toterminal(self._tw) + showcapture = self.config.option.showcapture + if showcapture == "no": + return + for secname, content in rep.sections: + if showcapture != "all" and showcapture not in secname: + continue + self._tw.sep("-", secname) + if content[-1:] == "\n": + content = content[:-1] + self._tw.line(content) + + def summary_stats(self): + session_duration = time.time() - self._sessionstarttime + (line, color) = build_summary_stats_line(self.stats) + msg = "%s in %.2f seconds" % (line, session_duration) + markup = {color: True, "bold": True} + + if self.verbosity >= 0: + self.write_sep("=", msg, **markup) + if self.verbosity == -1: + self.write_line(msg, **markup) + + def short_test_summary(self): + if not self.reportchars: + return + + def show_simple(stat, lines): + failed = self.stats.get(stat, []) + if not failed: + return + termwidth = self.writer.fullwidth + config = self.config + for rep in failed: + line = _get_line_with_reprcrash_message(config, rep, termwidth) + lines.append(line) + + def show_xfailed(lines): + xfailed = self.stats.get("xfailed", []) + for rep in xfailed: + verbose_word = rep._get_verbose_word(self.config) + pos = _get_pos(self.config, rep) + lines.append("%s %s" % (verbose_word, pos)) + reason = rep.wasxfail + if reason: + lines.append(" " + str(reason)) + + def show_xpassed(lines): + xpassed = self.stats.get("xpassed", []) + for rep in xpassed: + verbose_word = rep._get_verbose_word(self.config) + pos = _get_pos(self.config, rep) + reason = rep.wasxfail + lines.append("%s %s %s" % (verbose_word, pos, reason)) + + def show_skipped(lines): + skipped = self.stats.get("skipped", []) + fskips = _folded_skips(skipped) if skipped else [] + if not fskips: + return + verbose_word = skipped[0]._get_verbose_word(self.config) + for num, fspath, lineno, reason in fskips: + if reason.startswith("Skipped: "): + reason = reason[9:] + if lineno is not None: + lines.append( + "%s [%d] %s:%d: %s" + % (verbose_word, num, fspath, lineno + 1, reason) + ) + else: + lines.append("%s [%d] %s: %s" % (verbose_word, num, fspath, reason)) + + REPORTCHAR_ACTIONS = { + "x": show_xfailed, + "X": show_xpassed, + "f": partial(show_simple, "failed"), + "F": partial(show_simple, "failed"), + "s": show_skipped, + "S": show_skipped, + "p": partial(show_simple, "passed"), + "E": partial(show_simple, "error"), + } + + lines = [] + for char in self.reportchars: + action = REPORTCHAR_ACTIONS.get(char) + if action: # skipping e.g. "P" (passed with output) here. + action(lines) + + if lines: + self.write_sep("=", "short test summary info") + for line in lines: + self.write_line(line) + + +def _get_pos(config, rep): + nodeid = config.cwd_relative_nodeid(rep.nodeid) + return nodeid + + +def _get_line_with_reprcrash_message(config, rep, termwidth): + """Get summary line for a report, trying to add reprcrash message.""" + from wcwidth import wcswidth + + verbose_word = rep._get_verbose_word(config) + pos = _get_pos(config, rep) + + line = "%s %s" % (verbose_word, pos) + len_line = wcswidth(line) + ellipsis, len_ellipsis = "...", 3 + if len_line > termwidth - len_ellipsis: + # No space for an additional message. + return line + + try: + msg = rep.longrepr.reprcrash.message + except AttributeError: + pass + else: + # Only use the first line. + i = msg.find("\n") + if i != -1: + msg = msg[:i] + len_msg = wcswidth(msg) + + sep, len_sep = " - ", 3 + max_len_msg = termwidth - len_line - len_sep + if max_len_msg >= len_ellipsis: + if len_msg > max_len_msg: + max_len_msg -= len_ellipsis + msg = msg[:max_len_msg] + while wcswidth(msg) > max_len_msg: + msg = msg[:-1] + if six.PY2: + # on python 2 systems with narrow unicode compilation, trying to + # get a single character out of a multi-byte unicode character such as + # u'😄' will result in a High Surrogate (U+D83D) character, which is + # rendered as u'�'; in this case we just strip that character out as it + # serves no purpose being rendered + try: + surrogate = six.unichr(0xD83D) + msg = msg.rstrip(surrogate) + except ValueError: # pragma: no cover + # Jython cannot represent this lone surrogate at all (#5256): + # ValueError: unichr() arg is a lone surrogate in range + # (0xD800, 0xDFFF) (Jython UTF-16 encoding) + # ignore this case as it shouldn't appear in the string anyway + pass + msg += ellipsis + line += sep + msg + return line + + +def _folded_skips(skipped): + d = {} + for event in skipped: + key = event.longrepr + assert len(key) == 3, (event, key) + keywords = getattr(event, "keywords", {}) + # folding reports with global pytestmark variable + # this is workaround, because for now we cannot identify the scope of a skip marker + # TODO: revisit after marks scope would be fixed + if ( + event.when == "setup" + and "skip" in keywords + and "pytestmark" not in keywords + ): + key = (key[0], None, key[2]) + d.setdefault(key, []).append(event) + values = [] + for key, events in d.items(): + values.append((len(events),) + key) + return values + + +def build_summary_stats_line(stats): + known_types = ( + "failed passed skipped deselected xfailed xpassed warnings error".split() + ) + unknown_type_seen = False + for found_type in stats: + if found_type not in known_types: + if found_type: # setup/teardown reports have an empty key, ignore them + known_types.append(found_type) + unknown_type_seen = True + parts = [] + for key in known_types: + reports = stats.get(key, None) + if reports: + count = sum( + 1 for rep in reports if getattr(rep, "count_towards_summary", True) + ) + parts.append("%d %s" % (count, key)) + + if parts: + line = ", ".join(parts) + else: + line = "no tests ran" + + if "failed" in stats or "error" in stats: + color = "red" + elif "warnings" in stats or unknown_type_seen: + color = "yellow" + elif "passed" in stats: + color = "green" + else: + color = "yellow" + + return line, color + + +def _plugin_nameversions(plugininfo): + values = [] + for plugin, dist in plugininfo: + # gets us name and version! + name = "{dist.project_name}-{dist.version}".format(dist=dist) + # questionable convenience, but it keeps things short + if name.startswith("pytest-"): + name = name[7:] + # we decided to print python package names + # they can have more than one plugin + if name not in values: + values.append(name) + return values diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/tmpdir.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/tmpdir.py new file mode 100644 index 0000000000000000000000000000000000000000..a8a7037713c8c786be0a507507e5d9588f694895 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/tmpdir.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +""" support for providing temporary directories to test functions. """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import re +import tempfile +import warnings + +import attr +import py +import six + +import pytest +from .pathlib import ensure_reset_dir +from .pathlib import LOCK_TIMEOUT +from .pathlib import make_numbered_dir +from .pathlib import make_numbered_dir_with_cleanup +from .pathlib import Path +from _pytest.monkeypatch import MonkeyPatch + + +@attr.s +class TempPathFactory(object): + """Factory for temporary directories under the common base temp directory. + + The base directory can be configured using the ``--basetemp`` option.""" + + _given_basetemp = attr.ib( + # using os.path.abspath() to get absolute path instead of resolve() as it + # does not work the same in all platforms (see #4427) + # Path.absolute() exists, but it is not public (see https://bugs.python.org/issue25012) + converter=attr.converters.optional( + lambda p: Path(os.path.abspath(six.text_type(p))) + ) + ) + _trace = attr.ib() + _basetemp = attr.ib(default=None) + + @classmethod + def from_config(cls, config): + """ + :param config: a pytest configuration + """ + return cls( + given_basetemp=config.option.basetemp, trace=config.trace.get("tmpdir") + ) + + def mktemp(self, basename, numbered=True): + """makes a temporary directory managed by the factory""" + if not numbered: + p = self.getbasetemp().joinpath(basename) + p.mkdir() + else: + p = make_numbered_dir(root=self.getbasetemp(), prefix=basename) + self._trace("mktemp", p) + return p + + def getbasetemp(self): + """ return base temporary directory. """ + if self._basetemp is not None: + return self._basetemp + + if self._given_basetemp is not None: + basetemp = self._given_basetemp + ensure_reset_dir(basetemp) + basetemp = basetemp.resolve() + else: + from_env = os.environ.get("PYTEST_DEBUG_TEMPROOT") + temproot = Path(from_env or tempfile.gettempdir()).resolve() + user = get_user() or "unknown" + # use a sub-directory in the temproot to speed-up + # make_numbered_dir() call + rootdir = temproot.joinpath("pytest-of-{}".format(user)) + rootdir.mkdir(exist_ok=True) + basetemp = make_numbered_dir_with_cleanup( + prefix="pytest-", root=rootdir, keep=3, lock_timeout=LOCK_TIMEOUT + ) + assert basetemp is not None, basetemp + self._basetemp = t = basetemp + self._trace("new basetemp", t) + return t + + +@attr.s +class TempdirFactory(object): + """ + backward comptibility wrapper that implements + :class:``py.path.local`` for :class:``TempPathFactory`` + """ + + _tmppath_factory = attr.ib() + + def ensuretemp(self, string, dir=1): + """ (deprecated) return temporary directory path with + the given string as the trailing part. It is usually + better to use the 'tmpdir' function argument which + provides an empty unique-per-test-invocation directory + and is guaranteed to be empty. + """ + # py.log._apiwarn(">1.1", "use tmpdir function argument") + from .deprecated import PYTEST_ENSURETEMP + + warnings.warn(PYTEST_ENSURETEMP, stacklevel=2) + return self.getbasetemp().ensure(string, dir=dir) + + def mktemp(self, basename, numbered=True): + """Create a subdirectory of the base temporary directory and return it. + If ``numbered``, ensure the directory is unique by adding a number + prefix greater than any existing one. + """ + return py.path.local(self._tmppath_factory.mktemp(basename, numbered).resolve()) + + def getbasetemp(self): + """backward compat wrapper for ``_tmppath_factory.getbasetemp``""" + return py.path.local(self._tmppath_factory.getbasetemp().resolve()) + + +def get_user(): + """Return the current user name, or None if getuser() does not work + in the current environment (see #1010). + """ + import getpass + + try: + return getpass.getuser() + except (ImportError, KeyError): + return None + + +def pytest_configure(config): + """Create a TempdirFactory and attach it to the config object. + + This is to comply with existing plugins which expect the handler to be + available at pytest_configure time, but ideally should be moved entirely + to the tmpdir_factory session fixture. + """ + mp = MonkeyPatch() + tmppath_handler = TempPathFactory.from_config(config) + t = TempdirFactory(tmppath_handler) + config._cleanup.append(mp.undo) + mp.setattr(config, "_tmp_path_factory", tmppath_handler, raising=False) + mp.setattr(config, "_tmpdirhandler", t, raising=False) + mp.setattr(pytest, "ensuretemp", t.ensuretemp, raising=False) + + +@pytest.fixture(scope="session") +def tmpdir_factory(request): + """Return a :class:`_pytest.tmpdir.TempdirFactory` instance for the test session. + """ + return request.config._tmpdirhandler + + +@pytest.fixture(scope="session") +def tmp_path_factory(request): + """Return a :class:`_pytest.tmpdir.TempPathFactory` instance for the test session. + """ + return request.config._tmp_path_factory + + +def _mk_tmp(request, factory): + name = request.node.name + name = re.sub(r"[\W]", "_", name) + MAXVAL = 30 + name = name[:MAXVAL] + return factory.mktemp(name, numbered=True) + + +@pytest.fixture +def tmpdir(tmp_path): + """Return a temporary directory path object + which is unique to each test function invocation, + created as a sub directory of the base temporary + directory. The returned object is a `py.path.local`_ + path object. + + .. _`py.path.local`: https://py.readthedocs.io/en/latest/path.html + """ + return py.path.local(tmp_path) + + +@pytest.fixture +def tmp_path(request, tmp_path_factory): + """Return a temporary directory path object + which is unique to each test function invocation, + created as a sub directory of the base temporary + directory. The returned object is a :class:`pathlib.Path` + object. + + .. note:: + + in python < 3.6 this is a pathlib2.Path + """ + + return _mk_tmp(request, tmp_path_factory) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/unittest.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/unittest.py new file mode 100644 index 0000000000000000000000000000000000000000..3ff6f45d8dbe78300ef6105312223456f962eacd --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/unittest.py @@ -0,0 +1,291 @@ +# -*- coding: utf-8 -*- +""" discovery and running of std-library "unittest" style tests. """ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import sys +import traceback + +import _pytest._code +import pytest +from _pytest.compat import getimfunc +from _pytest.config import hookimpl +from _pytest.outcomes import fail +from _pytest.outcomes import skip +from _pytest.outcomes import xfail +from _pytest.python import Class +from _pytest.python import Function + + +def pytest_pycollect_makeitem(collector, name, obj): + # has unittest been imported and is obj a subclass of its TestCase? + try: + if not issubclass(obj, sys.modules["unittest"].TestCase): + return + except Exception: + return + # yes, so let's collect it + return UnitTestCase(name, parent=collector) + + +class UnitTestCase(Class): + # marker for fixturemanger.getfixtureinfo() + # to declare that our children do not support funcargs + nofuncargs = True + + def collect(self): + from unittest import TestLoader + + cls = self.obj + if not getattr(cls, "__test__", True): + return + + skipped = getattr(cls, "__unittest_skip__", False) + if not skipped: + self._inject_setup_teardown_fixtures(cls) + self._inject_setup_class_fixture() + + self.session._fixturemanager.parsefactories(self, unittest=True) + loader = TestLoader() + foundsomething = False + for name in loader.getTestCaseNames(self.obj): + x = getattr(self.obj, name) + if not getattr(x, "__test__", True): + continue + funcobj = getimfunc(x) + yield TestCaseFunction(name, parent=self, callobj=funcobj) + foundsomething = True + + if not foundsomething: + runtest = getattr(self.obj, "runTest", None) + if runtest is not None: + ut = sys.modules.get("twisted.trial.unittest", None) + if ut is None or runtest != ut.TestCase.runTest: + yield TestCaseFunction("runTest", parent=self) + + def _inject_setup_teardown_fixtures(self, cls): + """Injects a hidden auto-use fixture to invoke setUpClass/setup_method and corresponding + teardown functions (#517)""" + class_fixture = _make_xunit_fixture( + cls, "setUpClass", "tearDownClass", scope="class", pass_self=False + ) + if class_fixture: + cls.__pytest_class_setup = class_fixture + + method_fixture = _make_xunit_fixture( + cls, "setup_method", "teardown_method", scope="function", pass_self=True + ) + if method_fixture: + cls.__pytest_method_setup = method_fixture + + +def _make_xunit_fixture(obj, setup_name, teardown_name, scope, pass_self): + setup = getattr(obj, setup_name, None) + teardown = getattr(obj, teardown_name, None) + if setup is None and teardown is None: + return None + + @pytest.fixture(scope=scope, autouse=True) + def fixture(self, request): + if getattr(self, "__unittest_skip__", None): + reason = self.__unittest_skip_why__ + pytest.skip(reason) + if setup is not None: + if pass_self: + setup(self, request.function) + else: + setup() + yield + if teardown is not None: + if pass_self: + teardown(self, request.function) + else: + teardown() + + return fixture + + +class TestCaseFunction(Function): + nofuncargs = True + _excinfo = None + _testcase = None + + def setup(self): + self._testcase = self.parent.obj(self.name) + self._fix_unittest_skip_decorator() + self._obj = getattr(self._testcase, self.name) + if hasattr(self, "_request"): + self._request._fillfixtures() + + def _fix_unittest_skip_decorator(self): + """ + The @unittest.skip decorator calls functools.wraps(self._testcase) + The call to functools.wraps() fails unless self._testcase + has a __name__ attribute. This is usually automatically supplied + if the test is a function or method, but we need to add manually + here. + + See issue #1169 + """ + if sys.version_info[0] == 2: + setattr(self._testcase, "__name__", self.name) + + def teardown(self): + self._testcase = None + self._obj = None + + def startTest(self, testcase): + pass + + def _addexcinfo(self, rawexcinfo): + # unwrap potential exception info (see twisted trial support below) + rawexcinfo = getattr(rawexcinfo, "_rawexcinfo", rawexcinfo) + try: + excinfo = _pytest._code.ExceptionInfo(rawexcinfo) + # invoke the attributes to trigger storing the traceback + # trial causes some issue there + excinfo.value + excinfo.traceback + except TypeError: + try: + try: + values = traceback.format_exception(*rawexcinfo) + values.insert( + 0, + "NOTE: Incompatible Exception Representation, " + "displaying natively:\n\n", + ) + fail("".join(values), pytrace=False) + except (fail.Exception, KeyboardInterrupt): + raise + except: # noqa + fail( + "ERROR: Unknown Incompatible Exception " + "representation:\n%r" % (rawexcinfo,), + pytrace=False, + ) + except KeyboardInterrupt: + raise + except fail.Exception: + excinfo = _pytest._code.ExceptionInfo.from_current() + self.__dict__.setdefault("_excinfo", []).append(excinfo) + + def addError(self, testcase, rawexcinfo): + self._addexcinfo(rawexcinfo) + + def addFailure(self, testcase, rawexcinfo): + self._addexcinfo(rawexcinfo) + + def addSkip(self, testcase, reason): + try: + skip(reason) + except skip.Exception: + self._skipped_by_mark = True + self._addexcinfo(sys.exc_info()) + + def addExpectedFailure(self, testcase, rawexcinfo, reason=""): + try: + xfail(str(reason)) + except xfail.Exception: + self._addexcinfo(sys.exc_info()) + + def addUnexpectedSuccess(self, testcase, reason=""): + self._unexpectedsuccess = reason + + def addSuccess(self, testcase): + pass + + def stopTest(self, testcase): + pass + + def _handle_skip(self): + # implements the skipping machinery (see #2137) + # analog to pythons Lib/unittest/case.py:run + testMethod = getattr(self._testcase, self._testcase._testMethodName) + if getattr(self._testcase.__class__, "__unittest_skip__", False) or getattr( + testMethod, "__unittest_skip__", False + ): + # If the class or method was skipped. + skip_why = getattr( + self._testcase.__class__, "__unittest_skip_why__", "" + ) or getattr(testMethod, "__unittest_skip_why__", "") + try: # PY3, unittest2 on PY2 + self._testcase._addSkip(self, self._testcase, skip_why) + except TypeError: # PY2 + if sys.version_info[0] != 2: + raise + self._testcase._addSkip(self, skip_why) + return True + return False + + def runtest(self): + if self.config.pluginmanager.get_plugin("pdbinvoke") is None: + self._testcase(result=self) + else: + # disables tearDown and cleanups for post mortem debugging (see #1890) + if self._handle_skip(): + return + self._testcase.debug() + + def _prunetraceback(self, excinfo): + Function._prunetraceback(self, excinfo) + traceback = excinfo.traceback.filter( + lambda x: not x.frame.f_globals.get("__unittest") + ) + if traceback: + excinfo.traceback = traceback + + +@hookimpl(tryfirst=True) +def pytest_runtest_makereport(item, call): + if isinstance(item, TestCaseFunction): + if item._excinfo: + call.excinfo = item._excinfo.pop(0) + try: + del call.result + except AttributeError: + pass + + +# twisted trial support + + +@hookimpl(hookwrapper=True) +def pytest_runtest_protocol(item): + if isinstance(item, TestCaseFunction) and "twisted.trial.unittest" in sys.modules: + ut = sys.modules["twisted.python.failure"] + Failure__init__ = ut.Failure.__init__ + check_testcase_implements_trial_reporter() + + def excstore( + self, exc_value=None, exc_type=None, exc_tb=None, captureVars=None + ): + if exc_value is None: + self._rawexcinfo = sys.exc_info() + else: + if exc_type is None: + exc_type = type(exc_value) + self._rawexcinfo = (exc_type, exc_value, exc_tb) + try: + Failure__init__( + self, exc_value, exc_type, exc_tb, captureVars=captureVars + ) + except TypeError: + Failure__init__(self, exc_value, exc_type, exc_tb) + + ut.Failure.__init__ = excstore + yield + ut.Failure.__init__ = Failure__init__ + else: + yield + + +def check_testcase_implements_trial_reporter(done=[]): + if done: + return + from zope.interface import classImplements + from twisted.trial.itrial import IReporter + + classImplements(TestCaseFunction, IReporter) + done.append(1) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/warning_types.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/warning_types.py new file mode 100644 index 0000000000000000000000000000000000000000..861010a1275d62cfe3357a9663d35e90181f5776 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/warning_types.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +import attr + + +class PytestWarning(UserWarning): + """ + Bases: :class:`UserWarning`. + + Base class for all warnings emitted by pytest. + """ + + +class PytestAssertRewriteWarning(PytestWarning): + """ + Bases: :class:`PytestWarning`. + + Warning emitted by the pytest assert rewrite module. + """ + + +class PytestCacheWarning(PytestWarning): + """ + Bases: :class:`PytestWarning`. + + Warning emitted by the cache plugin in various situations. + """ + + +class PytestConfigWarning(PytestWarning): + """ + Bases: :class:`PytestWarning`. + + Warning emitted for configuration issues. + """ + + +class PytestCollectionWarning(PytestWarning): + """ + Bases: :class:`PytestWarning`. + + Warning emitted when pytest is not able to collect a file or symbol in a module. + """ + + +class PytestDeprecationWarning(PytestWarning, DeprecationWarning): + """ + Bases: :class:`pytest.PytestWarning`, :class:`DeprecationWarning`. + + Warning class for features that will be removed in a future version. + """ + + +class PytestExperimentalApiWarning(PytestWarning, FutureWarning): + """ + Bases: :class:`pytest.PytestWarning`, :class:`FutureWarning`. + + Warning category used to denote experiments in pytest. Use sparingly as the API might change or even be + removed completely in future version + """ + + @classmethod + def simple(cls, apiname): + return cls( + "{apiname} is an experimental api that may change over time".format( + apiname=apiname + ) + ) + + +class PytestUnhandledCoroutineWarning(PytestWarning): + """ + Bases: :class:`PytestWarning`. + + Warning emitted when pytest encounters a test function which is a coroutine, + but it was not handled by any async-aware plugin. Coroutine test functions + are not natively supported. + """ + + +class PytestUnknownMarkWarning(PytestWarning): + """ + Bases: :class:`PytestWarning`. + + Warning emitted on use of unknown markers. + See https://docs.pytest.org/en/latest/mark.html for details. + """ + + +class RemovedInPytest4Warning(PytestDeprecationWarning): + """ + Bases: :class:`pytest.PytestDeprecationWarning`. + + Warning class for features scheduled to be removed in pytest 4.0. + """ + + +@attr.s +class UnformattedWarning(object): + """Used to hold warnings that need to format their message at runtime, as opposed to a direct message. + + Using this class avoids to keep all the warning types and messages in this module, avoiding misuse. + """ + + category = attr.ib() + template = attr.ib() + + def format(self, **kwargs): + """Returns an instance of the warning category, formatted with given kwargs""" + return self.category(self.template.format(**kwargs)) + + +PYTESTER_COPY_EXAMPLE = PytestExperimentalApiWarning.simple("testdir.copy_example") diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/warnings.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..a3debae462fc149e74788bc5cdf3c0276c9df07a --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_pytest/warnings.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import sys +import warnings +from contextlib import contextmanager + +import pytest +from _pytest import compat + +SHOW_PYTEST_WARNINGS_ARG = "-Walways::pytest.RemovedInPytest4Warning" + + +def _setoption(wmod, arg): + """ + Copy of the warning._setoption function but does not escape arguments. + """ + parts = arg.split(":") + if len(parts) > 5: + raise wmod._OptionError("too many fields (max 5): %r" % (arg,)) + while len(parts) < 5: + parts.append("") + action, message, category, module, lineno = [s.strip() for s in parts] + action = wmod._getaction(action) + category = wmod._getcategory(category) + if lineno: + try: + lineno = int(lineno) + if lineno < 0: + raise ValueError + except (ValueError, OverflowError): + raise wmod._OptionError("invalid lineno %r" % (lineno,)) + else: + lineno = 0 + wmod.filterwarnings(action, message, category, module, lineno) + + +def pytest_addoption(parser): + group = parser.getgroup("pytest-warnings") + group.addoption( + "-W", + "--pythonwarnings", + action="append", + help="set which warnings to report, see -W option of python itself.", + ) + parser.addini( + "filterwarnings", + type="linelist", + help="Each line specifies a pattern for " + "warnings.filterwarnings. " + "Processed after -W and --pythonwarnings.", + ) + + +def pytest_configure(config): + config.addinivalue_line( + "markers", + "filterwarnings(warning): add a warning filter to the given test. " + "see https://docs.pytest.org/en/latest/warnings.html#pytest-mark-filterwarnings ", + ) + + +@contextmanager +def catch_warnings_for_item(config, ihook, when, item): + """ + Context manager that catches warnings generated in the contained execution block. + + ``item`` can be None if we are not in the context of an item execution. + + Each warning captured triggers the ``pytest_warning_captured`` hook. + """ + cmdline_filters = config.getoption("pythonwarnings") or [] + inifilters = config.getini("filterwarnings") + with warnings.catch_warnings(record=True) as log: + + if not sys.warnoptions: + # if user is not explicitly configuring warning filters, show deprecation warnings by default (#2908) + warnings.filterwarnings("always", category=DeprecationWarning) + warnings.filterwarnings("always", category=PendingDeprecationWarning) + + warnings.filterwarnings("error", category=pytest.RemovedInPytest4Warning) + + # filters should have this precedence: mark, cmdline options, ini + # filters should be applied in the inverse order of precedence + for arg in inifilters: + _setoption(warnings, arg) + + for arg in cmdline_filters: + warnings._setoption(arg) + + if item is not None: + for mark in item.iter_markers(name="filterwarnings"): + for arg in mark.args: + _setoption(warnings, arg) + + yield + + for warning_message in log: + ihook.pytest_warning_captured.call_historic( + kwargs=dict(warning_message=warning_message, when=when, item=item) + ) + + +def warning_record_to_str(warning_message): + """Convert a warnings.WarningMessage to a string. + + This takes lot of unicode shenaningans into account for Python 2. + When Python 2 support is dropped this function can be greatly simplified. + """ + warn_msg = warning_message.message + unicode_warning = False + if compat._PY2 and any(isinstance(m, compat.UNICODE_TYPES) for m in warn_msg.args): + new_args = [] + for m in warn_msg.args: + new_args.append( + compat.ascii_escaped(m) if isinstance(m, compat.UNICODE_TYPES) else m + ) + unicode_warning = list(warn_msg.args) != new_args + warn_msg.args = new_args + + msg = warnings.formatwarning( + warn_msg, + warning_message.category, + warning_message.filename, + warning_message.lineno, + warning_message.line, + ) + if unicode_warning: + warnings.warn( + "Warning is using unicode non convertible to ascii, " + "converting to a safe representation:\n {!r}".format(compat.safe_str(msg)), + UnicodeWarning, + ) + return msg + + +@pytest.hookimpl(hookwrapper=True, tryfirst=True) +def pytest_runtest_protocol(item): + with catch_warnings_for_item( + config=item.config, ihook=item.ihook, when="runtest", item=item + ): + yield + + +@pytest.hookimpl(hookwrapper=True, tryfirst=True) +def pytest_collection(session): + config = session.config + with catch_warnings_for_item( + config=config, ihook=config.hook, when="collect", item=None + ): + yield + + +@pytest.hookimpl(hookwrapper=True) +def pytest_terminal_summary(terminalreporter): + config = terminalreporter.config + with catch_warnings_for_item( + config=config, ihook=config.hook, when="config", item=None + ): + yield + + +def _issue_warning_captured(warning, hook, stacklevel): + """ + This function should be used instead of calling ``warnings.warn`` directly when we are in the "configure" stage: + at this point the actual options might not have been set, so we manually trigger the pytest_warning_captured + hook so we can display this warnings in the terminal. This is a hack until we can sort out #2891. + + :param warning: the warning instance. + :param hook: the hook caller + :param stacklevel: stacklevel forwarded to warnings.warn + """ + with warnings.catch_warnings(record=True) as records: + warnings.simplefilter("always", type(warning)) + warnings.warn(warning, stacklevel=stacklevel) + hook.pytest_warning_captured.call_historic( + kwargs=dict(warning_message=records[0], when="config", item=None) + ) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_thread/__init__.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_thread/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9f2a51c75a1d4d92fd83e2f9717583aaecaeb482 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/_thread/__init__.py @@ -0,0 +1,10 @@ +from __future__ import absolute_import +import sys +__future_module__ = True + +if sys.version_info[0] < 3: + from thread import * +else: + raise ImportError('This package should not be accessible on Python 3. ' + 'Either you are trying to run from the python-future src folder ' + 'or your installation of python-future is corrupted.') diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/future-0.17.1.dist-info/METADATA b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/future-0.17.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..3eab81ac8c3ca05e6206ffb20e7217853f5ec25e --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/future-0.17.1.dist-info/METADATA @@ -0,0 +1,108 @@ +Metadata-Version: 2.1 +Name: future +Version: 0.17.1 +Summary: Clean single-source support for Python 3 and 2 +Home-page: https://python-future.org +Author: Ed Schofield +Author-email: ed@pythoncharmers.com +License: MIT +Keywords: future past python3 migration futurize backport six 2to3 modernize pasteurize 3to2 +Platform: UNKNOWN +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.6 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.3 +Classifier: Programming Language :: Python :: 3.4 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: License :: OSI Approved +Classifier: License :: OSI Approved :: MIT License +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Requires-Python: >=2.6, !=3.0.*, !=3.1.*, !=3.2.* + +future: Easy, safe support for Python 2/3 compatibility +======================================================= + +``future`` is the missing compatibility layer between Python 2 and Python +3. It allows you to use a single, clean Python 3.x-compatible codebase to +support both Python 2 and Python 3 with minimal overhead. + +It is designed to be used as follows:: + + from __future__ import (absolute_import, division, + print_function, unicode_literals) + from builtins import ( + bytes, dict, int, list, object, range, str, + ascii, chr, hex, input, next, oct, open, + pow, round, super, + filter, map, zip) + +followed by predominantly standard, idiomatic Python 3 code that then runs +similarly on Python 2.6/2.7 and Python 3.3+. + +The imports have no effect on Python 3. On Python 2, they shadow the +corresponding builtins, which normally have different semantics on Python 3 +versus 2, to provide their Python 3 semantics. + + +Standard library reorganization +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``future`` supports the standard library reorganization (PEP 3108) through the +following Py3 interfaces: + + >>> # Top-level packages with Py3 names provided on Py2: + >>> import html.parser + >>> import queue + >>> import tkinter.dialog + >>> import xmlrpc.client + >>> # etc. + + >>> # Aliases provided for extensions to existing Py2 module names: + >>> from future.standard_library import install_aliases + >>> install_aliases() + + >>> from collections import Counter, OrderedDict # backported to Py2.6 + >>> from collections import UserDict, UserList, UserString + >>> import urllib.request + >>> from itertools import filterfalse, zip_longest + >>> from subprocess import getoutput, getstatusoutput + + +Automatic conversion +-------------------- + +An included script called `futurize +`_ aids in converting +code (from either Python 2 or Python 3) to code compatible with both +platforms. It is similar to ``python-modernize`` but goes further in +providing Python 3 compatibility through the use of the backported types +and builtin functions in ``future``. + + +Documentation +------------- + +See: http://python-future.org + + +Credits +------- + +:Author: Ed Schofield +:Sponsor: Python Charmers Pty Ltd, Australia, and Python Charmers Pte + Ltd, Singapore. http://pythoncharmers.com +:Others: See docs/credits.rst or http://python-future.org/credits.html + + +Licensing +--------- +Copyright 2013-2018 Python Charmers Pty Ltd, Australia. +The software is distributed under an MIT licence. See LICENSE.txt. + + + diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/future-0.17.1.dist-info/RECORD b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/future-0.17.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..7a326d1dbeed8704a5242007e142b5b35a432f24 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/future-0.17.1.dist-info/RECORD @@ -0,0 +1,479 @@ +../../../bin/futurize,sha256=U_HChhoc5KKCNbaUqZ7wLyfFWGAsxyzeIU_WXfUrEHU,265 +../../../bin/pasteurize,sha256=sIjyFLZHlL1vRDYGGPMTppyxL3KvqElmGp3sbmqnxh0,267 +_dummy_thread/__init__.py,sha256=begqpGBCVphDD2uFYcyjJbBx0MxXUVUsEU7Gc_uju-E,382 +_dummy_thread/__init__.pyc,, +_markupbase/__init__.py,sha256=OilSwOSJKVzseSZ99XzFfwbSlR1Hy29Bc6jDod1Iic8,380 +_markupbase/__init__.pyc,, +_thread/__init__.py,sha256=INkkMfy0EKARxwlhjFbDcnWyW8pjgywB0p0inp59--Q,376 +_thread/__init__.pyc,, +builtins/__init__.py,sha256=ap2ury-2CspMkFhENf-NBXOvycVcXHDyKbpQAkHEvCc,493 +builtins/__init__.pyc,, +copyreg/__init__.py,sha256=r-OjTdT3JaOrTaESjThKNHOyPJU_Ys1RnWeMgXZqQNw,353 +copyreg/__init__.pyc,, +future-0.17.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +future-0.17.1.dist-info/LICENSE.txt,sha256=4cyh70QH2LtuPyLWyO5mDJEMIw_p02Vwx4cQvbwLZEA,1083 +future-0.17.1.dist-info/METADATA,sha256=DyCTgB4KqwI6ji_CiwJGVXUYbfCs8PyIDV-doBeka4I,3678 +future-0.17.1.dist-info/RECORD,, +future-0.17.1.dist-info/WHEEL,sha256=I79qopWJ69l5T6wZayt9VUOMecGZGPzu2_icbRYWjpI,93 +future-0.17.1.dist-info/entry_points.txt,sha256=-ATQtLUC2gkzrCYqc1Twac093xrI164NuMwsRALJWnM,89 +future-0.17.1.dist-info/top_level.txt,sha256=FeMOZFDhPdQ7-OS54GrX6l-U-WxUqVqO7i1sSXHbdkU,148 +future/__init__.py,sha256=FLf0rGoJiUjDY3WyuEwIRt3JRqKhf5umZ1mSqE3pqSU,2967 +future/__init__.pyc,, +future/backports/__init__.py,sha256=aw9s1PXLXokw_d6llcZmQKKyCwwXPkwsvNyywhqp3QI,530 +future/backports/__init__.pyc,, +future/backports/_markupbase.py,sha256=MDPTCykLq4J7Aea3PvYotATEE0CG4R_SjlxfJaLXTJM,16215 +future/backports/_markupbase.pyc,, +future/backports/datetime.py,sha256=I214Vu0cRY8mi8J5aIcsAyQJnWmOKXeLV-QTWSn7VQU,75552 +future/backports/datetime.pyc,, +future/backports/email/__init__.py,sha256=eH3AJr3FkuBy_D6yS1V2K76Q2CQ93y2zmAMWmn8FbHI,2269 +future/backports/email/__init__.pyc,, +future/backports/email/_encoded_words.py,sha256=m1vTRfxAQdg4VyWO7PF-1ih1mmq97V-BPyHHkuEwSME,8443 +future/backports/email/_encoded_words.pyc,, +future/backports/email/_header_value_parser.py,sha256=cj_1ce1voLn8H98r9cKqiSLgfFSxCv3_UL3sSvjqgjk,104692 +future/backports/email/_header_value_parser.pyc,, +future/backports/email/_parseaddr.py,sha256=KewEnos0YDM-SYX503z7E1MmVbG5VRaKjxjcl0Ipjbs,17389 +future/backports/email/_parseaddr.pyc,, +future/backports/email/_policybase.py,sha256=2lJD9xouiz4uHvWGQ6j1nwlwWVQGwwzpy5JZoeQqhUc,14647 +future/backports/email/_policybase.pyc,, +future/backports/email/base64mime.py,sha256=sey6iJA9pHIOdFgoV1p7QAwYVjt8CEkDhITt304-nyI,3729 +future/backports/email/base64mime.pyc,, +future/backports/email/charset.py,sha256=CfE4iV2zAq6MQC0CHXHLnwTNW71zmhNITbzOcfxE4vY,17439 +future/backports/email/charset.pyc,, +future/backports/email/encoders.py,sha256=Nn4Pcx1rOdRgoSIzB6T5RWHl5zxClbf32wgE6D0tUt8,2800 +future/backports/email/encoders.pyc,, +future/backports/email/errors.py,sha256=tRX8PP5g7mk2bAxL1jTCYrbfhD2gPZFNrh4_GJRM8OQ,3680 +future/backports/email/errors.pyc,, +future/backports/email/feedparser.py,sha256=bvmhb4cdY-ipextPK2K2sDgMsNvTspmuQfYyCxc4zSc,22736 +future/backports/email/feedparser.pyc,, +future/backports/email/generator.py,sha256=lpaLhZHneguvZ2QgRu7Figkjb7zmY28AGhj9iZTdI7s,19520 +future/backports/email/generator.pyc,, +future/backports/email/header.py,sha256=uBHbNKO-yx5I9KBflernJpyy3fX4gImCB1QE7ICApLs,24448 +future/backports/email/header.pyc,, +future/backports/email/headerregistry.py,sha256=ZPbvLKXD0NMLSU4jXlVHfGyGcLMrFm-GQVURu_XHj88,20637 +future/backports/email/headerregistry.pyc,, +future/backports/email/iterators.py,sha256=kMRYFGy3SVVpo7HG7JJr2ZAlOoaX6CVPzKYwDSvLfV0,2348 +future/backports/email/iterators.pyc,, +future/backports/email/message.py,sha256=TcX-zkYVZVFU61UcVk2qflaWuN6KhUmN4ypNgKh2BwE,35225 +future/backports/email/message.pyc,, +future/backports/email/mime/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +future/backports/email/mime/__init__.pyc,, +future/backports/email/mime/application.py,sha256=m-5a4mSxu2E32XAImnp9x9eMVX5Vme2iNgn2dMMNyss,1401 +future/backports/email/mime/application.pyc,, +future/backports/email/mime/audio.py,sha256=2ognalFRadcsUYQYMUZbjv5i1xJbFhQN643doMuI7M4,2815 +future/backports/email/mime/audio.pyc,, +future/backports/email/mime/base.py,sha256=wV3ClQyMsOqmkXSXbk_wd_zPoPTvBx8kAIzq3rdM4lE,875 +future/backports/email/mime/base.pyc,, +future/backports/email/mime/image.py,sha256=DpQk1sB-IMmO43AF4uadsXyf_y5TdEzJLfyhqR48bIw,1907 +future/backports/email/mime/image.pyc,, +future/backports/email/mime/message.py,sha256=pFsMhXW07aRjsLq1peO847PApWFAl28-Z2Z7BP1Dn74,1429 +future/backports/email/mime/message.pyc,, +future/backports/email/mime/multipart.py,sha256=j4Lf_sJmuwTbfgdQ6R35_t1_ha2DynJBJDvpjwbNObE,1699 +future/backports/email/mime/multipart.pyc,, +future/backports/email/mime/nonmultipart.py,sha256=Ciba1Z8d2yLDDpxgDJuk3Bb-TqcpE9HCd8KfbW5vgl4,832 +future/backports/email/mime/nonmultipart.pyc,, +future/backports/email/mime/text.py,sha256=zV98BjoR4S_nX8c47x43LnsnifeGhIfNGwSAh575bs0,1552 +future/backports/email/mime/text.pyc,, +future/backports/email/parser.py,sha256=-115SC3DHZ6lLijWFTxuOnE-GiM2BOYaUSz-QpmvYSo,5312 +future/backports/email/parser.pyc,, +future/backports/email/policy.py,sha256=gpcbhVRXuCohkK6MUqopTs1lv4E4-ZVUO6OVncoGEJE,8823 +future/backports/email/policy.pyc,, +future/backports/email/quoprimime.py,sha256=w93W5XgdFpyGaDqDBJrnXF_v_npH5r20WuAxmrAzyQg,10923 +future/backports/email/quoprimime.pyc,, +future/backports/email/utils.py,sha256=vpfN0E8UjNbNw-2NFBQGCo4TNgrghMsqzpEYW5C_fBs,14270 +future/backports/email/utils.pyc,, +future/backports/html/__init__.py,sha256=FKwqFtWMCoGNkhU97OPnR1fZSh6etAKfN1FU1KvXcV8,924 +future/backports/html/__init__.pyc,, +future/backports/html/entities.py,sha256=kzoRnQyGk_3DgoucHLhL5QL1pglK9nvmxhPIGZFDTnc,75428 +future/backports/html/entities.pyc,, +future/backports/html/parser.py,sha256=G2tUObvbHSotNt06JLY-BP1swaZNfDYFd_ENWDjPmRg,19770 +future/backports/html/parser.pyc,, +future/backports/http/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +future/backports/http/__init__.pyc,, +future/backports/http/client.py,sha256=BMA9BQDddhj0zcJZ5Q2JJxo8PSYCWQbHXvC4eit2Mk4,47192 +future/backports/http/client.pyc,, +future/backports/http/cookiejar.py,sha256=TDLREuJIDMkRNd9h4oqkKdRvngCXgM0njaxyigDZ-To,76542 +future/backports/http/cookiejar.pyc,, +future/backports/http/cookies.py,sha256=ipa-j6pNmO3J9q2kmh5IZMcgLX18tC_wG-mWQUmaXco,21569 +future/backports/http/cookies.pyc,, +future/backports/http/server.py,sha256=1CaMxgzHf9lYhmTJyE7topgjRIlIn9cnjgw8YEvwJV4,45523 +future/backports/http/server.pyc,, +future/backports/misc.py,sha256=8wbCh2Jfa5g4GzAVa6xaXxQ3Xn7otG9I3mIOoJC4-TE,32602 +future/backports/misc.pyc,, +future/backports/socket.py,sha256=DH1V6IjKPpJ0tln8bYvxvQ7qnvZG-UoQtMA5yVleHiU,15663 +future/backports/socket.pyc,, +future/backports/socketserver.py,sha256=Twvyk5FqVnOeiNcbVsyMDPTF1mNlkKfyofG7tKxTdD8,24286 +future/backports/socketserver.pyc,, +future/backports/test/__init__.py,sha256=9dXxIZnkI095YfHC-XIaVF6d31GjeY1Ag8TEzcFgepM,264 +future/backports/test/__init__.pyc,, +future/backports/test/badcert.pem,sha256=JioQeRZkHH8hGsWJjAF3U1zQvcWqhyzG6IOEJpTY9SE,1928 +future/backports/test/badkey.pem,sha256=gaBK9px_gG7DmrLKxfD6f6i-toAmARBTVfs-YGFRQF0,2162 +future/backports/test/dh512.pem,sha256=dUTsjtLbK-femrorUrTGF8qvLjhTiT_n4Uo5V6u__Gs,402 +future/backports/test/https_svn_python_org_root.pem,sha256=wOB3Onnc62Iu9kEFd8GcHhd_suucYjpJNA3jyfHeJWA,2569 +future/backports/test/keycert.passwd.pem,sha256=ZBfnVLpbBtAOf_2gCdiQ-yrBHmRsNzSf8VC3UpQZIjg,1830 +future/backports/test/keycert.pem,sha256=xPXi5idPcQVbrhgxBqF2TNGm6sSZ2aLVVEt6DWzplL8,1783 +future/backports/test/keycert2.pem,sha256=DB46FEAYv8BWwQJ-5RzC696FxPN7CON-Qsi-R4poJgc,1795 +future/backports/test/nokia.pem,sha256=s00x0uPDSaa5DHJ_CwzlVhg3OVdJ47f4zgqQdd0SAfQ,1923 +future/backports/test/nullbytecert.pem,sha256=NFRYWhmP_qT3jGfVjR6-iaC-EQdhIFjiXtTLN5ZPKnE,5435 +future/backports/test/nullcert.pem,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +future/backports/test/pystone.py,sha256=fvyoJ_tVovTNaxbJmdJMwr9F6SngY-U4ibULnd_wUqA,7427 +future/backports/test/pystone.pyc,, +future/backports/test/sha256.pem,sha256=3wB-GQqEc7jq-PYwYAQaPbtTvvr7stk_DVmZxFgehfA,8344 +future/backports/test/ssl_cert.pem,sha256=M607jJNeIeHG9BlTf_jaQkPJI4nOxSJPn-zmEAaW43M,867 +future/backports/test/ssl_key.passwd.pem,sha256=I_WH4sBw9Vs9Z-BvmuXY0aw8tx8avv6rm5UL4S_pP00,963 +future/backports/test/ssl_key.pem,sha256=VKGU-R3UYaZpVTXl7chWl4vEYEDeob69SfvRTQ8aq_4,916 +future/backports/test/ssl_servers.py,sha256=-pd7HMZljuZfFRAbCAiAP_2G04orITJFj-S9ddr6o84,7209 +future/backports/test/ssl_servers.pyc,, +future/backports/test/support.py,sha256=zJrb-pz-Wu2dZwnNodg1v3w96zVq7ORuN-hOGOHbdA8,70881 +future/backports/test/support.pyc,, +future/backports/total_ordering.py,sha256=O3M57_IisQ-zW5hW20uxkfk4fTGsr0EF2tAKx3BksQo,1929 +future/backports/total_ordering.pyc,, +future/backports/urllib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +future/backports/urllib/__init__.pyc,, +future/backports/urllib/error.py,sha256=ktikuK9ag4lS4f8Z0k5p1F11qF40N2AiOtjbXiF97ew,2715 +future/backports/urllib/error.pyc,, +future/backports/urllib/parse.py,sha256=67avrYqV1UK7i_22goRUrvJ8SffzjRdTja9wzq_ynXY,35792 +future/backports/urllib/parse.pyc,, +future/backports/urllib/request.py,sha256=qlfcSWQW0VdzJQ7NEERG0_CBC63ylg-vqhI15WuWskk,96184 +future/backports/urllib/request.pyc,, +future/backports/urllib/response.py,sha256=ooQyswwbb-9N6IVi1Kwjss1aR-Kvm8ZNezoyVEonp8c,3180 +future/backports/urllib/response.pyc,, +future/backports/urllib/robotparser.py,sha256=pnAGTbKhdbCq_9yMZp7m8hj5q_NJpyQX6oQIZuYcnkw,6865 +future/backports/urllib/robotparser.pyc,, +future/backports/xmlrpc/__init__.py,sha256=h61ciVTdVvu8oEUXv4dHf_Tc5XUXDH3RKB1-8fQhSsg,38 +future/backports/xmlrpc/__init__.pyc,, +future/backports/xmlrpc/client.py,sha256=6a6Pvx_RVC9gIHDkFOVdREeGaZckOOiWd7T6GyzU3qU,48133 +future/backports/xmlrpc/client.pyc,, +future/backports/xmlrpc/server.py,sha256=W_RW5hgYbNV2LGbnvngzm7akacRdK-XFY-Cy2HL-qsY,37285 +future/backports/xmlrpc/server.pyc,, +future/builtins/__init__.py,sha256=35dOTp0QKhdjVvucI_stXqZq0slHqBvNAFp0yJEOBXw,1664 +future/builtins/__init__.pyc,, +future/builtins/disabled.py,sha256=Ysq74bsmwntpq7dzkwTAD7IHKrkXy66vJlPshVwgVBI,2109 +future/builtins/disabled.pyc,, +future/builtins/iterators.py,sha256=l1Zawm2x82oqOuGGtCZRE76Ej98sMlHQwu9fZLK5RrA,1396 +future/builtins/iterators.pyc,, +future/builtins/misc.py,sha256=3-f7krUdaKl3ruh-YzuXvkffnGmAeUqKvA3aW7QCq9c,4087 +future/builtins/misc.pyc,, +future/builtins/newnext.py,sha256=oxXB8baXqJv29YG40aCS9UXk9zObyoOjya8BJ7NdBJM,2009 +future/builtins/newnext.pyc,, +future/builtins/newround.py,sha256=K-5rp4dPT5T2JS5nyHiJNCRoGqTnXDcTxDKV_0HMGHQ,3096 +future/builtins/newround.pyc,, +future/builtins/newsuper.py,sha256=LmiUQ_f6NXDIz6v6sDPkoTWl-2Zccy7PpZfQKYtscac,4146 +future/builtins/newsuper.pyc,, +future/moves/__init__.py,sha256=pLfIJ4U3nfhd64_YpAp8lDvKunk0oPVQtHruNBQtgAI,220 +future/moves/__init__.pyc,, +future/moves/_dummy_thread.py,sha256=c8ZRUd8ffvyvGKGGgve5NKc8VdtAWquu8-4FnO2EdvA,175 +future/moves/_dummy_thread.pyc,, +future/moves/_markupbase.py,sha256=W9wh_Gu3jDAMIhVBV1ZnCkJwYLHRk_v_su_HLALBkZQ,171 +future/moves/_markupbase.pyc,, +future/moves/_thread.py,sha256=rwY7L4BZMFPlrp_i6T2Un4_iKYwnrXJ-yV6FJZN8YDo,163 +future/moves/_thread.pyc,, +future/moves/builtins.py,sha256=4sjjKiylecJeL9da_RaBZjdymX2jtMs84oA9lCqb4Ug,281 +future/moves/builtins.pyc,, +future/moves/collections.py,sha256=OKQ-TfUgms_2bnZRn4hrclLDoiN2i-HSWcjs3BC2iY8,417 +future/moves/collections.pyc,, +future/moves/configparser.py,sha256=TNy226uCbljjU-DjAVo7j7Effbj5zxXvDh0SdXehbzk,146 +future/moves/configparser.pyc,, +future/moves/copyreg.py,sha256=-71LEo3hA2K9VeI4Ny5QvvfouyPz4YxMafK4eNwfk-0,165 +future/moves/copyreg.pyc,, +future/moves/dbm/__init__.py,sha256=_VkvQHC2UcIgZFPRroiX_P0Fs7HNqS_69flR0-oq2B8,488 +future/moves/dbm/__init__.pyc,, +future/moves/dbm/dumb.py,sha256=HKdjjtO3EyP9EKi1Hgxh_eUU6yCQ0fBX9NN3n-zb8JE,166 +future/moves/dbm/dumb.pyc,, +future/moves/dbm/gnu.py,sha256=XoCSEpZ2QaOgo2h1m80GW7NUgj_b93BKtbcuwgtnaKo,162 +future/moves/dbm/gnu.pyc,, +future/moves/dbm/ndbm.py,sha256=OFnreyo_1YHDBl5YUm9gCzKlN1MHgWbfSQAZVls2jaM,162 +future/moves/dbm/ndbm.pyc,, +future/moves/html/__init__.py,sha256=BSUFSHxXf2kGvHozlnrB1nn6bPE6p4PpN3DwA_Z5geo,1016 +future/moves/html/__init__.pyc,, +future/moves/html/entities.py,sha256=lVvchdjK_RzRj759eg4RMvGWHfgBbj0tKGOoZ8dbRyY,177 +future/moves/html/entities.pyc,, +future/moves/html/parser.py,sha256=V2XpHLKLCxQum3N9xlO3IUccAD7BIykZMqdEcWET3vY,167 +future/moves/html/parser.pyc,, +future/moves/http/__init__.py,sha256=Mx1v_Tcks4udHCtDM8q2xnYUiQ01gD7EpPyeQwsP3-Q,71 +future/moves/http/__init__.pyc,, +future/moves/http/client.py,sha256=hqEBq7GDXZidd1AscKnSyjSoMcuj8rERqGTmD7VheDQ,165 +future/moves/http/client.pyc,, +future/moves/http/cookiejar.py,sha256=Frr9ZZCg-145ymy0VGpiPJhvBEpJtVqRBYPaKhgT1Z4,173 +future/moves/http/cookiejar.pyc,, +future/moves/http/cookies.py,sha256=PPrHa1_oDbu3D_BhJGc6PvMgY1KoxyYq1jqeJwEcMvE,233 +future/moves/http/cookies.pyc,, +future/moves/http/server.py,sha256=8YQlSCShjAsB5rr5foVvZgp3IzwYFvTmGZCHhBSDtaI,606 +future/moves/http/server.pyc,, +future/moves/itertools.py,sha256=PVxFHRlBQl9ElS0cuGFPcUtj53eHX7Z1DmggzGfgQ6c,158 +future/moves/itertools.pyc,, +future/moves/pickle.py,sha256=r8j9skzfE8ZCeHyh_OB-WucOkRTIHN7zpRM7l7V3qS4,229 +future/moves/pickle.pyc,, +future/moves/queue.py,sha256=uxvLCChF-zxWWgrY1a_wxt8rp2jILdwO4PrnkBW6VTE,160 +future/moves/queue.pyc,, +future/moves/reprlib.py,sha256=Nt5sUgMQ3jeVIukqSHOvB0UIsl6Y5t-mmT_13mpZmiY,161 +future/moves/reprlib.pyc,, +future/moves/socketserver.py,sha256=v8ZLurDxHOgsubYm1iefjlpnnJQcx2VuRUGt9FCJB9k,174 +future/moves/socketserver.pyc,, +future/moves/subprocess.py,sha256=oqRSMfFZkxM4MXkt3oD5N6eBwmmJ6rQ9KPhvSQKT_hM,251 +future/moves/subprocess.pyc,, +future/moves/sys.py,sha256=HOMRX4Loim75FMbWawd3oEwuGNJR-ClMREEFkVpBsRs,132 +future/moves/sys.pyc,, +future/moves/test/__init__.py,sha256=yB9F-fDQpzu1v8cBoKgIrL2ScUNqjlkqEztYrGVCQ-0,110 +future/moves/test/__init__.pyc,, +future/moves/test/support.py,sha256=6zGgTTXcERyBJIQ04-X-sAe781tVgLVHp3HzmQPy52g,259 +future/moves/test/support.pyc,, +future/moves/tkinter/__init__.py,sha256=jV9vDx3wRl0bsoclU8oSe-5SqHQ3YpCbStmqtXnq1p4,620 +future/moves/tkinter/__init__.pyc,, +future/moves/tkinter/colorchooser.py,sha256=kprlmpRtvDbW5Gq43H1mi2KmNJ2kuzLQOba0a5EwDkU,333 +future/moves/tkinter/colorchooser.pyc,, +future/moves/tkinter/commondialog.py,sha256=mdUbq1IZqOGaSA7_8R367IukDCsMfzXiVHrTQQpp7Z0,333 +future/moves/tkinter/commondialog.pyc,, +future/moves/tkinter/constants.py,sha256=0qRUrZLRPdVxueABL9KTzzEWEsk6xM1rOjxK6OHxXtA,324 +future/moves/tkinter/constants.pyc,, +future/moves/tkinter/dialog.py,sha256=ksp-zvs-_A90P9RNHS8S27f1k8f48zG2Bel2jwZV5y0,311 +future/moves/tkinter/dialog.pyc,, +future/moves/tkinter/dnd.py,sha256=C_Ah0Urnyf2XKE5u-oP6mWi16RzMSXgMA1uhBSAwKY8,306 +future/moves/tkinter/dnd.pyc,, +future/moves/tkinter/filedialog.py,sha256=RSJFDGOP2AJ4T0ZscJ2hyF9ssOWp9t_S_DtnOmT-WZ8,323 +future/moves/tkinter/filedialog.pyc,, +future/moves/tkinter/font.py,sha256=TXarflhJRxqepaRNSDw6JFUVGz5P1T1C4_uF9VRqj3w,309 +future/moves/tkinter/font.pyc,, +future/moves/tkinter/messagebox.py,sha256=WJt4t83kLmr_UnpCWFuLoyazZr3wAUOEl6ADn3osoEA,327 +future/moves/tkinter/messagebox.pyc,, +future/moves/tkinter/scrolledtext.py,sha256=DRzN8aBAlDBUo1B2KDHzdpRSzXBfH4rOOz0iuHXbQcg,329 +future/moves/tkinter/scrolledtext.pyc,, +future/moves/tkinter/simpledialog.py,sha256=6MhuVhZCJV4XfPpPSUWKlDLLGEi0Y2ZlGQ9TbsmJFL0,329 +future/moves/tkinter/simpledialog.pyc,, +future/moves/tkinter/tix.py,sha256=aNeOfbWSGmcN69UmEGf4tJ-QIxLT6SU5ynzm1iWgepA,302 +future/moves/tkinter/tix.pyc,, +future/moves/tkinter/ttk.py,sha256=rRrJpDjcP2gjQNukECu4F026P-CkW-3Ca2tN6Oia-Fw,302 +future/moves/tkinter/ttk.pyc,, +future/moves/urllib/__init__.py,sha256=yB9F-fDQpzu1v8cBoKgIrL2ScUNqjlkqEztYrGVCQ-0,110 +future/moves/urllib/__init__.pyc,, +future/moves/urllib/error.py,sha256=gfrKzv-6W5OjzNIfjvJaQkxABRLym2KwjfKFXSdDB60,479 +future/moves/urllib/error.pyc,, +future/moves/urllib/parse.py,sha256=xLLUMIIB5MreCdYzRZ5zIRWrhTRCoMO8RZEH4WPFQDY,1045 +future/moves/urllib/parse.pyc,, +future/moves/urllib/request.py,sha256=4ohgf18_6Ky_zFaHOlEIIv6h9M-fF3JAIyjWB61xWnQ,3517 +future/moves/urllib/request.pyc,, +future/moves/urllib/response.py,sha256=ZEZML0FpbB--GIeBFPvSzbtlVJ6EsR4tCI4qB7D8sFQ,342 +future/moves/urllib/response.pyc,, +future/moves/urllib/robotparser.py,sha256=j24p6dMNzUpGZtT3BQxwRoE-F88iWmBpKgu0tRV61FQ,179 +future/moves/urllib/robotparser.pyc,, +future/moves/winreg.py,sha256=2zNAG59QI7vFlCj7kqDh0JrAYTpexOnI55PEAIjYhqo,163 +future/moves/winreg.pyc,, +future/moves/xmlrpc/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +future/moves/xmlrpc/__init__.pyc,, +future/moves/xmlrpc/client.py,sha256=2PfnL5IbKVwdKP7C8B1OUviEtuBObwoH4pAPfvHIvQc,143 +future/moves/xmlrpc/client.pyc,, +future/moves/xmlrpc/server.py,sha256=ESDXdpUgTKyeFmCDSnJmBp8zONjJklsRJOvy4OtaALc,143 +future/moves/xmlrpc/server.pyc,, +future/standard_library/__init__.py,sha256=7paz9IsD5qv_tvk5Rre3YrlA2_2aS1FJfI7UlrzAtWY,27743 +future/standard_library/__init__.pyc,, +future/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +future/tests/__init__.pyc,, +future/tests/base.py,sha256=vAViwQ6WbnNBNppE1sToQRknDPzPLR9Spb754xwyO9Q,19706 +future/tests/base.pyc,, +future/types/__init__.py,sha256=5fBxWqf_OTQ8jZ7k2TS34rFH14togeR488F4zBHIQ-s,6831 +future/types/__init__.pyc,, +future/types/newbytes.py,sha256=DoBdTV-khuDIASe4jD1wEJErWyJA1FEG0QTafF5Zyx8,16238 +future/types/newbytes.pyc,, +future/types/newdict.py,sha256=2N7P44cWmWtiDHvlK5ir15mW492gg6uP2n65d5bsDy4,3100 +future/types/newdict.pyc,, +future/types/newint.py,sha256=jrAHLllFwp4abWIw4o_C0fN9yR-F80X_-oyaXiwLC1M,13233 +future/types/newint.pyc,, +future/types/newlist.py,sha256=-H5-fXodd-UQgTFnZBJdwE68CrgIL_jViYdv4w7q2rU,2284 +future/types/newlist.pyc,, +future/types/newmemoryview.py,sha256=Ra5y0P-7as020zRRuylI98NJNQZkAUBFjWv-io3C5rg,654 +future/types/newmemoryview.pyc,, +future/types/newobject.py,sha256=jmksg01rnb4V8GUm383gdFKFNsqOaJMSjhS3uPEBbBI,3339 +future/types/newobject.pyc,, +future/types/newopen.py,sha256=lcRNHWZ1UjEn_0_XKis1ZA5U6l-4c-CHlC0WX1sY4NI,810 +future/types/newopen.pyc,, +future/types/newrange.py,sha256=b4gv-ZyjNvdKjEwDYpIWroARhsw2FxEvaKmMlkyiFoE,5195 +future/types/newrange.pyc,, +future/types/newstr.py,sha256=LfE2T2z-58h-XxFKDzFuBb0XkZdCM6Vyzt7YmdZhZdA,15464 +future/types/newstr.pyc,, +future/utils/__init__.py,sha256=po-TLpbn6zpxPQC4BKfYLkcqiJ1j_N-ulX42WCNgBp8,20325 +future/utils/__init__.pyc,, +future/utils/surrogateescape.py,sha256=7u4V4XlW83P5YSAJS2f92YUF8vsWthsiTnmAshOJL_M,6097 +future/utils/surrogateescape.pyc,, +html/__init__.py,sha256=tYP_EBms51UOZkx8Hbud4fhkDY70L8Z0nkXwXKNeP8Y,362 +html/__init__.pyc,, +html/entities.py,sha256=tv5rW4wfFnke2ULqiuKhB4CTyAzmTpYf7j5l5j8LLXA,160 +html/entities.pyc,, +html/parser.py,sha256=3PbUx6CBHilS6I9jwZm3FsPjhSQUKITGBLcXIBt58Kk,233 +html/parser.pyc,, +http/__init__.py,sha256=cuI7TcJ1aevAtq79-IIox_ohWc4ZvsA_xDG4GVd1KT8,335 +http/__init__.pyc,, +http/client.py,sha256=7APb4B6lcFkDvRAZZ93XU-_D5teQd_UQxRNx7ZONrBE,2786 +http/client.pyc,, +http/cookiejar.py,sha256=gr7S7uZDamwxtMqRvDm6dSzcIlXrXsZIYQNGqY83zig,107 +http/cookiejar.pyc,, +http/cookies.py,sha256=xSjselJwo5tNZzpjKE_7WRNM498fW8YFIuZAk8qhZ3E,165 +http/cookies.pyc,, +http/server.py,sha256=SO1sTWbfR1k68rEliM-BcCjmwlTxkKpcMDPILbj0ZQ4,495 +http/server.pyc,, +libfuturize/__init__.py,sha256=CZA_KgvTQOPAY1_MrlJeQ6eMh2Eei4_KIv4JuyAkpfw,31 +libfuturize/__init__.pyc,, +libfuturize/fixer_util.py,sha256=Zhms5G97l40pyG1krQM2lCp-TxnocBdJkB2AbkAFnKY,17494 +libfuturize/fixer_util.pyc,, +libfuturize/fixes/__init__.py,sha256=anwWy6vHlv4ZmAuqs9S3HTnPBcTEBEc5yuoGFWTR3SE,5141 +libfuturize/fixes/__init__.pyc,, +libfuturize/fixes/fix_UserDict.py,sha256=jL4jXnGaUQTkG8RKfGXbU_HVTkB3MWZMQwUkqMAjB6I,3840 +libfuturize/fixes/fix_UserDict.pyc,, +libfuturize/fixes/fix_absolute_import.py,sha256=vkrF2FyQR5lSz2WmdqywzkEJVTC0eq4gh_REWBKHh7w,3140 +libfuturize/fixes/fix_absolute_import.pyc,, +libfuturize/fixes/fix_add__future__imports_except_unicode_literals.py,sha256=OAhy8tfHVco1dlB4439T7847vRu4eHSBwDGBQlPDi2A,662 +libfuturize/fixes/fix_add__future__imports_except_unicode_literals.pyc,, +libfuturize/fixes/fix_basestring.py,sha256=bHkKuMzhr5FMXwjXlMOjsod4S3rQkVdbzhoWV4-tl3Y,394 +libfuturize/fixes/fix_basestring.pyc,, +libfuturize/fixes/fix_bytes.py,sha256=AhzOJes6EnPwgzboDjvURANbWKqciG6ZGaYW07PYQK8,685 +libfuturize/fixes/fix_bytes.pyc,, +libfuturize/fixes/fix_cmp.py,sha256=Blq_Z0IGkYiKS83QzZ5wUgpJyZfQiZoEsWJ1VPyXgFY,701 +libfuturize/fixes/fix_cmp.pyc,, +libfuturize/fixes/fix_division.py,sha256=gnrAi7stquiVUyi_De1H8q--43iQaSUX0CjnOmQ6O2w,228 +libfuturize/fixes/fix_division.pyc,, +libfuturize/fixes/fix_division_safe.py,sha256=zDZdrLwGSSqNjPqewVmRhwj1kQObZygVEqjCgysA53E,3460 +libfuturize/fixes/fix_division_safe.pyc,, +libfuturize/fixes/fix_execfile.py,sha256=I5AcJ6vPZ7i70TChaq9inxqnZ4C04-yJyfAItGa8E3c,921 +libfuturize/fixes/fix_execfile.pyc,, +libfuturize/fixes/fix_future_builtins.py,sha256=QBCRpD9XA7tbtfP4wmOF2DXquB4lq-eupkQj-QAxp0s,2027 +libfuturize/fixes/fix_future_builtins.pyc,, +libfuturize/fixes/fix_future_standard_library.py,sha256=FVtflFt38efHe_SEX6k3m6IYAtKWjA4rAPZrlCv6yA0,733 +libfuturize/fixes/fix_future_standard_library.pyc,, +libfuturize/fixes/fix_future_standard_library_urllib.py,sha256=Rf81XcAXA-vwNvrhskf5sLExbR--Wkr5fiUcMYGAKzs,1001 +libfuturize/fixes/fix_future_standard_library_urllib.pyc,, +libfuturize/fixes/fix_metaclass.py,sha256=GLB76wbuyUVciDgW9bgNNOBEnLeS_AR-fKABcPBZk6M,9568 +libfuturize/fixes/fix_metaclass.pyc,, +libfuturize/fixes/fix_next_call.py,sha256=01STG86Av9o5QcpQDJ6UbPhvxt9kKrkatiPeddXRgvA,3158 +libfuturize/fixes/fix_next_call.pyc,, +libfuturize/fixes/fix_object.py,sha256=qalFIjn0VTWXG5sGOOoCvO65omjX5_9d40SUpwUjBdw,407 +libfuturize/fixes/fix_object.pyc,, +libfuturize/fixes/fix_oldstr_wrap.py,sha256=UCR6Q2l-pVqJSrRTnQAWMlaqBoX7oX1VpG_w6Q0XcyY,1214 +libfuturize/fixes/fix_oldstr_wrap.pyc,, +libfuturize/fixes/fix_order___future__imports.py,sha256=ACUCw5NEGWvj6XA9rNj8BYha3ktxLvkM5Ssh5cyV644,829 +libfuturize/fixes/fix_order___future__imports.pyc,, +libfuturize/fixes/fix_print.py,sha256=92s1w2t9SynA3Y1_85-lexSBbgEWJM6lBrhCxVacfDc,3384 +libfuturize/fixes/fix_print.pyc,, +libfuturize/fixes/fix_print_with_import.py,sha256=hVWn70Q1DPMUiHMyEqgUx-6sM1AylLj78v9pMc4LFw8,735 +libfuturize/fixes/fix_print_with_import.pyc,, +libfuturize/fixes/fix_raise.py,sha256=SylpUQUZnw06bMRI6cbV9mJcVWJ78HCvxro7AAjGu9c,2167 +libfuturize/fixes/fix_raise.pyc,, +libfuturize/fixes/fix_remove_old__future__imports.py,sha256=j4EC1KEVgXhuQAqhYHnAruUjW6uczPjV_fTCSOLMuAw,851 +libfuturize/fixes/fix_remove_old__future__imports.pyc,, +libfuturize/fixes/fix_unicode_keep_u.py,sha256=M8fcFxHeFnWVOKoQRpkMsnpd9qmUFubI2oFhO4ZPk7A,779 +libfuturize/fixes/fix_unicode_keep_u.pyc,, +libfuturize/fixes/fix_unicode_literals_import.py,sha256=wq-hb-9Yx3Az4ol-ylXZJPEDZ81EaPZeIy5VvpA0CEY,367 +libfuturize/fixes/fix_unicode_literals_import.pyc,, +libfuturize/fixes/fix_xrange_with_import.py,sha256=f074qStjMz3OtLjt1bKKZSxQnRbbb7HzEbqHt9wgqdw,479 +libfuturize/fixes/fix_xrange_with_import.pyc,, +libfuturize/main.py,sha256=feICmcv0dzWhutvwz0unnIVxusbSlQZFDaxObkHebs8,13733 +libfuturize/main.pyc,, +libpasteurize/__init__.py,sha256=CZA_KgvTQOPAY1_MrlJeQ6eMh2Eei4_KIv4JuyAkpfw,31 +libpasteurize/__init__.pyc,, +libpasteurize/fixes/__init__.py,sha256=ccdv-2MGjQMbq8XuEZBndHmbzGRrZnabksjXZLUv044,3719 +libpasteurize/fixes/__init__.pyc,, +libpasteurize/fixes/feature_base.py,sha256=v7yLjBDBUPeNUc-YHGGlIsJDOQzFAM4Vo0RN5F1JHVU,1723 +libpasteurize/fixes/feature_base.pyc,, +libpasteurize/fixes/fix_add_all__future__imports.py,sha256=BwVxr4o3gZLEUFVhO92J4X0jNGKqM3QGmJvhz1PjT-o,676 +libpasteurize/fixes/fix_add_all__future__imports.pyc,, +libpasteurize/fixes/fix_add_all_future_builtins.py,sha256=scfkY-Sz5j0yDtLYls2ENOcqEMPVxeDm9gFYYPINPB8,1269 +libpasteurize/fixes/fix_add_all_future_builtins.pyc,, +libpasteurize/fixes/fix_add_future_standard_library_import.py,sha256=thTRbkBzy_SJjZ0bJteTp0sBTx8Wr69xFakH4styf7Y,663 +libpasteurize/fixes/fix_add_future_standard_library_import.pyc,, +libpasteurize/fixes/fix_annotations.py,sha256=VT_AorKY9AYWYZUZ17_CeUrJlEA7VGkwVLDQlwD1Bxo,1581 +libpasteurize/fixes/fix_annotations.pyc,, +libpasteurize/fixes/fix_division.py,sha256=_TD_c5KniAYqEm11O7NJF0v2WEhYSNkRGcKG_94ZOas,904 +libpasteurize/fixes/fix_division.pyc,, +libpasteurize/fixes/fix_features.py,sha256=NZn0n34_MYZpLNwyP1Tf51hOiN58Rg7A8tA9pK1S8-c,2675 +libpasteurize/fixes/fix_features.pyc,, +libpasteurize/fixes/fix_fullargspec.py,sha256=VlZuIU6QNrClmRuvC4mtLICL3yMCi-RcGCnS9fD4b-Q,438 +libpasteurize/fixes/fix_fullargspec.pyc,, +libpasteurize/fixes/fix_future_builtins.py,sha256=SlCK9I9u05m19Lr1wxlJxF8toZ5yu0yXBeDLxUN9_fw,1450 +libpasteurize/fixes/fix_future_builtins.pyc,, +libpasteurize/fixes/fix_getcwd.py,sha256=uebvTvFboLqsROFCwdnzoP6ThziM0skz9TDXHoJcFsQ,873 +libpasteurize/fixes/fix_getcwd.pyc,, +libpasteurize/fixes/fix_imports.py,sha256=U4lIs_5Xp1qqM8mN72ieDkkIdiyALZFyCZsRC8ZmXlM,4944 +libpasteurize/fixes/fix_imports.pyc,, +libpasteurize/fixes/fix_imports2.py,sha256=bs2V5Yv0v_8xLx-lNj9kNEAK2dLYXUXkZ2hxECg01CU,8580 +libpasteurize/fixes/fix_imports2.pyc,, +libpasteurize/fixes/fix_kwargs.py,sha256=NB_Ap8YJk-9ncoJRbOiPY_VMIigFgVB8m8AuY29DDhE,5991 +libpasteurize/fixes/fix_kwargs.pyc,, +libpasteurize/fixes/fix_memoryview.py,sha256=Fwayx_ezpr22tbJ0-QrKdJ-FZTpU-m7y78l1h_N4xxc,551 +libpasteurize/fixes/fix_memoryview.pyc,, +libpasteurize/fixes/fix_metaclass.py,sha256=IcE2KjaDG8jUR3FYXECzOC_cr2pr5r95W1NTbMrK8Wc,3260 +libpasteurize/fixes/fix_metaclass.pyc,, +libpasteurize/fixes/fix_newstyle.py,sha256=78sazKOHm9DUoMyW4VdvQpMXZhicbXzorVPRhBpSUrM,888 +libpasteurize/fixes/fix_newstyle.pyc,, +libpasteurize/fixes/fix_next.py,sha256=VHqcyORRNVqKJ51jJ1OkhwxHuXRgp8qaldyqcMvA4J0,1233 +libpasteurize/fixes/fix_next.pyc,, +libpasteurize/fixes/fix_printfunction.py,sha256=NDIfqVmUJBG3H9E6nrnN0cWZK8ch9pL4F-nMexdsa38,401 +libpasteurize/fixes/fix_printfunction.pyc,, +libpasteurize/fixes/fix_raise.py,sha256=zQ_AcMsGmCbtKMgrxZGcHLYNscw6tqXFvHQxgqtNbU8,1099 +libpasteurize/fixes/fix_raise.pyc,, +libpasteurize/fixes/fix_raise_.py,sha256=9STp633frUfYASjYzqhwxx_MXePNmMhfJClowRj8FLY,1225 +libpasteurize/fixes/fix_raise_.pyc,, +libpasteurize/fixes/fix_throw.py,sha256=_ZREVre-WttUvk4sWjrqUNqm9Q1uFaATECN0_-PXKbk,835 +libpasteurize/fixes/fix_throw.pyc,, +libpasteurize/fixes/fix_unpacking.py,sha256=eMqRe44Nfq8lo0YFL9oKW75dGARmBSmklj4BCS_q1Lo,5946 +libpasteurize/fixes/fix_unpacking.pyc,, +libpasteurize/main.py,sha256=dVHYTQQeJonuOFDNrenJZl-rKHgOQKRMPP1OqnJogWQ,8186 +libpasteurize/main.pyc,, +past/__init__.py,sha256=nG-N5LsTBvdRG4f6pAVMNB9eRrvdPxcJbrXGEXnGwx8,2943 +past/__init__.pyc,, +past/builtins/__init__.py,sha256=7j_4OsUlN6q2eKr14do7mRQ1GwXRoXAMUR0A1fJpAls,1805 +past/builtins/__init__.pyc,, +past/builtins/misc.py,sha256=6mlC5SaIGI7YnpuixUrK4Jj6O6mHw-6sKfdNsqeZVbc,2499 +past/builtins/misc.pyc,, +past/builtins/noniterators.py,sha256=rNMEK5Bh39JaSxR6OSkQtHg97VKhtD2DOGhiDYF4j-A,9371 +past/builtins/noniterators.pyc,, +past/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +past/tests/__init__.pyc,, +past/translation/__init__.py,sha256=BPMBdcpf2mM6Bbe3iqFhOvObtibBb_N5NmvX3xVvZ5k,18417 +past/translation/__init__.pyc,, +past/types/__init__.py,sha256=RyJlgqg9uJ8oF-kJT9QlfhfdmhiMh3fShmtvd2CQycY,879 +past/types/__init__.pyc,, +past/types/basestring.py,sha256=qrImcr24wvdDCMvF9x0Tyx8S1lCt6GIwRvzuAmvg_Tg,728 +past/types/basestring.pyc,, +past/types/olddict.py,sha256=0YtffZ55VY6AyQ_rwu4DZ4vcRsp6dz-dQzczeyN8hLk,2721 +past/types/olddict.pyc,, +past/types/oldstr.py,sha256=PPSge0xthxHFvq_GLSRPjjoPzckmlU3N5WvN85Tw6xM,4273 +past/types/oldstr.pyc,, +past/utils/__init__.py,sha256=615AAEnnuC4NMohv07vqlaEgKZVgGFizk5sznounQ9Y,2633 +past/utils/__init__.pyc,, +queue/__init__.py,sha256=e1rZ2Mpporng-zJK-o1FVTXjUHIjbs1e8eXuvT-Qjug,375 +queue/__init__.pyc,, +reprlib/__init__.py,sha256=1h_GrFugWg11ZyZlXqyFRvhbgDMRHOYMftmkv4gJuBc,349 +reprlib/__init__.pyc,, +socketserver/__init__.py,sha256=sdl-H-eOi3Vg8ZnOzujmc9_l5q5kaFuvpOSpX0SpRH8,357 +socketserver/__init__.pyc,, +tkinter/__init__.py,sha256=Q-bHBRS4-GB-FZzLGhdz9V-1Fs4SfbgWSWduUMa721Y,808 +tkinter/__init__.pyc,, +tkinter/colorchooser.py,sha256=kprlmpRtvDbW5Gq43H1mi2KmNJ2kuzLQOba0a5EwDkU,333 +tkinter/colorchooser.pyc,, +tkinter/commondialog.py,sha256=mdUbq1IZqOGaSA7_8R367IukDCsMfzXiVHrTQQpp7Z0,333 +tkinter/commondialog.pyc,, +tkinter/constants.py,sha256=0qRUrZLRPdVxueABL9KTzzEWEsk6xM1rOjxK6OHxXtA,324 +tkinter/constants.pyc,, +tkinter/dialog.py,sha256=ksp-zvs-_A90P9RNHS8S27f1k8f48zG2Bel2jwZV5y0,311 +tkinter/dialog.pyc,, +tkinter/dnd.py,sha256=C_Ah0Urnyf2XKE5u-oP6mWi16RzMSXgMA1uhBSAwKY8,306 +tkinter/dnd.pyc,, +tkinter/filedialog.py,sha256=L-jJGtO1Zn8-y2Dv6zX2dhhT4PbfR_UTIavnZrqwgrI,529 +tkinter/filedialog.pyc,, +tkinter/font.py,sha256=TXarflhJRxqepaRNSDw6JFUVGz5P1T1C4_uF9VRqj3w,309 +tkinter/font.pyc,, +tkinter/messagebox.py,sha256=WJt4t83kLmr_UnpCWFuLoyazZr3wAUOEl6ADn3osoEA,327 +tkinter/messagebox.pyc,, +tkinter/scrolledtext.py,sha256=DRzN8aBAlDBUo1B2KDHzdpRSzXBfH4rOOz0iuHXbQcg,329 +tkinter/scrolledtext.pyc,, +tkinter/simpledialog.py,sha256=6MhuVhZCJV4XfPpPSUWKlDLLGEi0Y2ZlGQ9TbsmJFL0,329 +tkinter/simpledialog.pyc,, +tkinter/tix.py,sha256=aNeOfbWSGmcN69UmEGf4tJ-QIxLT6SU5ynzm1iWgepA,302 +tkinter/tix.pyc,, +tkinter/ttk.py,sha256=rRrJpDjcP2gjQNukECu4F026P-CkW-3Ca2tN6Oia-Fw,302 +tkinter/ttk.pyc,, +winreg/__init__.py,sha256=JuX4_LacOg48xmn0oERhWRtqHKTu5FPTSERX3b4IEBk,377 +winreg/__init__.pyc,, +xmlrpc/__init__.py,sha256=cuI7TcJ1aevAtq79-IIox_ohWc4ZvsA_xDG4GVd1KT8,335 +xmlrpc/__init__.pyc,, +xmlrpc/client.py,sha256=S14IklVTxdFPcsX8s1qYP50FbjVuKAaz63jcg9Vb7zs,106 +xmlrpc/client.pyc,, +xmlrpc/server.py,sha256=S14IklVTxdFPcsX8s1qYP50FbjVuKAaz63jcg9Vb7zs,106 +xmlrpc/server.pyc,, diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/EST b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/EST new file mode 100644 index 0000000000000000000000000000000000000000..21ebc00b3fc096035b9810519d778d04a3562a44 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/EST differ diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/EST5EDT b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/EST5EDT new file mode 100644 index 0000000000000000000000000000000000000000..9bce5007d4dbb871974a69cb0f68151c1ee22556 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/EST5EDT differ diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Egypt b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Egypt new file mode 100644 index 0000000000000000000000000000000000000000..d3f819623fc9ef90d327380fad15341ec1a0e202 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Egypt differ diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Eire b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Eire new file mode 100644 index 0000000000000000000000000000000000000000..1d994902db21814a626e42639d7a96b18ee73756 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Eire differ diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Factory b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Factory new file mode 100644 index 0000000000000000000000000000000000000000..60aa2a0d695ba577ff87624d479f1eb25c8f1caf Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pytz/zoneinfo/Factory differ diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools-41.2.0.dist-info/INSTALLER b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools-41.2.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools-41.2.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools-41.2.0.dist-info/dependency_links.txt b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools-41.2.0.dist-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..e87d02103ede91545d70783dd59653d183424b68 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools-41.2.0.dist-info/dependency_links.txt @@ -0,0 +1,2 @@ +https://files.pythonhosted.org/packages/source/c/certifi/certifi-2016.9.26.tar.gz#md5=baa81e951a29958563689d868ef1064d +https://files.pythonhosted.org/packages/source/w/wincertstore/wincertstore-0.2.zip#md5=ae728f2f007185648d0c7a8679b361e2 diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools-41.2.0.dist-info/entry_points.txt b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools-41.2.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..4159fd0a1b925dc63b5ddafc71dfcdf997e84002 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools-41.2.0.dist-info/entry_points.txt @@ -0,0 +1,65 @@ +[console_scripts] +easy_install = setuptools.command.easy_install:main +easy_install-3.6 = setuptools.command.easy_install:main + +[distutils.commands] +alias = setuptools.command.alias:alias +bdist_egg = setuptools.command.bdist_egg:bdist_egg +bdist_rpm = setuptools.command.bdist_rpm:bdist_rpm +bdist_wininst = setuptools.command.bdist_wininst:bdist_wininst +build_clib = setuptools.command.build_clib:build_clib +build_ext = setuptools.command.build_ext:build_ext +build_py = setuptools.command.build_py:build_py +develop = setuptools.command.develop:develop +dist_info = setuptools.command.dist_info:dist_info +easy_install = setuptools.command.easy_install:easy_install +egg_info = setuptools.command.egg_info:egg_info +install = setuptools.command.install:install +install_egg_info = setuptools.command.install_egg_info:install_egg_info +install_lib = setuptools.command.install_lib:install_lib +install_scripts = setuptools.command.install_scripts:install_scripts +register = setuptools.command.register:register +rotate = setuptools.command.rotate:rotate +saveopts = setuptools.command.saveopts:saveopts +sdist = setuptools.command.sdist:sdist +setopt = setuptools.command.setopt:setopt +test = setuptools.command.test:test +upload = setuptools.command.upload:upload +upload_docs = setuptools.command.upload_docs:upload_docs + +[distutils.setup_keywords] +convert_2to3_doctests = setuptools.dist:assert_string_list +dependency_links = setuptools.dist:assert_string_list +eager_resources = setuptools.dist:assert_string_list +entry_points = setuptools.dist:check_entry_points +exclude_package_data = setuptools.dist:check_package_data +extras_require = setuptools.dist:check_extras +include_package_data = setuptools.dist:assert_bool +install_requires = setuptools.dist:check_requirements +namespace_packages = setuptools.dist:check_nsp +package_data = setuptools.dist:check_package_data +packages = setuptools.dist:check_packages +python_requires = setuptools.dist:check_specifier +setup_requires = setuptools.dist:check_requirements +test_loader = setuptools.dist:check_importable +test_runner = setuptools.dist:check_importable +test_suite = setuptools.dist:check_test_suite +tests_require = setuptools.dist:check_requirements +use_2to3 = setuptools.dist:assert_bool +use_2to3_exclude_fixers = setuptools.dist:assert_string_list +use_2to3_fixers = setuptools.dist:assert_string_list +zip_safe = setuptools.dist:assert_bool + +[egg_info.writers] +PKG-INFO = setuptools.command.egg_info:write_pkg_info +dependency_links.txt = setuptools.command.egg_info:overwrite_arg +depends.txt = setuptools.command.egg_info:warn_depends_obsolete +eager_resources.txt = setuptools.command.egg_info:overwrite_arg +entry_points.txt = setuptools.command.egg_info:write_entries +namespace_packages.txt = setuptools.command.egg_info:overwrite_arg +requires.txt = setuptools.command.egg_info:write_requirements +top_level.txt = setuptools.command.egg_info:write_toplevel_names + +[setuptools.installation] +eggsecutable = setuptools.command.easy_install:bootstrap + diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/__init__.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a71b2bbdc6170963a66959c48080c1dedc7bb703 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/__init__.py @@ -0,0 +1,228 @@ +"""Extensions to the 'distutils' for large or complex distributions""" + +import os +import sys +import functools +import distutils.core +import distutils.filelist +import re +from distutils.errors import DistutilsOptionError +from distutils.util import convert_path +from fnmatch import fnmatchcase + +from ._deprecation_warning import SetuptoolsDeprecationWarning + +from setuptools.extern.six import PY3, string_types +from setuptools.extern.six.moves import filter, map + +import setuptools.version +from setuptools.extension import Extension +from setuptools.dist import Distribution, Feature +from setuptools.depends import Require +from . import monkey + +__metaclass__ = type + + +__all__ = [ + 'setup', 'Distribution', 'Feature', 'Command', 'Extension', 'Require', + 'SetuptoolsDeprecationWarning', + 'find_packages' +] + +if PY3: + __all__.append('find_namespace_packages') + +__version__ = setuptools.version.__version__ + +bootstrap_install_from = None + +# If we run 2to3 on .py files, should we also convert docstrings? +# Default: yes; assume that we can detect doctests reliably +run_2to3_on_doctests = True +# Standard package names for fixer packages +lib2to3_fixer_packages = ['lib2to3.fixes'] + + +class PackageFinder: + """ + Generate a list of all Python packages found within a directory + """ + + @classmethod + def find(cls, where='.', exclude=(), include=('*',)): + """Return a list all Python packages found within directory 'where' + + 'where' is the root directory which will be searched for packages. It + should be supplied as a "cross-platform" (i.e. URL-style) path; it will + be converted to the appropriate local path syntax. + + 'exclude' is a sequence of package names to exclude; '*' can be used + as a wildcard in the names, such that 'foo.*' will exclude all + subpackages of 'foo' (but not 'foo' itself). + + 'include' is a sequence of package names to include. If it's + specified, only the named packages will be included. If it's not + specified, all found packages will be included. 'include' can contain + shell style wildcard patterns just like 'exclude'. + """ + + return list(cls._find_packages_iter( + convert_path(where), + cls._build_filter('ez_setup', '*__pycache__', *exclude), + cls._build_filter(*include))) + + @classmethod + def _find_packages_iter(cls, where, exclude, include): + """ + All the packages found in 'where' that pass the 'include' filter, but + not the 'exclude' filter. + """ + for root, dirs, files in os.walk(where, followlinks=True): + # Copy dirs to iterate over it, then empty dirs. + all_dirs = dirs[:] + dirs[:] = [] + + for dir in all_dirs: + full_path = os.path.join(root, dir) + rel_path = os.path.relpath(full_path, where) + package = rel_path.replace(os.path.sep, '.') + + # Skip directory trees that are not valid packages + if ('.' in dir or not cls._looks_like_package(full_path)): + continue + + # Should this package be included? + if include(package) and not exclude(package): + yield package + + # Keep searching subdirectories, as there may be more packages + # down there, even if the parent was excluded. + dirs.append(dir) + + @staticmethod + def _looks_like_package(path): + """Does a directory look like a package?""" + return os.path.isfile(os.path.join(path, '__init__.py')) + + @staticmethod + def _build_filter(*patterns): + """ + Given a list of patterns, return a callable that will be true only if + the input matches at least one of the patterns. + """ + return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns) + + +class PEP420PackageFinder(PackageFinder): + @staticmethod + def _looks_like_package(path): + return True + + +find_packages = PackageFinder.find + +if PY3: + find_namespace_packages = PEP420PackageFinder.find + + +def _install_setup_requires(attrs): + # Note: do not use `setuptools.Distribution` directly, as + # our PEP 517 backend patch `distutils.core.Distribution`. + dist = distutils.core.Distribution(dict( + (k, v) for k, v in attrs.items() + if k in ('dependency_links', 'setup_requires') + )) + # Honor setup.cfg's options. + dist.parse_config_files(ignore_option_errors=True) + if dist.setup_requires: + dist.fetch_build_eggs(dist.setup_requires) + + +def setup(**attrs): + # Make sure we have any requirements needed to interpret 'attrs'. + _install_setup_requires(attrs) + return distutils.core.setup(**attrs) + +setup.__doc__ = distutils.core.setup.__doc__ + + +_Command = monkey.get_unpatched(distutils.core.Command) + + +class Command(_Command): + __doc__ = _Command.__doc__ + + command_consumes_arguments = False + + def __init__(self, dist, **kw): + """ + Construct the command for dist, updating + vars(self) with any keyword parameters. + """ + _Command.__init__(self, dist) + vars(self).update(kw) + + def _ensure_stringlike(self, option, what, default=None): + val = getattr(self, option) + if val is None: + setattr(self, option, default) + return default + elif not isinstance(val, string_types): + raise DistutilsOptionError("'%s' must be a %s (got `%s`)" + % (option, what, val)) + return val + + def ensure_string_list(self, option): + r"""Ensure that 'option' is a list of strings. If 'option' is + currently a string, we split it either on /,\s*/ or /\s+/, so + "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become + ["foo", "bar", "baz"]. + """ + val = getattr(self, option) + if val is None: + return + elif isinstance(val, string_types): + setattr(self, option, re.split(r',\s*|\s+', val)) + else: + if isinstance(val, list): + ok = all(isinstance(v, string_types) for v in val) + else: + ok = False + if not ok: + raise DistutilsOptionError( + "'%s' must be a list of strings (got %r)" + % (option, val)) + + def reinitialize_command(self, command, reinit_subcommands=0, **kw): + cmd = _Command.reinitialize_command(self, command, reinit_subcommands) + vars(cmd).update(kw) + return cmd + + +def _find_all_simple(path): + """ + Find all files under 'path' + """ + results = ( + os.path.join(base, file) + for base, dirs, files in os.walk(path, followlinks=True) + for file in files + ) + return filter(os.path.isfile, results) + + +def findall(dir=os.curdir): + """ + Find all files under 'dir' and return the list of full filenames. + Unless dir is '.', return full filenames with dir prepended. + """ + files = _find_all_simple(dir) + if dir == os.curdir: + make_rel = functools.partial(os.path.relpath, start=dir) + files = map(make_rel, files) + return list(files) + + +# Apply monkey patches +monkey.patch_all() diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_deprecation_warning.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_deprecation_warning.py new file mode 100644 index 0000000000000000000000000000000000000000..086b64dd3817c0c1a194ffc1959eeffdd2695bef --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_deprecation_warning.py @@ -0,0 +1,7 @@ +class SetuptoolsDeprecationWarning(Warning): + """ + Base class for warning deprecations in ``setuptools`` + + This class is not derived from ``DeprecationWarning``, and as such is + visible by default. + """ diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_vendor/__init__.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_vendor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_vendor/packaging/markers.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_vendor/packaging/markers.py new file mode 100644 index 0000000000000000000000000000000000000000..031332a3058f4bc47eadd320e63a2cdc6b76df25 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_vendor/packaging/markers.py @@ -0,0 +1,301 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +from __future__ import absolute_import, division, print_function + +import operator +import os +import platform +import sys + +from setuptools.extern.pyparsing import ParseException, ParseResults, stringStart, stringEnd +from setuptools.extern.pyparsing import ZeroOrMore, Group, Forward, QuotedString +from setuptools.extern.pyparsing import Literal as L # noqa + +from ._compat import string_types +from .specifiers import Specifier, InvalidSpecifier + + +__all__ = [ + "InvalidMarker", "UndefinedComparison", "UndefinedEnvironmentName", + "Marker", "default_environment", +] + + +class InvalidMarker(ValueError): + """ + An invalid marker was found, users should refer to PEP 508. + """ + + +class UndefinedComparison(ValueError): + """ + An invalid operation was attempted on a value that doesn't support it. + """ + + +class UndefinedEnvironmentName(ValueError): + """ + A name was attempted to be used that does not exist inside of the + environment. + """ + + +class Node(object): + + def __init__(self, value): + self.value = value + + def __str__(self): + return str(self.value) + + def __repr__(self): + return "<{0}({1!r})>".format(self.__class__.__name__, str(self)) + + def serialize(self): + raise NotImplementedError + + +class Variable(Node): + + def serialize(self): + return str(self) + + +class Value(Node): + + def serialize(self): + return '"{0}"'.format(self) + + +class Op(Node): + + def serialize(self): + return str(self) + + +VARIABLE = ( + L("implementation_version") | + L("platform_python_implementation") | + L("implementation_name") | + L("python_full_version") | + L("platform_release") | + L("platform_version") | + L("platform_machine") | + L("platform_system") | + L("python_version") | + L("sys_platform") | + L("os_name") | + L("os.name") | # PEP-345 + L("sys.platform") | # PEP-345 + L("platform.version") | # PEP-345 + L("platform.machine") | # PEP-345 + L("platform.python_implementation") | # PEP-345 + L("python_implementation") | # undocumented setuptools legacy + L("extra") +) +ALIASES = { + 'os.name': 'os_name', + 'sys.platform': 'sys_platform', + 'platform.version': 'platform_version', + 'platform.machine': 'platform_machine', + 'platform.python_implementation': 'platform_python_implementation', + 'python_implementation': 'platform_python_implementation' +} +VARIABLE.setParseAction(lambda s, l, t: Variable(ALIASES.get(t[0], t[0]))) + +VERSION_CMP = ( + L("===") | + L("==") | + L(">=") | + L("<=") | + L("!=") | + L("~=") | + L(">") | + L("<") +) + +MARKER_OP = VERSION_CMP | L("not in") | L("in") +MARKER_OP.setParseAction(lambda s, l, t: Op(t[0])) + +MARKER_VALUE = QuotedString("'") | QuotedString('"') +MARKER_VALUE.setParseAction(lambda s, l, t: Value(t[0])) + +BOOLOP = L("and") | L("or") + +MARKER_VAR = VARIABLE | MARKER_VALUE + +MARKER_ITEM = Group(MARKER_VAR + MARKER_OP + MARKER_VAR) +MARKER_ITEM.setParseAction(lambda s, l, t: tuple(t[0])) + +LPAREN = L("(").suppress() +RPAREN = L(")").suppress() + +MARKER_EXPR = Forward() +MARKER_ATOM = MARKER_ITEM | Group(LPAREN + MARKER_EXPR + RPAREN) +MARKER_EXPR << MARKER_ATOM + ZeroOrMore(BOOLOP + MARKER_EXPR) + +MARKER = stringStart + MARKER_EXPR + stringEnd + + +def _coerce_parse_result(results): + if isinstance(results, ParseResults): + return [_coerce_parse_result(i) for i in results] + else: + return results + + +def _format_marker(marker, first=True): + assert isinstance(marker, (list, tuple, string_types)) + + # Sometimes we have a structure like [[...]] which is a single item list + # where the single item is itself it's own list. In that case we want skip + # the rest of this function so that we don't get extraneous () on the + # outside. + if (isinstance(marker, list) and len(marker) == 1 and + isinstance(marker[0], (list, tuple))): + return _format_marker(marker[0]) + + if isinstance(marker, list): + inner = (_format_marker(m, first=False) for m in marker) + if first: + return " ".join(inner) + else: + return "(" + " ".join(inner) + ")" + elif isinstance(marker, tuple): + return " ".join([m.serialize() for m in marker]) + else: + return marker + + +_operators = { + "in": lambda lhs, rhs: lhs in rhs, + "not in": lambda lhs, rhs: lhs not in rhs, + "<": operator.lt, + "<=": operator.le, + "==": operator.eq, + "!=": operator.ne, + ">=": operator.ge, + ">": operator.gt, +} + + +def _eval_op(lhs, op, rhs): + try: + spec = Specifier("".join([op.serialize(), rhs])) + except InvalidSpecifier: + pass + else: + return spec.contains(lhs) + + oper = _operators.get(op.serialize()) + if oper is None: + raise UndefinedComparison( + "Undefined {0!r} on {1!r} and {2!r}.".format(op, lhs, rhs) + ) + + return oper(lhs, rhs) + + +_undefined = object() + + +def _get_env(environment, name): + value = environment.get(name, _undefined) + + if value is _undefined: + raise UndefinedEnvironmentName( + "{0!r} does not exist in evaluation environment.".format(name) + ) + + return value + + +def _evaluate_markers(markers, environment): + groups = [[]] + + for marker in markers: + assert isinstance(marker, (list, tuple, string_types)) + + if isinstance(marker, list): + groups[-1].append(_evaluate_markers(marker, environment)) + elif isinstance(marker, tuple): + lhs, op, rhs = marker + + if isinstance(lhs, Variable): + lhs_value = _get_env(environment, lhs.value) + rhs_value = rhs.value + else: + lhs_value = lhs.value + rhs_value = _get_env(environment, rhs.value) + + groups[-1].append(_eval_op(lhs_value, op, rhs_value)) + else: + assert marker in ["and", "or"] + if marker == "or": + groups.append([]) + + return any(all(item) for item in groups) + + +def format_full_version(info): + version = '{0.major}.{0.minor}.{0.micro}'.format(info) + kind = info.releaselevel + if kind != 'final': + version += kind[0] + str(info.serial) + return version + + +def default_environment(): + if hasattr(sys, 'implementation'): + iver = format_full_version(sys.implementation.version) + implementation_name = sys.implementation.name + else: + iver = '0' + implementation_name = '' + + return { + "implementation_name": implementation_name, + "implementation_version": iver, + "os_name": os.name, + "platform_machine": platform.machine(), + "platform_release": platform.release(), + "platform_system": platform.system(), + "platform_version": platform.version(), + "python_full_version": platform.python_version(), + "platform_python_implementation": platform.python_implementation(), + "python_version": platform.python_version()[:3], + "sys_platform": sys.platform, + } + + +class Marker(object): + + def __init__(self, marker): + try: + self._markers = _coerce_parse_result(MARKER.parseString(marker)) + except ParseException as e: + err_str = "Invalid marker: {0!r}, parse error at {1!r}".format( + marker, marker[e.loc:e.loc + 8]) + raise InvalidMarker(err_str) + + def __str__(self): + return _format_marker(self._markers) + + def __repr__(self): + return "".format(str(self)) + + def evaluate(self, environment=None): + """Evaluate a marker. + + Return the boolean from evaluating the given marker against the + environment. environment is an optional argument to override all or + part of the determined environment. + + The environment is determined from the current Python process. + """ + current_environment = default_environment() + if environment is not None: + current_environment.update(environment) + + return _evaluate_markers(self._markers, current_environment) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_vendor/packaging/requirements.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_vendor/packaging/requirements.py new file mode 100644 index 0000000000000000000000000000000000000000..5b493416f215081b46c901d76c3a4b4648a32296 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_vendor/packaging/requirements.py @@ -0,0 +1,127 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +from __future__ import absolute_import, division, print_function + +import string +import re + +from setuptools.extern.pyparsing import stringStart, stringEnd, originalTextFor, ParseException +from setuptools.extern.pyparsing import ZeroOrMore, Word, Optional, Regex, Combine +from setuptools.extern.pyparsing import Literal as L # noqa +from setuptools.extern.six.moves.urllib import parse as urlparse + +from .markers import MARKER_EXPR, Marker +from .specifiers import LegacySpecifier, Specifier, SpecifierSet + + +class InvalidRequirement(ValueError): + """ + An invalid requirement was found, users should refer to PEP 508. + """ + + +ALPHANUM = Word(string.ascii_letters + string.digits) + +LBRACKET = L("[").suppress() +RBRACKET = L("]").suppress() +LPAREN = L("(").suppress() +RPAREN = L(")").suppress() +COMMA = L(",").suppress() +SEMICOLON = L(";").suppress() +AT = L("@").suppress() + +PUNCTUATION = Word("-_.") +IDENTIFIER_END = ALPHANUM | (ZeroOrMore(PUNCTUATION) + ALPHANUM) +IDENTIFIER = Combine(ALPHANUM + ZeroOrMore(IDENTIFIER_END)) + +NAME = IDENTIFIER("name") +EXTRA = IDENTIFIER + +URI = Regex(r'[^ ]+')("url") +URL = (AT + URI) + +EXTRAS_LIST = EXTRA + ZeroOrMore(COMMA + EXTRA) +EXTRAS = (LBRACKET + Optional(EXTRAS_LIST) + RBRACKET)("extras") + +VERSION_PEP440 = Regex(Specifier._regex_str, re.VERBOSE | re.IGNORECASE) +VERSION_LEGACY = Regex(LegacySpecifier._regex_str, re.VERBOSE | re.IGNORECASE) + +VERSION_ONE = VERSION_PEP440 ^ VERSION_LEGACY +VERSION_MANY = Combine(VERSION_ONE + ZeroOrMore(COMMA + VERSION_ONE), + joinString=",", adjacent=False)("_raw_spec") +_VERSION_SPEC = Optional(((LPAREN + VERSION_MANY + RPAREN) | VERSION_MANY)) +_VERSION_SPEC.setParseAction(lambda s, l, t: t._raw_spec or '') + +VERSION_SPEC = originalTextFor(_VERSION_SPEC)("specifier") +VERSION_SPEC.setParseAction(lambda s, l, t: t[1]) + +MARKER_EXPR = originalTextFor(MARKER_EXPR())("marker") +MARKER_EXPR.setParseAction( + lambda s, l, t: Marker(s[t._original_start:t._original_end]) +) +MARKER_SEPERATOR = SEMICOLON +MARKER = MARKER_SEPERATOR + MARKER_EXPR + +VERSION_AND_MARKER = VERSION_SPEC + Optional(MARKER) +URL_AND_MARKER = URL + Optional(MARKER) + +NAMED_REQUIREMENT = \ + NAME + Optional(EXTRAS) + (URL_AND_MARKER | VERSION_AND_MARKER) + +REQUIREMENT = stringStart + NAMED_REQUIREMENT + stringEnd + + +class Requirement(object): + """Parse a requirement. + + Parse a given requirement string into its parts, such as name, specifier, + URL, and extras. Raises InvalidRequirement on a badly-formed requirement + string. + """ + + # TODO: Can we test whether something is contained within a requirement? + # If so how do we do that? Do we need to test against the _name_ of + # the thing as well as the version? What about the markers? + # TODO: Can we normalize the name and extra name? + + def __init__(self, requirement_string): + try: + req = REQUIREMENT.parseString(requirement_string) + except ParseException as e: + raise InvalidRequirement( + "Invalid requirement, parse error at \"{0!r}\"".format( + requirement_string[e.loc:e.loc + 8])) + + self.name = req.name + if req.url: + parsed_url = urlparse.urlparse(req.url) + if not (parsed_url.scheme and parsed_url.netloc) or ( + not parsed_url.scheme and not parsed_url.netloc): + raise InvalidRequirement("Invalid URL given") + self.url = req.url + else: + self.url = None + self.extras = set(req.extras.asList() if req.extras else []) + self.specifier = SpecifierSet(req.specifier) + self.marker = req.marker if req.marker else None + + def __str__(self): + parts = [self.name] + + if self.extras: + parts.append("[{0}]".format(",".join(sorted(self.extras)))) + + if self.specifier: + parts.append(str(self.specifier)) + + if self.url: + parts.append("@ {0}".format(self.url)) + + if self.marker: + parts.append("; {0}".format(self.marker)) + + return "".join(parts) + + def __repr__(self): + return "".format(str(self)) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_vendor/packaging/specifiers.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_vendor/packaging/specifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..7f5a76cfd63f47dcce29b3ea82f59d10f4e8d771 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_vendor/packaging/specifiers.py @@ -0,0 +1,774 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +from __future__ import absolute_import, division, print_function + +import abc +import functools +import itertools +import re + +from ._compat import string_types, with_metaclass +from .version import Version, LegacyVersion, parse + + +class InvalidSpecifier(ValueError): + """ + An invalid specifier was found, users should refer to PEP 440. + """ + + +class BaseSpecifier(with_metaclass(abc.ABCMeta, object)): + + @abc.abstractmethod + def __str__(self): + """ + Returns the str representation of this Specifier like object. This + should be representative of the Specifier itself. + """ + + @abc.abstractmethod + def __hash__(self): + """ + Returns a hash value for this Specifier like object. + """ + + @abc.abstractmethod + def __eq__(self, other): + """ + Returns a boolean representing whether or not the two Specifier like + objects are equal. + """ + + @abc.abstractmethod + def __ne__(self, other): + """ + Returns a boolean representing whether or not the two Specifier like + objects are not equal. + """ + + @abc.abstractproperty + def prereleases(self): + """ + Returns whether or not pre-releases as a whole are allowed by this + specifier. + """ + + @prereleases.setter + def prereleases(self, value): + """ + Sets whether or not pre-releases as a whole are allowed by this + specifier. + """ + + @abc.abstractmethod + def contains(self, item, prereleases=None): + """ + Determines if the given item is contained within this specifier. + """ + + @abc.abstractmethod + def filter(self, iterable, prereleases=None): + """ + Takes an iterable of items and filters them so that only items which + are contained within this specifier are allowed in it. + """ + + +class _IndividualSpecifier(BaseSpecifier): + + _operators = {} + + def __init__(self, spec="", prereleases=None): + match = self._regex.search(spec) + if not match: + raise InvalidSpecifier("Invalid specifier: '{0}'".format(spec)) + + self._spec = ( + match.group("operator").strip(), + match.group("version").strip(), + ) + + # Store whether or not this Specifier should accept prereleases + self._prereleases = prereleases + + def __repr__(self): + pre = ( + ", prereleases={0!r}".format(self.prereleases) + if self._prereleases is not None + else "" + ) + + return "<{0}({1!r}{2})>".format( + self.__class__.__name__, + str(self), + pre, + ) + + def __str__(self): + return "{0}{1}".format(*self._spec) + + def __hash__(self): + return hash(self._spec) + + def __eq__(self, other): + if isinstance(other, string_types): + try: + other = self.__class__(other) + except InvalidSpecifier: + return NotImplemented + elif not isinstance(other, self.__class__): + return NotImplemented + + return self._spec == other._spec + + def __ne__(self, other): + if isinstance(other, string_types): + try: + other = self.__class__(other) + except InvalidSpecifier: + return NotImplemented + elif not isinstance(other, self.__class__): + return NotImplemented + + return self._spec != other._spec + + def _get_operator(self, op): + return getattr(self, "_compare_{0}".format(self._operators[op])) + + def _coerce_version(self, version): + if not isinstance(version, (LegacyVersion, Version)): + version = parse(version) + return version + + @property + def operator(self): + return self._spec[0] + + @property + def version(self): + return self._spec[1] + + @property + def prereleases(self): + return self._prereleases + + @prereleases.setter + def prereleases(self, value): + self._prereleases = value + + def __contains__(self, item): + return self.contains(item) + + def contains(self, item, prereleases=None): + # Determine if prereleases are to be allowed or not. + if prereleases is None: + prereleases = self.prereleases + + # Normalize item to a Version or LegacyVersion, this allows us to have + # a shortcut for ``"2.0" in Specifier(">=2") + item = self._coerce_version(item) + + # Determine if we should be supporting prereleases in this specifier + # or not, if we do not support prereleases than we can short circuit + # logic if this version is a prereleases. + if item.is_prerelease and not prereleases: + return False + + # Actually do the comparison to determine if this item is contained + # within this Specifier or not. + return self._get_operator(self.operator)(item, self.version) + + def filter(self, iterable, prereleases=None): + yielded = False + found_prereleases = [] + + kw = {"prereleases": prereleases if prereleases is not None else True} + + # Attempt to iterate over all the values in the iterable and if any of + # them match, yield them. + for version in iterable: + parsed_version = self._coerce_version(version) + + if self.contains(parsed_version, **kw): + # If our version is a prerelease, and we were not set to allow + # prereleases, then we'll store it for later incase nothing + # else matches this specifier. + if (parsed_version.is_prerelease and not + (prereleases or self.prereleases)): + found_prereleases.append(version) + # Either this is not a prerelease, or we should have been + # accepting prereleases from the begining. + else: + yielded = True + yield version + + # Now that we've iterated over everything, determine if we've yielded + # any values, and if we have not and we have any prereleases stored up + # then we will go ahead and yield the prereleases. + if not yielded and found_prereleases: + for version in found_prereleases: + yield version + + +class LegacySpecifier(_IndividualSpecifier): + + _regex_str = ( + r""" + (?P(==|!=|<=|>=|<|>)) + \s* + (?P + [^,;\s)]* # Since this is a "legacy" specifier, and the version + # string can be just about anything, we match everything + # except for whitespace, a semi-colon for marker support, + # a closing paren since versions can be enclosed in + # them, and a comma since it's a version separator. + ) + """ + ) + + _regex = re.compile( + r"^\s*" + _regex_str + r"\s*$", re.VERBOSE | re.IGNORECASE) + + _operators = { + "==": "equal", + "!=": "not_equal", + "<=": "less_than_equal", + ">=": "greater_than_equal", + "<": "less_than", + ">": "greater_than", + } + + def _coerce_version(self, version): + if not isinstance(version, LegacyVersion): + version = LegacyVersion(str(version)) + return version + + def _compare_equal(self, prospective, spec): + return prospective == self._coerce_version(spec) + + def _compare_not_equal(self, prospective, spec): + return prospective != self._coerce_version(spec) + + def _compare_less_than_equal(self, prospective, spec): + return prospective <= self._coerce_version(spec) + + def _compare_greater_than_equal(self, prospective, spec): + return prospective >= self._coerce_version(spec) + + def _compare_less_than(self, prospective, spec): + return prospective < self._coerce_version(spec) + + def _compare_greater_than(self, prospective, spec): + return prospective > self._coerce_version(spec) + + +def _require_version_compare(fn): + @functools.wraps(fn) + def wrapped(self, prospective, spec): + if not isinstance(prospective, Version): + return False + return fn(self, prospective, spec) + return wrapped + + +class Specifier(_IndividualSpecifier): + + _regex_str = ( + r""" + (?P(~=|==|!=|<=|>=|<|>|===)) + (?P + (?: + # The identity operators allow for an escape hatch that will + # do an exact string match of the version you wish to install. + # This will not be parsed by PEP 440 and we cannot determine + # any semantic meaning from it. This operator is discouraged + # but included entirely as an escape hatch. + (?<====) # Only match for the identity operator + \s* + [^\s]* # We just match everything, except for whitespace + # since we are only testing for strict identity. + ) + | + (?: + # The (non)equality operators allow for wild card and local + # versions to be specified so we have to define these two + # operators separately to enable that. + (?<===|!=) # Only match for equals and not equals + + \s* + v? + (?:[0-9]+!)? # epoch + [0-9]+(?:\.[0-9]+)* # release + (?: # pre release + [-_\.]? + (a|b|c|rc|alpha|beta|pre|preview) + [-_\.]? + [0-9]* + )? + (?: # post release + (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) + )? + + # You cannot use a wild card and a dev or local version + # together so group them with a | and make them optional. + (?: + (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release + (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local + | + \.\* # Wild card syntax of .* + )? + ) + | + (?: + # The compatible operator requires at least two digits in the + # release segment. + (?<=~=) # Only match for the compatible operator + + \s* + v? + (?:[0-9]+!)? # epoch + [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *) + (?: # pre release + [-_\.]? + (a|b|c|rc|alpha|beta|pre|preview) + [-_\.]? + [0-9]* + )? + (?: # post release + (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) + )? + (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release + ) + | + (?: + # All other operators only allow a sub set of what the + # (non)equality operators do. Specifically they do not allow + # local versions to be specified nor do they allow the prefix + # matching wild cards. + (?=": "greater_than_equal", + "<": "less_than", + ">": "greater_than", + "===": "arbitrary", + } + + @_require_version_compare + def _compare_compatible(self, prospective, spec): + # Compatible releases have an equivalent combination of >= and ==. That + # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to + # implement this in terms of the other specifiers instead of + # implementing it ourselves. The only thing we need to do is construct + # the other specifiers. + + # We want everything but the last item in the version, but we want to + # ignore post and dev releases and we want to treat the pre-release as + # it's own separate segment. + prefix = ".".join( + list( + itertools.takewhile( + lambda x: (not x.startswith("post") and not + x.startswith("dev")), + _version_split(spec), + ) + )[:-1] + ) + + # Add the prefix notation to the end of our string + prefix += ".*" + + return (self._get_operator(">=")(prospective, spec) and + self._get_operator("==")(prospective, prefix)) + + @_require_version_compare + def _compare_equal(self, prospective, spec): + # We need special logic to handle prefix matching + if spec.endswith(".*"): + # In the case of prefix matching we want to ignore local segment. + prospective = Version(prospective.public) + # Split the spec out by dots, and pretend that there is an implicit + # dot in between a release segment and a pre-release segment. + spec = _version_split(spec[:-2]) # Remove the trailing .* + + # Split the prospective version out by dots, and pretend that there + # is an implicit dot in between a release segment and a pre-release + # segment. + prospective = _version_split(str(prospective)) + + # Shorten the prospective version to be the same length as the spec + # so that we can determine if the specifier is a prefix of the + # prospective version or not. + prospective = prospective[:len(spec)] + + # Pad out our two sides with zeros so that they both equal the same + # length. + spec, prospective = _pad_version(spec, prospective) + else: + # Convert our spec string into a Version + spec = Version(spec) + + # If the specifier does not have a local segment, then we want to + # act as if the prospective version also does not have a local + # segment. + if not spec.local: + prospective = Version(prospective.public) + + return prospective == spec + + @_require_version_compare + def _compare_not_equal(self, prospective, spec): + return not self._compare_equal(prospective, spec) + + @_require_version_compare + def _compare_less_than_equal(self, prospective, spec): + return prospective <= Version(spec) + + @_require_version_compare + def _compare_greater_than_equal(self, prospective, spec): + return prospective >= Version(spec) + + @_require_version_compare + def _compare_less_than(self, prospective, spec): + # Convert our spec to a Version instance, since we'll want to work with + # it as a version. + spec = Version(spec) + + # Check to see if the prospective version is less than the spec + # version. If it's not we can short circuit and just return False now + # instead of doing extra unneeded work. + if not prospective < spec: + return False + + # This special case is here so that, unless the specifier itself + # includes is a pre-release version, that we do not accept pre-release + # versions for the version mentioned in the specifier (e.g. <3.1 should + # not match 3.1.dev0, but should match 3.0.dev0). + if not spec.is_prerelease and prospective.is_prerelease: + if Version(prospective.base_version) == Version(spec.base_version): + return False + + # If we've gotten to here, it means that prospective version is both + # less than the spec version *and* it's not a pre-release of the same + # version in the spec. + return True + + @_require_version_compare + def _compare_greater_than(self, prospective, spec): + # Convert our spec to a Version instance, since we'll want to work with + # it as a version. + spec = Version(spec) + + # Check to see if the prospective version is greater than the spec + # version. If it's not we can short circuit and just return False now + # instead of doing extra unneeded work. + if not prospective > spec: + return False + + # This special case is here so that, unless the specifier itself + # includes is a post-release version, that we do not accept + # post-release versions for the version mentioned in the specifier + # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0). + if not spec.is_postrelease and prospective.is_postrelease: + if Version(prospective.base_version) == Version(spec.base_version): + return False + + # Ensure that we do not allow a local version of the version mentioned + # in the specifier, which is techincally greater than, to match. + if prospective.local is not None: + if Version(prospective.base_version) == Version(spec.base_version): + return False + + # If we've gotten to here, it means that prospective version is both + # greater than the spec version *and* it's not a pre-release of the + # same version in the spec. + return True + + def _compare_arbitrary(self, prospective, spec): + return str(prospective).lower() == str(spec).lower() + + @property + def prereleases(self): + # If there is an explicit prereleases set for this, then we'll just + # blindly use that. + if self._prereleases is not None: + return self._prereleases + + # Look at all of our specifiers and determine if they are inclusive + # operators, and if they are if they are including an explicit + # prerelease. + operator, version = self._spec + if operator in ["==", ">=", "<=", "~=", "==="]: + # The == specifier can include a trailing .*, if it does we + # want to remove before parsing. + if operator == "==" and version.endswith(".*"): + version = version[:-2] + + # Parse the version, and if it is a pre-release than this + # specifier allows pre-releases. + if parse(version).is_prerelease: + return True + + return False + + @prereleases.setter + def prereleases(self, value): + self._prereleases = value + + +_prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$") + + +def _version_split(version): + result = [] + for item in version.split("."): + match = _prefix_regex.search(item) + if match: + result.extend(match.groups()) + else: + result.append(item) + return result + + +def _pad_version(left, right): + left_split, right_split = [], [] + + # Get the release segment of our versions + left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left))) + right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right))) + + # Get the rest of our versions + left_split.append(left[len(left_split[0]):]) + right_split.append(right[len(right_split[0]):]) + + # Insert our padding + left_split.insert( + 1, + ["0"] * max(0, len(right_split[0]) - len(left_split[0])), + ) + right_split.insert( + 1, + ["0"] * max(0, len(left_split[0]) - len(right_split[0])), + ) + + return ( + list(itertools.chain(*left_split)), + list(itertools.chain(*right_split)), + ) + + +class SpecifierSet(BaseSpecifier): + + def __init__(self, specifiers="", prereleases=None): + # Split on , to break each indidivual specifier into it's own item, and + # strip each item to remove leading/trailing whitespace. + specifiers = [s.strip() for s in specifiers.split(",") if s.strip()] + + # Parsed each individual specifier, attempting first to make it a + # Specifier and falling back to a LegacySpecifier. + parsed = set() + for specifier in specifiers: + try: + parsed.add(Specifier(specifier)) + except InvalidSpecifier: + parsed.add(LegacySpecifier(specifier)) + + # Turn our parsed specifiers into a frozen set and save them for later. + self._specs = frozenset(parsed) + + # Store our prereleases value so we can use it later to determine if + # we accept prereleases or not. + self._prereleases = prereleases + + def __repr__(self): + pre = ( + ", prereleases={0!r}".format(self.prereleases) + if self._prereleases is not None + else "" + ) + + return "".format(str(self), pre) + + def __str__(self): + return ",".join(sorted(str(s) for s in self._specs)) + + def __hash__(self): + return hash(self._specs) + + def __and__(self, other): + if isinstance(other, string_types): + other = SpecifierSet(other) + elif not isinstance(other, SpecifierSet): + return NotImplemented + + specifier = SpecifierSet() + specifier._specs = frozenset(self._specs | other._specs) + + if self._prereleases is None and other._prereleases is not None: + specifier._prereleases = other._prereleases + elif self._prereleases is not None and other._prereleases is None: + specifier._prereleases = self._prereleases + elif self._prereleases == other._prereleases: + specifier._prereleases = self._prereleases + else: + raise ValueError( + "Cannot combine SpecifierSets with True and False prerelease " + "overrides." + ) + + return specifier + + def __eq__(self, other): + if isinstance(other, string_types): + other = SpecifierSet(other) + elif isinstance(other, _IndividualSpecifier): + other = SpecifierSet(str(other)) + elif not isinstance(other, SpecifierSet): + return NotImplemented + + return self._specs == other._specs + + def __ne__(self, other): + if isinstance(other, string_types): + other = SpecifierSet(other) + elif isinstance(other, _IndividualSpecifier): + other = SpecifierSet(str(other)) + elif not isinstance(other, SpecifierSet): + return NotImplemented + + return self._specs != other._specs + + def __len__(self): + return len(self._specs) + + def __iter__(self): + return iter(self._specs) + + @property + def prereleases(self): + # If we have been given an explicit prerelease modifier, then we'll + # pass that through here. + if self._prereleases is not None: + return self._prereleases + + # If we don't have any specifiers, and we don't have a forced value, + # then we'll just return None since we don't know if this should have + # pre-releases or not. + if not self._specs: + return None + + # Otherwise we'll see if any of the given specifiers accept + # prereleases, if any of them do we'll return True, otherwise False. + return any(s.prereleases for s in self._specs) + + @prereleases.setter + def prereleases(self, value): + self._prereleases = value + + def __contains__(self, item): + return self.contains(item) + + def contains(self, item, prereleases=None): + # Ensure that our item is a Version or LegacyVersion instance. + if not isinstance(item, (LegacyVersion, Version)): + item = parse(item) + + # Determine if we're forcing a prerelease or not, if we're not forcing + # one for this particular filter call, then we'll use whatever the + # SpecifierSet thinks for whether or not we should support prereleases. + if prereleases is None: + prereleases = self.prereleases + + # We can determine if we're going to allow pre-releases by looking to + # see if any of the underlying items supports them. If none of them do + # and this item is a pre-release then we do not allow it and we can + # short circuit that here. + # Note: This means that 1.0.dev1 would not be contained in something + # like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0 + if not prereleases and item.is_prerelease: + return False + + # We simply dispatch to the underlying specs here to make sure that the + # given version is contained within all of them. + # Note: This use of all() here means that an empty set of specifiers + # will always return True, this is an explicit design decision. + return all( + s.contains(item, prereleases=prereleases) + for s in self._specs + ) + + def filter(self, iterable, prereleases=None): + # Determine if we're forcing a prerelease or not, if we're not forcing + # one for this particular filter call, then we'll use whatever the + # SpecifierSet thinks for whether or not we should support prereleases. + if prereleases is None: + prereleases = self.prereleases + + # If we have any specifiers, then we want to wrap our iterable in the + # filter method for each one, this will act as a logical AND amongst + # each specifier. + if self._specs: + for spec in self._specs: + iterable = spec.filter(iterable, prereleases=bool(prereleases)) + return iterable + # If we do not have any specifiers, then we need to have a rough filter + # which will filter out any pre-releases, unless there are no final + # releases, and which will filter out LegacyVersion in general. + else: + filtered = [] + found_prereleases = [] + + for item in iterable: + # Ensure that we some kind of Version class for this item. + if not isinstance(item, (LegacyVersion, Version)): + parsed_version = parse(item) + else: + parsed_version = item + + # Filter out any item which is parsed as a LegacyVersion + if isinstance(parsed_version, LegacyVersion): + continue + + # Store any item which is a pre-release for later unless we've + # already found a final version or we are accepting prereleases + if parsed_version.is_prerelease and not prereleases: + if not filtered: + found_prereleases.append(item) + else: + filtered.append(item) + + # If we've found no items except for pre-releases, then we'll go + # ahead and use the pre-releases + if not filtered and found_prereleases and prereleases is None: + return found_prereleases + + return filtered diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_vendor/pyparsing.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_vendor/pyparsing.py new file mode 100644 index 0000000000000000000000000000000000000000..cf75e1e5fcbfe7eac41d2a9e446c5c980741087b --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_vendor/pyparsing.py @@ -0,0 +1,5742 @@ +# module pyparsing.py +# +# Copyright (c) 2003-2018 Paul T. McGuire +# +# 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. +# + +__doc__ = \ +""" +pyparsing module - Classes and methods to define and execute parsing grammars +============================================================================= + +The pyparsing module is an alternative approach to creating and executing simple grammars, +vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you +don't need to learn a new syntax for defining grammars or matching expressions - the parsing module +provides a library of classes that you use to construct the grammar directly in Python. + +Here is a program to parse "Hello, World!" (or any greeting of the form +C{", !"}), built up using L{Word}, L{Literal}, and L{And} elements +(L{'+'} operator gives L{And} expressions, strings are auto-converted to +L{Literal} expressions):: + + from pyparsing import Word, alphas + + # define grammar of a greeting + greet = Word(alphas) + "," + Word(alphas) + "!" + + hello = "Hello, World!" + print (hello, "->", greet.parseString(hello)) + +The program outputs the following:: + + Hello, World! -> ['Hello', ',', 'World', '!'] + +The Python representation of the grammar is quite readable, owing to the self-explanatory +class names, and the use of '+', '|' and '^' operators. + +The L{ParseResults} object returned from L{ParserElement.parseString} can be accessed as a nested list, a dictionary, or an +object with named attributes. + +The pyparsing module handles some of the problems that are typically vexing when writing text parsers: + - extra or missing whitespace (the above program will also handle "Hello,World!", "Hello , World !", etc.) + - quoted strings + - embedded comments + + +Getting Started - +----------------- +Visit the classes L{ParserElement} and L{ParseResults} to see the base classes that most other pyparsing +classes inherit from. Use the docstrings for examples of how to: + - construct literal match expressions from L{Literal} and L{CaselessLiteral} classes + - construct character word-group expressions using the L{Word} class + - see how to create repetitive expressions using L{ZeroOrMore} and L{OneOrMore} classes + - use L{'+'}, L{'|'}, L{'^'}, and L{'&'} operators to combine simple expressions into more complex ones + - associate names with your parsed results using L{ParserElement.setResultsName} + - find some helpful expression short-cuts like L{delimitedList} and L{oneOf} + - find more useful common expressions in the L{pyparsing_common} namespace class +""" + +__version__ = "2.2.1" +__versionTime__ = "18 Sep 2018 00:49 UTC" +__author__ = "Paul McGuire " + +import string +from weakref import ref as wkref +import copy +import sys +import warnings +import re +import sre_constants +import collections +import pprint +import traceback +import types +from datetime import datetime + +try: + from _thread import RLock +except ImportError: + from threading import RLock + +try: + # Python 3 + from collections.abc import Iterable + from collections.abc import MutableMapping +except ImportError: + # Python 2.7 + from collections import Iterable + from collections import MutableMapping + +try: + from collections import OrderedDict as _OrderedDict +except ImportError: + try: + from ordereddict import OrderedDict as _OrderedDict + except ImportError: + _OrderedDict = None + +#~ sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) ) + +__all__ = [ +'And', 'CaselessKeyword', 'CaselessLiteral', 'CharsNotIn', 'Combine', 'Dict', 'Each', 'Empty', +'FollowedBy', 'Forward', 'GoToColumn', 'Group', 'Keyword', 'LineEnd', 'LineStart', 'Literal', +'MatchFirst', 'NoMatch', 'NotAny', 'OneOrMore', 'OnlyOnce', 'Optional', 'Or', +'ParseBaseException', 'ParseElementEnhance', 'ParseException', 'ParseExpression', 'ParseFatalException', +'ParseResults', 'ParseSyntaxException', 'ParserElement', 'QuotedString', 'RecursiveGrammarException', +'Regex', 'SkipTo', 'StringEnd', 'StringStart', 'Suppress', 'Token', 'TokenConverter', +'White', 'Word', 'WordEnd', 'WordStart', 'ZeroOrMore', +'alphanums', 'alphas', 'alphas8bit', 'anyCloseTag', 'anyOpenTag', 'cStyleComment', 'col', +'commaSeparatedList', 'commonHTMLEntity', 'countedArray', 'cppStyleComment', 'dblQuotedString', +'dblSlashComment', 'delimitedList', 'dictOf', 'downcaseTokens', 'empty', 'hexnums', +'htmlComment', 'javaStyleComment', 'line', 'lineEnd', 'lineStart', 'lineno', +'makeHTMLTags', 'makeXMLTags', 'matchOnlyAtCol', 'matchPreviousExpr', 'matchPreviousLiteral', +'nestedExpr', 'nullDebugAction', 'nums', 'oneOf', 'opAssoc', 'operatorPrecedence', 'printables', +'punc8bit', 'pythonStyleComment', 'quotedString', 'removeQuotes', 'replaceHTMLEntity', +'replaceWith', 'restOfLine', 'sglQuotedString', 'srange', 'stringEnd', +'stringStart', 'traceParseAction', 'unicodeString', 'upcaseTokens', 'withAttribute', +'indentedBlock', 'originalTextFor', 'ungroup', 'infixNotation','locatedExpr', 'withClass', +'CloseMatch', 'tokenMap', 'pyparsing_common', +] + +system_version = tuple(sys.version_info)[:3] +PY_3 = system_version[0] == 3 +if PY_3: + _MAX_INT = sys.maxsize + basestring = str + unichr = chr + _ustr = str + + # build list of single arg builtins, that can be used as parse actions + singleArgBuiltins = [sum, len, sorted, reversed, list, tuple, set, any, all, min, max] + +else: + _MAX_INT = sys.maxint + range = xrange + + def _ustr(obj): + """Drop-in replacement for str(obj) that tries to be Unicode friendly. It first tries + str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It + then < returns the unicode object | encodes it with the default encoding | ... >. + """ + if isinstance(obj,unicode): + return obj + + try: + # If this works, then _ustr(obj) has the same behaviour as str(obj), so + # it won't break any existing code. + return str(obj) + + except UnicodeEncodeError: + # Else encode it + ret = unicode(obj).encode(sys.getdefaultencoding(), 'xmlcharrefreplace') + xmlcharref = Regex(r'&#\d+;') + xmlcharref.setParseAction(lambda t: '\\u' + hex(int(t[0][2:-1]))[2:]) + return xmlcharref.transformString(ret) + + # build list of single arg builtins, tolerant of Python version, that can be used as parse actions + singleArgBuiltins = [] + import __builtin__ + for fname in "sum len sorted reversed list tuple set any all min max".split(): + try: + singleArgBuiltins.append(getattr(__builtin__,fname)) + except AttributeError: + continue + +_generatorType = type((y for y in range(1))) + +def _xml_escape(data): + """Escape &, <, >, ", ', etc. in a string of data.""" + + # ampersand must be replaced first + from_symbols = '&><"\'' + to_symbols = ('&'+s+';' for s in "amp gt lt quot apos".split()) + for from_,to_ in zip(from_symbols, to_symbols): + data = data.replace(from_, to_) + return data + +class _Constants(object): + pass + +alphas = string.ascii_uppercase + string.ascii_lowercase +nums = "0123456789" +hexnums = nums + "ABCDEFabcdef" +alphanums = alphas + nums +_bslash = chr(92) +printables = "".join(c for c in string.printable if c not in string.whitespace) + +class ParseBaseException(Exception): + """base exception class for all parsing runtime exceptions""" + # Performance tuning: we construct a *lot* of these, so keep this + # constructor as small and fast as possible + def __init__( self, pstr, loc=0, msg=None, elem=None ): + self.loc = loc + if msg is None: + self.msg = pstr + self.pstr = "" + else: + self.msg = msg + self.pstr = pstr + self.parserElement = elem + self.args = (pstr, loc, msg) + + @classmethod + def _from_exception(cls, pe): + """ + internal factory method to simplify creating one type of ParseException + from another - avoids having __init__ signature conflicts among subclasses + """ + return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement) + + def __getattr__( self, aname ): + """supported attributes by name are: + - lineno - returns the line number of the exception text + - col - returns the column number of the exception text + - line - returns the line containing the exception text + """ + if( aname == "lineno" ): + return lineno( self.loc, self.pstr ) + elif( aname in ("col", "column") ): + return col( self.loc, self.pstr ) + elif( aname == "line" ): + return line( self.loc, self.pstr ) + else: + raise AttributeError(aname) + + def __str__( self ): + return "%s (at char %d), (line:%d, col:%d)" % \ + ( self.msg, self.loc, self.lineno, self.column ) + def __repr__( self ): + return _ustr(self) + def markInputline( self, markerString = ">!<" ): + """Extracts the exception line from the input string, and marks + the location of the exception with a special symbol. + """ + line_str = self.line + line_column = self.column - 1 + if markerString: + line_str = "".join((line_str[:line_column], + markerString, line_str[line_column:])) + return line_str.strip() + def __dir__(self): + return "lineno col line".split() + dir(type(self)) + +class ParseException(ParseBaseException): + """ + Exception thrown when parse expressions don't match class; + supported attributes by name are: + - lineno - returns the line number of the exception text + - col - returns the column number of the exception text + - line - returns the line containing the exception text + + Example:: + try: + Word(nums).setName("integer").parseString("ABC") + except ParseException as pe: + print(pe) + print("column: {}".format(pe.col)) + + prints:: + Expected integer (at char 0), (line:1, col:1) + column: 1 + """ + pass + +class ParseFatalException(ParseBaseException): + """user-throwable exception thrown when inconsistent parse content + is found; stops all parsing immediately""" + pass + +class ParseSyntaxException(ParseFatalException): + """just like L{ParseFatalException}, but thrown internally when an + L{ErrorStop} ('-' operator) indicates that parsing is to stop + immediately because an unbacktrackable syntax error has been found""" + pass + +#~ class ReparseException(ParseBaseException): + #~ """Experimental class - parse actions can raise this exception to cause + #~ pyparsing to reparse the input string: + #~ - with a modified input string, and/or + #~ - with a modified start location + #~ Set the values of the ReparseException in the constructor, and raise the + #~ exception in a parse action to cause pyparsing to use the new string/location. + #~ Setting the values as None causes no change to be made. + #~ """ + #~ def __init_( self, newstring, restartLoc ): + #~ self.newParseText = newstring + #~ self.reparseLoc = restartLoc + +class RecursiveGrammarException(Exception): + """exception thrown by L{ParserElement.validate} if the grammar could be improperly recursive""" + def __init__( self, parseElementList ): + self.parseElementTrace = parseElementList + + def __str__( self ): + return "RecursiveGrammarException: %s" % self.parseElementTrace + +class _ParseResultsWithOffset(object): + def __init__(self,p1,p2): + self.tup = (p1,p2) + def __getitem__(self,i): + return self.tup[i] + def __repr__(self): + return repr(self.tup[0]) + def setOffset(self,i): + self.tup = (self.tup[0],i) + +class ParseResults(object): + """ + Structured parse results, to provide multiple means of access to the parsed data: + - as a list (C{len(results)}) + - by list index (C{results[0], results[1]}, etc.) + - by attribute (C{results.} - see L{ParserElement.setResultsName}) + + Example:: + integer = Word(nums) + date_str = (integer.setResultsName("year") + '/' + + integer.setResultsName("month") + '/' + + integer.setResultsName("day")) + # equivalent form: + # date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + # parseString returns a ParseResults object + result = date_str.parseString("1999/12/31") + + def test(s, fn=repr): + print("%s -> %s" % (s, fn(eval(s)))) + test("list(result)") + test("result[0]") + test("result['month']") + test("result.day") + test("'month' in result") + test("'minutes' in result") + test("result.dump()", str) + prints:: + list(result) -> ['1999', '/', '12', '/', '31'] + result[0] -> '1999' + result['month'] -> '12' + result.day -> '31' + 'month' in result -> True + 'minutes' in result -> False + result.dump() -> ['1999', '/', '12', '/', '31'] + - day: 31 + - month: 12 + - year: 1999 + """ + def __new__(cls, toklist=None, name=None, asList=True, modal=True ): + if isinstance(toklist, cls): + return toklist + retobj = object.__new__(cls) + retobj.__doinit = True + return retobj + + # Performance tuning: we construct a *lot* of these, so keep this + # constructor as small and fast as possible + def __init__( self, toklist=None, name=None, asList=True, modal=True, isinstance=isinstance ): + if self.__doinit: + self.__doinit = False + self.__name = None + self.__parent = None + self.__accumNames = {} + self.__asList = asList + self.__modal = modal + if toklist is None: + toklist = [] + if isinstance(toklist, list): + self.__toklist = toklist[:] + elif isinstance(toklist, _generatorType): + self.__toklist = list(toklist) + else: + self.__toklist = [toklist] + self.__tokdict = dict() + + if name is not None and name: + if not modal: + self.__accumNames[name] = 0 + if isinstance(name,int): + name = _ustr(name) # will always return a str, but use _ustr for consistency + self.__name = name + if not (isinstance(toklist, (type(None), basestring, list)) and toklist in (None,'',[])): + if isinstance(toklist,basestring): + toklist = [ toklist ] + if asList: + if isinstance(toklist,ParseResults): + self[name] = _ParseResultsWithOffset(toklist.copy(),0) + else: + self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]),0) + self[name].__name = name + else: + try: + self[name] = toklist[0] + except (KeyError,TypeError,IndexError): + self[name] = toklist + + def __getitem__( self, i ): + if isinstance( i, (int,slice) ): + return self.__toklist[i] + else: + if i not in self.__accumNames: + return self.__tokdict[i][-1][0] + else: + return ParseResults([ v[0] for v in self.__tokdict[i] ]) + + def __setitem__( self, k, v, isinstance=isinstance ): + if isinstance(v,_ParseResultsWithOffset): + self.__tokdict[k] = self.__tokdict.get(k,list()) + [v] + sub = v[0] + elif isinstance(k,(int,slice)): + self.__toklist[k] = v + sub = v + else: + self.__tokdict[k] = self.__tokdict.get(k,list()) + [_ParseResultsWithOffset(v,0)] + sub = v + if isinstance(sub,ParseResults): + sub.__parent = wkref(self) + + def __delitem__( self, i ): + if isinstance(i,(int,slice)): + mylen = len( self.__toklist ) + del self.__toklist[i] + + # convert int to slice + if isinstance(i, int): + if i < 0: + i += mylen + i = slice(i, i+1) + # get removed indices + removed = list(range(*i.indices(mylen))) + removed.reverse() + # fixup indices in token dictionary + for name,occurrences in self.__tokdict.items(): + for j in removed: + for k, (value, position) in enumerate(occurrences): + occurrences[k] = _ParseResultsWithOffset(value, position - (position > j)) + else: + del self.__tokdict[i] + + def __contains__( self, k ): + return k in self.__tokdict + + def __len__( self ): return len( self.__toklist ) + def __bool__(self): return ( not not self.__toklist ) + __nonzero__ = __bool__ + def __iter__( self ): return iter( self.__toklist ) + def __reversed__( self ): return iter( self.__toklist[::-1] ) + def _iterkeys( self ): + if hasattr(self.__tokdict, "iterkeys"): + return self.__tokdict.iterkeys() + else: + return iter(self.__tokdict) + + def _itervalues( self ): + return (self[k] for k in self._iterkeys()) + + def _iteritems( self ): + return ((k, self[k]) for k in self._iterkeys()) + + if PY_3: + keys = _iterkeys + """Returns an iterator of all named result keys (Python 3.x only).""" + + values = _itervalues + """Returns an iterator of all named result values (Python 3.x only).""" + + items = _iteritems + """Returns an iterator of all named result key-value tuples (Python 3.x only).""" + + else: + iterkeys = _iterkeys + """Returns an iterator of all named result keys (Python 2.x only).""" + + itervalues = _itervalues + """Returns an iterator of all named result values (Python 2.x only).""" + + iteritems = _iteritems + """Returns an iterator of all named result key-value tuples (Python 2.x only).""" + + def keys( self ): + """Returns all named result keys (as a list in Python 2.x, as an iterator in Python 3.x).""" + return list(self.iterkeys()) + + def values( self ): + """Returns all named result values (as a list in Python 2.x, as an iterator in Python 3.x).""" + return list(self.itervalues()) + + def items( self ): + """Returns all named result key-values (as a list of tuples in Python 2.x, as an iterator in Python 3.x).""" + return list(self.iteritems()) + + def haskeys( self ): + """Since keys() returns an iterator, this method is helpful in bypassing + code that looks for the existence of any defined results names.""" + return bool(self.__tokdict) + + def pop( self, *args, **kwargs): + """ + Removes and returns item at specified index (default=C{last}). + Supports both C{list} and C{dict} semantics for C{pop()}. If passed no + argument or an integer argument, it will use C{list} semantics + and pop tokens from the list of parsed tokens. If passed a + non-integer argument (most likely a string), it will use C{dict} + semantics and pop the corresponding value from any defined + results names. A second default return value argument is + supported, just as in C{dict.pop()}. + + Example:: + def remove_first(tokens): + tokens.pop(0) + print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] + print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321'] + + label = Word(alphas) + patt = label("LABEL") + OneOrMore(Word(nums)) + print(patt.parseString("AAB 123 321").dump()) + + # Use pop() in a parse action to remove named result (note that corresponding value is not + # removed from list form of results) + def remove_LABEL(tokens): + tokens.pop("LABEL") + return tokens + patt.addParseAction(remove_LABEL) + print(patt.parseString("AAB 123 321").dump()) + prints:: + ['AAB', '123', '321'] + - LABEL: AAB + + ['AAB', '123', '321'] + """ + if not args: + args = [-1] + for k,v in kwargs.items(): + if k == 'default': + args = (args[0], v) + else: + raise TypeError("pop() got an unexpected keyword argument '%s'" % k) + if (isinstance(args[0], int) or + len(args) == 1 or + args[0] in self): + index = args[0] + ret = self[index] + del self[index] + return ret + else: + defaultvalue = args[1] + return defaultvalue + + def get(self, key, defaultValue=None): + """ + Returns named result matching the given key, or if there is no + such name, then returns the given C{defaultValue} or C{None} if no + C{defaultValue} is specified. + + Similar to C{dict.get()}. + + Example:: + integer = Word(nums) + date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + result = date_str.parseString("1999/12/31") + print(result.get("year")) # -> '1999' + print(result.get("hour", "not specified")) # -> 'not specified' + print(result.get("hour")) # -> None + """ + if key in self: + return self[key] + else: + return defaultValue + + def insert( self, index, insStr ): + """ + Inserts new element at location index in the list of parsed tokens. + + Similar to C{list.insert()}. + + Example:: + print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] + + # use a parse action to insert the parse location in the front of the parsed results + def insert_locn(locn, tokens): + tokens.insert(0, locn) + print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321'] + """ + self.__toklist.insert(index, insStr) + # fixup indices in token dictionary + for name,occurrences in self.__tokdict.items(): + for k, (value, position) in enumerate(occurrences): + occurrences[k] = _ParseResultsWithOffset(value, position + (position > index)) + + def append( self, item ): + """ + Add single element to end of ParseResults list of elements. + + Example:: + print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] + + # use a parse action to compute the sum of the parsed integers, and add it to the end + def append_sum(tokens): + tokens.append(sum(map(int, tokens))) + print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444] + """ + self.__toklist.append(item) + + def extend( self, itemseq ): + """ + Add sequence of elements to end of ParseResults list of elements. + + Example:: + patt = OneOrMore(Word(alphas)) + + # use a parse action to append the reverse of the matched strings, to make a palindrome + def make_palindrome(tokens): + tokens.extend(reversed([t[::-1] for t in tokens])) + return ''.join(tokens) + print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl' + """ + if isinstance(itemseq, ParseResults): + self += itemseq + else: + self.__toklist.extend(itemseq) + + def clear( self ): + """ + Clear all elements and results names. + """ + del self.__toklist[:] + self.__tokdict.clear() + + def __getattr__( self, name ): + try: + return self[name] + except KeyError: + return "" + + if name in self.__tokdict: + if name not in self.__accumNames: + return self.__tokdict[name][-1][0] + else: + return ParseResults([ v[0] for v in self.__tokdict[name] ]) + else: + return "" + + def __add__( self, other ): + ret = self.copy() + ret += other + return ret + + def __iadd__( self, other ): + if other.__tokdict: + offset = len(self.__toklist) + addoffset = lambda a: offset if a<0 else a+offset + otheritems = other.__tokdict.items() + otherdictitems = [(k, _ParseResultsWithOffset(v[0],addoffset(v[1])) ) + for (k,vlist) in otheritems for v in vlist] + for k,v in otherdictitems: + self[k] = v + if isinstance(v[0],ParseResults): + v[0].__parent = wkref(self) + + self.__toklist += other.__toklist + self.__accumNames.update( other.__accumNames ) + return self + + def __radd__(self, other): + if isinstance(other,int) and other == 0: + # useful for merging many ParseResults using sum() builtin + return self.copy() + else: + # this may raise a TypeError - so be it + return other + self + + def __repr__( self ): + return "(%s, %s)" % ( repr( self.__toklist ), repr( self.__tokdict ) ) + + def __str__( self ): + return '[' + ', '.join(_ustr(i) if isinstance(i, ParseResults) else repr(i) for i in self.__toklist) + ']' + + def _asStringList( self, sep='' ): + out = [] + for item in self.__toklist: + if out and sep: + out.append(sep) + if isinstance( item, ParseResults ): + out += item._asStringList() + else: + out.append( _ustr(item) ) + return out + + def asList( self ): + """ + Returns the parse results as a nested list of matching tokens, all converted to strings. + + Example:: + patt = OneOrMore(Word(alphas)) + result = patt.parseString("sldkj lsdkj sldkj") + # even though the result prints in string-like form, it is actually a pyparsing ParseResults + print(type(result), result) # -> ['sldkj', 'lsdkj', 'sldkj'] + + # Use asList() to create an actual list + result_list = result.asList() + print(type(result_list), result_list) # -> ['sldkj', 'lsdkj', 'sldkj'] + """ + return [res.asList() if isinstance(res,ParseResults) else res for res in self.__toklist] + + def asDict( self ): + """ + Returns the named parse results as a nested dictionary. + + Example:: + integer = Word(nums) + date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + result = date_str.parseString('12/31/1999') + print(type(result), repr(result)) # -> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]}) + + result_dict = result.asDict() + print(type(result_dict), repr(result_dict)) # -> {'day': '1999', 'year': '12', 'month': '31'} + + # even though a ParseResults supports dict-like access, sometime you just need to have a dict + import json + print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable + print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"} + """ + if PY_3: + item_fn = self.items + else: + item_fn = self.iteritems + + def toItem(obj): + if isinstance(obj, ParseResults): + if obj.haskeys(): + return obj.asDict() + else: + return [toItem(v) for v in obj] + else: + return obj + + return dict((k,toItem(v)) for k,v in item_fn()) + + def copy( self ): + """ + Returns a new copy of a C{ParseResults} object. + """ + ret = ParseResults( self.__toklist ) + ret.__tokdict = self.__tokdict.copy() + ret.__parent = self.__parent + ret.__accumNames.update( self.__accumNames ) + ret.__name = self.__name + return ret + + def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ): + """ + (Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names. + """ + nl = "\n" + out = [] + namedItems = dict((v[1],k) for (k,vlist) in self.__tokdict.items() + for v in vlist) + nextLevelIndent = indent + " " + + # collapse out indents if formatting is not desired + if not formatted: + indent = "" + nextLevelIndent = "" + nl = "" + + selfTag = None + if doctag is not None: + selfTag = doctag + else: + if self.__name: + selfTag = self.__name + + if not selfTag: + if namedItemsOnly: + return "" + else: + selfTag = "ITEM" + + out += [ nl, indent, "<", selfTag, ">" ] + + for i,res in enumerate(self.__toklist): + if isinstance(res,ParseResults): + if i in namedItems: + out += [ res.asXML(namedItems[i], + namedItemsOnly and doctag is None, + nextLevelIndent, + formatted)] + else: + out += [ res.asXML(None, + namedItemsOnly and doctag is None, + nextLevelIndent, + formatted)] + else: + # individual token, see if there is a name for it + resTag = None + if i in namedItems: + resTag = namedItems[i] + if not resTag: + if namedItemsOnly: + continue + else: + resTag = "ITEM" + xmlBodyText = _xml_escape(_ustr(res)) + out += [ nl, nextLevelIndent, "<", resTag, ">", + xmlBodyText, + "" ] + + out += [ nl, indent, "" ] + return "".join(out) + + def __lookup(self,sub): + for k,vlist in self.__tokdict.items(): + for v,loc in vlist: + if sub is v: + return k + return None + + def getName(self): + r""" + Returns the results name for this token expression. Useful when several + different expressions might match at a particular location. + + Example:: + integer = Word(nums) + ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d") + house_number_expr = Suppress('#') + Word(nums, alphanums) + user_data = (Group(house_number_expr)("house_number") + | Group(ssn_expr)("ssn") + | Group(integer)("age")) + user_info = OneOrMore(user_data) + + result = user_info.parseString("22 111-22-3333 #221B") + for item in result: + print(item.getName(), ':', item[0]) + prints:: + age : 22 + ssn : 111-22-3333 + house_number : 221B + """ + if self.__name: + return self.__name + elif self.__parent: + par = self.__parent() + if par: + return par.__lookup(self) + else: + return None + elif (len(self) == 1 and + len(self.__tokdict) == 1 and + next(iter(self.__tokdict.values()))[0][1] in (0,-1)): + return next(iter(self.__tokdict.keys())) + else: + return None + + def dump(self, indent='', depth=0, full=True): + """ + Diagnostic method for listing out the contents of a C{ParseResults}. + Accepts an optional C{indent} argument so that this string can be embedded + in a nested display of other data. + + Example:: + integer = Word(nums) + date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + result = date_str.parseString('12/31/1999') + print(result.dump()) + prints:: + ['12', '/', '31', '/', '1999'] + - day: 1999 + - month: 31 + - year: 12 + """ + out = [] + NL = '\n' + out.append( indent+_ustr(self.asList()) ) + if full: + if self.haskeys(): + items = sorted((str(k), v) for k,v in self.items()) + for k,v in items: + if out: + out.append(NL) + out.append( "%s%s- %s: " % (indent,(' '*depth), k) ) + if isinstance(v,ParseResults): + if v: + out.append( v.dump(indent,depth+1) ) + else: + out.append(_ustr(v)) + else: + out.append(repr(v)) + elif any(isinstance(vv,ParseResults) for vv in self): + v = self + for i,vv in enumerate(v): + if isinstance(vv,ParseResults): + out.append("\n%s%s[%d]:\n%s%s%s" % (indent,(' '*(depth)),i,indent,(' '*(depth+1)),vv.dump(indent,depth+1) )) + else: + out.append("\n%s%s[%d]:\n%s%s%s" % (indent,(' '*(depth)),i,indent,(' '*(depth+1)),_ustr(vv))) + + return "".join(out) + + def pprint(self, *args, **kwargs): + """ + Pretty-printer for parsed results as a list, using the C{pprint} module. + Accepts additional positional or keyword args as defined for the + C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint}) + + Example:: + ident = Word(alphas, alphanums) + num = Word(nums) + func = Forward() + term = ident | num | Group('(' + func + ')') + func <<= ident + Group(Optional(delimitedList(term))) + result = func.parseString("fna a,b,(fnb c,d,200),100") + result.pprint(width=40) + prints:: + ['fna', + ['a', + 'b', + ['(', 'fnb', ['c', 'd', '200'], ')'], + '100']] + """ + pprint.pprint(self.asList(), *args, **kwargs) + + # add support for pickle protocol + def __getstate__(self): + return ( self.__toklist, + ( self.__tokdict.copy(), + self.__parent is not None and self.__parent() or None, + self.__accumNames, + self.__name ) ) + + def __setstate__(self,state): + self.__toklist = state[0] + (self.__tokdict, + par, + inAccumNames, + self.__name) = state[1] + self.__accumNames = {} + self.__accumNames.update(inAccumNames) + if par is not None: + self.__parent = wkref(par) + else: + self.__parent = None + + def __getnewargs__(self): + return self.__toklist, self.__name, self.__asList, self.__modal + + def __dir__(self): + return (dir(type(self)) + list(self.keys())) + +MutableMapping.register(ParseResults) + +def col (loc,strg): + """Returns current column within a string, counting newlines as line separators. + The first column is number 1. + + Note: the default parsing behavior is to expand tabs in the input string + before starting the parsing process. See L{I{ParserElement.parseString}} for more information + on parsing strings containing C{}s, and suggested methods to maintain a + consistent view of the parsed string, the parse location, and line and column + positions within the parsed string. + """ + s = strg + return 1 if 0} for more information + on parsing strings containing C{}s, and suggested methods to maintain a + consistent view of the parsed string, the parse location, and line and column + positions within the parsed string. + """ + return strg.count("\n",0,loc) + 1 + +def line( loc, strg ): + """Returns the line of text containing loc within a string, counting newlines as line separators. + """ + lastCR = strg.rfind("\n", 0, loc) + nextCR = strg.find("\n", loc) + if nextCR >= 0: + return strg[lastCR+1:nextCR] + else: + return strg[lastCR+1:] + +def _defaultStartDebugAction( instring, loc, expr ): + print (("Match " + _ustr(expr) + " at loc " + _ustr(loc) + "(%d,%d)" % ( lineno(loc,instring), col(loc,instring) ))) + +def _defaultSuccessDebugAction( instring, startloc, endloc, expr, toks ): + print ("Matched " + _ustr(expr) + " -> " + str(toks.asList())) + +def _defaultExceptionDebugAction( instring, loc, expr, exc ): + print ("Exception raised:" + _ustr(exc)) + +def nullDebugAction(*args): + """'Do-nothing' debug action, to suppress debugging output during parsing.""" + pass + +# Only works on Python 3.x - nonlocal is toxic to Python 2 installs +#~ 'decorator to trim function calls to match the arity of the target' +#~ def _trim_arity(func, maxargs=3): + #~ if func in singleArgBuiltins: + #~ return lambda s,l,t: func(t) + #~ limit = 0 + #~ foundArity = False + #~ def wrapper(*args): + #~ nonlocal limit,foundArity + #~ while 1: + #~ try: + #~ ret = func(*args[limit:]) + #~ foundArity = True + #~ return ret + #~ except TypeError: + #~ if limit == maxargs or foundArity: + #~ raise + #~ limit += 1 + #~ continue + #~ return wrapper + +# this version is Python 2.x-3.x cross-compatible +'decorator to trim function calls to match the arity of the target' +def _trim_arity(func, maxargs=2): + if func in singleArgBuiltins: + return lambda s,l,t: func(t) + limit = [0] + foundArity = [False] + + # traceback return data structure changed in Py3.5 - normalize back to plain tuples + if system_version[:2] >= (3,5): + def extract_stack(limit=0): + # special handling for Python 3.5.0 - extra deep call stack by 1 + offset = -3 if system_version == (3,5,0) else -2 + frame_summary = traceback.extract_stack(limit=-offset+limit-1)[offset] + return [frame_summary[:2]] + def extract_tb(tb, limit=0): + frames = traceback.extract_tb(tb, limit=limit) + frame_summary = frames[-1] + return [frame_summary[:2]] + else: + extract_stack = traceback.extract_stack + extract_tb = traceback.extract_tb + + # synthesize what would be returned by traceback.extract_stack at the call to + # user's parse action 'func', so that we don't incur call penalty at parse time + + LINE_DIFF = 6 + # IF ANY CODE CHANGES, EVEN JUST COMMENTS OR BLANK LINES, BETWEEN THE NEXT LINE AND + # THE CALL TO FUNC INSIDE WRAPPER, LINE_DIFF MUST BE MODIFIED!!!! + this_line = extract_stack(limit=2)[-1] + pa_call_line_synth = (this_line[0], this_line[1]+LINE_DIFF) + + def wrapper(*args): + while 1: + try: + ret = func(*args[limit[0]:]) + foundArity[0] = True + return ret + except TypeError: + # re-raise TypeErrors if they did not come from our arity testing + if foundArity[0]: + raise + else: + try: + tb = sys.exc_info()[-1] + if not extract_tb(tb, limit=2)[-1][:2] == pa_call_line_synth: + raise + finally: + del tb + + if limit[0] <= maxargs: + limit[0] += 1 + continue + raise + + # copy func name to wrapper for sensible debug output + func_name = "" + try: + func_name = getattr(func, '__name__', + getattr(func, '__class__').__name__) + except Exception: + func_name = str(func) + wrapper.__name__ = func_name + + return wrapper + +class ParserElement(object): + """Abstract base level parser element class.""" + DEFAULT_WHITE_CHARS = " \n\t\r" + verbose_stacktrace = False + + @staticmethod + def setDefaultWhitespaceChars( chars ): + r""" + Overrides the default whitespace chars + + Example:: + # default whitespace chars are space, and newline + OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl'] + + # change to just treat newline as significant + ParserElement.setDefaultWhitespaceChars(" \t") + OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def'] + """ + ParserElement.DEFAULT_WHITE_CHARS = chars + + @staticmethod + def inlineLiteralsUsing(cls): + """ + Set class to be used for inclusion of string literals into a parser. + + Example:: + # default literal class used is Literal + integer = Word(nums) + date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] + + + # change to Suppress + ParserElement.inlineLiteralsUsing(Suppress) + date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + date_str.parseString("1999/12/31") # -> ['1999', '12', '31'] + """ + ParserElement._literalStringClass = cls + + def __init__( self, savelist=False ): + self.parseAction = list() + self.failAction = None + #~ self.name = "" # don't define self.name, let subclasses try/except upcall + self.strRepr = None + self.resultsName = None + self.saveAsList = savelist + self.skipWhitespace = True + self.whiteChars = ParserElement.DEFAULT_WHITE_CHARS + self.copyDefaultWhiteChars = True + self.mayReturnEmpty = False # used when checking for left-recursion + self.keepTabs = False + self.ignoreExprs = list() + self.debug = False + self.streamlined = False + self.mayIndexError = True # used to optimize exception handling for subclasses that don't advance parse index + self.errmsg = "" + self.modalResults = True # used to mark results names as modal (report only last) or cumulative (list all) + self.debugActions = ( None, None, None ) #custom debug actions + self.re = None + self.callPreparse = True # used to avoid redundant calls to preParse + self.callDuringTry = False + + def copy( self ): + """ + Make a copy of this C{ParserElement}. Useful for defining different parse actions + for the same parsing pattern, using copies of the original parse element. + + Example:: + integer = Word(nums).setParseAction(lambda toks: int(toks[0])) + integerK = integer.copy().addParseAction(lambda toks: toks[0]*1024) + Suppress("K") + integerM = integer.copy().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M") + + print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M")) + prints:: + [5120, 100, 655360, 268435456] + Equivalent form of C{expr.copy()} is just C{expr()}:: + integerM = integer().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M") + """ + cpy = copy.copy( self ) + cpy.parseAction = self.parseAction[:] + cpy.ignoreExprs = self.ignoreExprs[:] + if self.copyDefaultWhiteChars: + cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS + return cpy + + def setName( self, name ): + """ + Define name for this expression, makes debugging and exception messages clearer. + + Example:: + Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1) + Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1) + """ + self.name = name + self.errmsg = "Expected " + self.name + if hasattr(self,"exception"): + self.exception.msg = self.errmsg + return self + + def setResultsName( self, name, listAllMatches=False ): + """ + Define name for referencing matching tokens as a nested attribute + of the returned parse results. + NOTE: this returns a *copy* of the original C{ParserElement} object; + this is so that the client can define a basic element, such as an + integer, and reference it in multiple places with different names. + + You can also set results names using the abbreviated syntax, + C{expr("name")} in place of C{expr.setResultsName("name")} - + see L{I{__call__}<__call__>}. + + Example:: + date_str = (integer.setResultsName("year") + '/' + + integer.setResultsName("month") + '/' + + integer.setResultsName("day")) + + # equivalent form: + date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + """ + newself = self.copy() + if name.endswith("*"): + name = name[:-1] + listAllMatches=True + newself.resultsName = name + newself.modalResults = not listAllMatches + return newself + + def setBreak(self,breakFlag = True): + """Method to invoke the Python pdb debugger when this element is + about to be parsed. Set C{breakFlag} to True to enable, False to + disable. + """ + if breakFlag: + _parseMethod = self._parse + def breaker(instring, loc, doActions=True, callPreParse=True): + import pdb + pdb.set_trace() + return _parseMethod( instring, loc, doActions, callPreParse ) + breaker._originalParseMethod = _parseMethod + self._parse = breaker + else: + if hasattr(self._parse,"_originalParseMethod"): + self._parse = self._parse._originalParseMethod + return self + + def setParseAction( self, *fns, **kwargs ): + """ + Define one or more actions to perform when successfully matching parse element definition. + Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)}, + C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where: + - s = the original string being parsed (see note below) + - loc = the location of the matching substring + - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object + If the functions in fns modify the tokens, they can return them as the return + value from fn, and the modified list of tokens will replace the original. + Otherwise, fn does not need to return any value. + + Optional keyword arguments: + - callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing + + Note: the default parsing behavior is to expand tabs in the input string + before starting the parsing process. See L{I{parseString}} for more information + on parsing strings containing C{}s, and suggested methods to maintain a + consistent view of the parsed string, the parse location, and line and column + positions within the parsed string. + + Example:: + integer = Word(nums) + date_str = integer + '/' + integer + '/' + integer + + date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] + + # use parse action to convert to ints at parse time + integer = Word(nums).setParseAction(lambda toks: int(toks[0])) + date_str = integer + '/' + integer + '/' + integer + + # note that integer fields are now ints, not strings + date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31] + """ + self.parseAction = list(map(_trim_arity, list(fns))) + self.callDuringTry = kwargs.get("callDuringTry", False) + return self + + def addParseAction( self, *fns, **kwargs ): + """ + Add one or more parse actions to expression's list of parse actions. See L{I{setParseAction}}. + + See examples in L{I{copy}}. + """ + self.parseAction += list(map(_trim_arity, list(fns))) + self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False) + return self + + def addCondition(self, *fns, **kwargs): + """Add a boolean predicate function to expression's list of parse actions. See + L{I{setParseAction}} for function call signatures. Unlike C{setParseAction}, + functions passed to C{addCondition} need to return boolean success/fail of the condition. + + Optional keyword arguments: + - message = define a custom message to be used in the raised exception + - fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException + + Example:: + integer = Word(nums).setParseAction(lambda toks: int(toks[0])) + year_int = integer.copy() + year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later") + date_str = year_int + '/' + integer + '/' + integer + + result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1) + """ + msg = kwargs.get("message", "failed user-defined condition") + exc_type = ParseFatalException if kwargs.get("fatal", False) else ParseException + for fn in fns: + def pa(s,l,t): + if not bool(_trim_arity(fn)(s,l,t)): + raise exc_type(s,l,msg) + self.parseAction.append(pa) + self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False) + return self + + def setFailAction( self, fn ): + """Define action to perform if parsing fails at this expression. + Fail acton fn is a callable function that takes the arguments + C{fn(s,loc,expr,err)} where: + - s = string being parsed + - loc = location where expression match was attempted and failed + - expr = the parse expression that failed + - err = the exception thrown + The function returns no value. It may throw C{L{ParseFatalException}} + if it is desired to stop parsing immediately.""" + self.failAction = fn + return self + + def _skipIgnorables( self, instring, loc ): + exprsFound = True + while exprsFound: + exprsFound = False + for e in self.ignoreExprs: + try: + while 1: + loc,dummy = e._parse( instring, loc ) + exprsFound = True + except ParseException: + pass + return loc + + def preParse( self, instring, loc ): + if self.ignoreExprs: + loc = self._skipIgnorables( instring, loc ) + + if self.skipWhitespace: + wt = self.whiteChars + instrlen = len(instring) + while loc < instrlen and instring[loc] in wt: + loc += 1 + + return loc + + def parseImpl( self, instring, loc, doActions=True ): + return loc, [] + + def postParse( self, instring, loc, tokenlist ): + return tokenlist + + #~ @profile + def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ): + debugging = ( self.debug ) #and doActions ) + + if debugging or self.failAction: + #~ print ("Match",self,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )) + if (self.debugActions[0] ): + self.debugActions[0]( instring, loc, self ) + if callPreParse and self.callPreparse: + preloc = self.preParse( instring, loc ) + else: + preloc = loc + tokensStart = preloc + try: + try: + loc,tokens = self.parseImpl( instring, preloc, doActions ) + except IndexError: + raise ParseException( instring, len(instring), self.errmsg, self ) + except ParseBaseException as err: + #~ print ("Exception raised:", err) + if self.debugActions[2]: + self.debugActions[2]( instring, tokensStart, self, err ) + if self.failAction: + self.failAction( instring, tokensStart, self, err ) + raise + else: + if callPreParse and self.callPreparse: + preloc = self.preParse( instring, loc ) + else: + preloc = loc + tokensStart = preloc + if self.mayIndexError or preloc >= len(instring): + try: + loc,tokens = self.parseImpl( instring, preloc, doActions ) + except IndexError: + raise ParseException( instring, len(instring), self.errmsg, self ) + else: + loc,tokens = self.parseImpl( instring, preloc, doActions ) + + tokens = self.postParse( instring, loc, tokens ) + + retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults ) + if self.parseAction and (doActions or self.callDuringTry): + if debugging: + try: + for fn in self.parseAction: + tokens = fn( instring, tokensStart, retTokens ) + if tokens is not None: + retTokens = ParseResults( tokens, + self.resultsName, + asList=self.saveAsList and isinstance(tokens,(ParseResults,list)), + modal=self.modalResults ) + except ParseBaseException as err: + #~ print "Exception raised in user parse action:", err + if (self.debugActions[2] ): + self.debugActions[2]( instring, tokensStart, self, err ) + raise + else: + for fn in self.parseAction: + tokens = fn( instring, tokensStart, retTokens ) + if tokens is not None: + retTokens = ParseResults( tokens, + self.resultsName, + asList=self.saveAsList and isinstance(tokens,(ParseResults,list)), + modal=self.modalResults ) + if debugging: + #~ print ("Matched",self,"->",retTokens.asList()) + if (self.debugActions[1] ): + self.debugActions[1]( instring, tokensStart, loc, self, retTokens ) + + return loc, retTokens + + def tryParse( self, instring, loc ): + try: + return self._parse( instring, loc, doActions=False )[0] + except ParseFatalException: + raise ParseException( instring, loc, self.errmsg, self) + + def canParseNext(self, instring, loc): + try: + self.tryParse(instring, loc) + except (ParseException, IndexError): + return False + else: + return True + + class _UnboundedCache(object): + def __init__(self): + cache = {} + self.not_in_cache = not_in_cache = object() + + def get(self, key): + return cache.get(key, not_in_cache) + + def set(self, key, value): + cache[key] = value + + def clear(self): + cache.clear() + + def cache_len(self): + return len(cache) + + self.get = types.MethodType(get, self) + self.set = types.MethodType(set, self) + self.clear = types.MethodType(clear, self) + self.__len__ = types.MethodType(cache_len, self) + + if _OrderedDict is not None: + class _FifoCache(object): + def __init__(self, size): + self.not_in_cache = not_in_cache = object() + + cache = _OrderedDict() + + def get(self, key): + return cache.get(key, not_in_cache) + + def set(self, key, value): + cache[key] = value + while len(cache) > size: + try: + cache.popitem(False) + except KeyError: + pass + + def clear(self): + cache.clear() + + def cache_len(self): + return len(cache) + + self.get = types.MethodType(get, self) + self.set = types.MethodType(set, self) + self.clear = types.MethodType(clear, self) + self.__len__ = types.MethodType(cache_len, self) + + else: + class _FifoCache(object): + def __init__(self, size): + self.not_in_cache = not_in_cache = object() + + cache = {} + key_fifo = collections.deque([], size) + + def get(self, key): + return cache.get(key, not_in_cache) + + def set(self, key, value): + cache[key] = value + while len(key_fifo) > size: + cache.pop(key_fifo.popleft(), None) + key_fifo.append(key) + + def clear(self): + cache.clear() + key_fifo.clear() + + def cache_len(self): + return len(cache) + + self.get = types.MethodType(get, self) + self.set = types.MethodType(set, self) + self.clear = types.MethodType(clear, self) + self.__len__ = types.MethodType(cache_len, self) + + # argument cache for optimizing repeated calls when backtracking through recursive expressions + packrat_cache = {} # this is set later by enabledPackrat(); this is here so that resetCache() doesn't fail + packrat_cache_lock = RLock() + packrat_cache_stats = [0, 0] + + # this method gets repeatedly called during backtracking with the same arguments - + # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression + def _parseCache( self, instring, loc, doActions=True, callPreParse=True ): + HIT, MISS = 0, 1 + lookup = (self, instring, loc, callPreParse, doActions) + with ParserElement.packrat_cache_lock: + cache = ParserElement.packrat_cache + value = cache.get(lookup) + if value is cache.not_in_cache: + ParserElement.packrat_cache_stats[MISS] += 1 + try: + value = self._parseNoCache(instring, loc, doActions, callPreParse) + except ParseBaseException as pe: + # cache a copy of the exception, without the traceback + cache.set(lookup, pe.__class__(*pe.args)) + raise + else: + cache.set(lookup, (value[0], value[1].copy())) + return value + else: + ParserElement.packrat_cache_stats[HIT] += 1 + if isinstance(value, Exception): + raise value + return (value[0], value[1].copy()) + + _parse = _parseNoCache + + @staticmethod + def resetCache(): + ParserElement.packrat_cache.clear() + ParserElement.packrat_cache_stats[:] = [0] * len(ParserElement.packrat_cache_stats) + + _packratEnabled = False + @staticmethod + def enablePackrat(cache_size_limit=128): + """Enables "packrat" parsing, which adds memoizing to the parsing logic. + Repeated parse attempts at the same string location (which happens + often in many complex grammars) can immediately return a cached value, + instead of re-executing parsing/validating code. Memoizing is done of + both valid results and parsing exceptions. + + Parameters: + - cache_size_limit - (default=C{128}) - if an integer value is provided + will limit the size of the packrat cache; if None is passed, then + the cache size will be unbounded; if 0 is passed, the cache will + be effectively disabled. + + This speedup may break existing programs that use parse actions that + have side-effects. For this reason, packrat parsing is disabled when + you first import pyparsing. To activate the packrat feature, your + program must call the class method C{ParserElement.enablePackrat()}. If + your program uses C{psyco} to "compile as you go", you must call + C{enablePackrat} before calling C{psyco.full()}. If you do not do this, + Python will crash. For best results, call C{enablePackrat()} immediately + after importing pyparsing. + + Example:: + import pyparsing + pyparsing.ParserElement.enablePackrat() + """ + if not ParserElement._packratEnabled: + ParserElement._packratEnabled = True + if cache_size_limit is None: + ParserElement.packrat_cache = ParserElement._UnboundedCache() + else: + ParserElement.packrat_cache = ParserElement._FifoCache(cache_size_limit) + ParserElement._parse = ParserElement._parseCache + + def parseString( self, instring, parseAll=False ): + """ + Execute the parse expression with the given string. + This is the main interface to the client code, once the complete + expression has been built. + + If you want the grammar to require that the entire input string be + successfully parsed, then set C{parseAll} to True (equivalent to ending + the grammar with C{L{StringEnd()}}). + + Note: C{parseString} implicitly calls C{expandtabs()} on the input string, + in order to report proper column numbers in parse actions. + If the input string contains tabs and + the grammar uses parse actions that use the C{loc} argument to index into the + string being parsed, you can ensure you have a consistent view of the input + string by: + - calling C{parseWithTabs} on your grammar before calling C{parseString} + (see L{I{parseWithTabs}}) + - define your parse action using the full C{(s,loc,toks)} signature, and + reference the input string using the parse action's C{s} argument + - explictly expand the tabs in your input string before calling + C{parseString} + + Example:: + Word('a').parseString('aaaaabaaa') # -> ['aaaaa'] + Word('a').parseString('aaaaabaaa', parseAll=True) # -> Exception: Expected end of text + """ + ParserElement.resetCache() + if not self.streamlined: + self.streamline() + #~ self.saveAsList = True + for e in self.ignoreExprs: + e.streamline() + if not self.keepTabs: + instring = instring.expandtabs() + try: + loc, tokens = self._parse( instring, 0 ) + if parseAll: + loc = self.preParse( instring, loc ) + se = Empty() + StringEnd() + se._parse( instring, loc ) + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + else: + # catch and re-raise exception from here, clears out pyparsing internal stack trace + raise exc + else: + return tokens + + def scanString( self, instring, maxMatches=_MAX_INT, overlap=False ): + """ + Scan the input string for expression matches. Each match will return the + matching tokens, start location, and end location. May be called with optional + C{maxMatches} argument, to clip scanning after 'n' matches are found. If + C{overlap} is specified, then overlapping matches will be reported. + + Note that the start and end locations are reported relative to the string + being parsed. See L{I{parseString}} for more information on parsing + strings with embedded tabs. + + Example:: + source = "sldjf123lsdjjkf345sldkjf879lkjsfd987" + print(source) + for tokens,start,end in Word(alphas).scanString(source): + print(' '*start + '^'*(end-start)) + print(' '*start + tokens[0]) + + prints:: + + sldjf123lsdjjkf345sldkjf879lkjsfd987 + ^^^^^ + sldjf + ^^^^^^^ + lsdjjkf + ^^^^^^ + sldkjf + ^^^^^^ + lkjsfd + """ + if not self.streamlined: + self.streamline() + for e in self.ignoreExprs: + e.streamline() + + if not self.keepTabs: + instring = _ustr(instring).expandtabs() + instrlen = len(instring) + loc = 0 + preparseFn = self.preParse + parseFn = self._parse + ParserElement.resetCache() + matches = 0 + try: + while loc <= instrlen and matches < maxMatches: + try: + preloc = preparseFn( instring, loc ) + nextLoc,tokens = parseFn( instring, preloc, callPreParse=False ) + except ParseException: + loc = preloc+1 + else: + if nextLoc > loc: + matches += 1 + yield tokens, preloc, nextLoc + if overlap: + nextloc = preparseFn( instring, loc ) + if nextloc > loc: + loc = nextLoc + else: + loc += 1 + else: + loc = nextLoc + else: + loc = preloc+1 + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + else: + # catch and re-raise exception from here, clears out pyparsing internal stack trace + raise exc + + def transformString( self, instring ): + """ + Extension to C{L{scanString}}, to modify matching text with modified tokens that may + be returned from a parse action. To use C{transformString}, define a grammar and + attach a parse action to it that modifies the returned token list. + Invoking C{transformString()} on a target string will then scan for matches, + and replace the matched text patterns according to the logic in the parse + action. C{transformString()} returns the resulting transformed string. + + Example:: + wd = Word(alphas) + wd.setParseAction(lambda toks: toks[0].title()) + + print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york.")) + Prints:: + Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York. + """ + out = [] + lastE = 0 + # force preservation of s, to minimize unwanted transformation of string, and to + # keep string locs straight between transformString and scanString + self.keepTabs = True + try: + for t,s,e in self.scanString( instring ): + out.append( instring[lastE:s] ) + if t: + if isinstance(t,ParseResults): + out += t.asList() + elif isinstance(t,list): + out += t + else: + out.append(t) + lastE = e + out.append(instring[lastE:]) + out = [o for o in out if o] + return "".join(map(_ustr,_flatten(out))) + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + else: + # catch and re-raise exception from here, clears out pyparsing internal stack trace + raise exc + + def searchString( self, instring, maxMatches=_MAX_INT ): + """ + Another extension to C{L{scanString}}, simplifying the access to the tokens found + to match the given parse expression. May be called with optional + C{maxMatches} argument, to clip searching after 'n' matches are found. + + Example:: + # a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters + cap_word = Word(alphas.upper(), alphas.lower()) + + print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity")) + + # the sum() builtin can be used to merge results into a single ParseResults object + print(sum(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity"))) + prints:: + [['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']] + ['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity'] + """ + try: + return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ]) + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + else: + # catch and re-raise exception from here, clears out pyparsing internal stack trace + raise exc + + def split(self, instring, maxsplit=_MAX_INT, includeSeparators=False): + """ + Generator method to split a string using the given expression as a separator. + May be called with optional C{maxsplit} argument, to limit the number of splits; + and the optional C{includeSeparators} argument (default=C{False}), if the separating + matching text should be included in the split results. + + Example:: + punc = oneOf(list(".,;:/-!?")) + print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) + prints:: + ['This', ' this', '', ' this sentence', ' is badly punctuated', ''] + """ + splits = 0 + last = 0 + for t,s,e in self.scanString(instring, maxMatches=maxsplit): + yield instring[last:s] + if includeSeparators: + yield t[0] + last = e + yield instring[last:] + + def __add__(self, other ): + """ + Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement + converts them to L{Literal}s by default. + + Example:: + greet = Word(alphas) + "," + Word(alphas) + "!" + hello = "Hello, World!" + print (hello, "->", greet.parseString(hello)) + Prints:: + Hello, World! -> ['Hello', ',', 'World', '!'] + """ + if isinstance( other, basestring ): + other = ParserElement._literalStringClass( other ) + if not isinstance( other, ParserElement ): + warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), + SyntaxWarning, stacklevel=2) + return None + return And( [ self, other ] ) + + def __radd__(self, other ): + """ + Implementation of + operator when left operand is not a C{L{ParserElement}} + """ + if isinstance( other, basestring ): + other = ParserElement._literalStringClass( other ) + if not isinstance( other, ParserElement ): + warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), + SyntaxWarning, stacklevel=2) + return None + return other + self + + def __sub__(self, other): + """ + Implementation of - operator, returns C{L{And}} with error stop + """ + if isinstance( other, basestring ): + other = ParserElement._literalStringClass( other ) + if not isinstance( other, ParserElement ): + warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), + SyntaxWarning, stacklevel=2) + return None + return self + And._ErrorStop() + other + + def __rsub__(self, other ): + """ + Implementation of - operator when left operand is not a C{L{ParserElement}} + """ + if isinstance( other, basestring ): + other = ParserElement._literalStringClass( other ) + if not isinstance( other, ParserElement ): + warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), + SyntaxWarning, stacklevel=2) + return None + return other - self + + def __mul__(self,other): + """ + Implementation of * operator, allows use of C{expr * 3} in place of + C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer + tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples + may also include C{None} as in: + - C{expr*(n,None)} or C{expr*(n,)} is equivalent + to C{expr*n + L{ZeroOrMore}(expr)} + (read as "at least n instances of C{expr}") + - C{expr*(None,n)} is equivalent to C{expr*(0,n)} + (read as "0 to n instances of C{expr}") + - C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)} + - C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)} + + Note that C{expr*(None,n)} does not raise an exception if + more than n exprs exist in the input stream; that is, + C{expr*(None,n)} does not enforce a maximum number of expr + occurrences. If this behavior is desired, then write + C{expr*(None,n) + ~expr} + """ + if isinstance(other,int): + minElements, optElements = other,0 + elif isinstance(other,tuple): + other = (other + (None, None))[:2] + if other[0] is None: + other = (0, other[1]) + if isinstance(other[0],int) and other[1] is None: + if other[0] == 0: + return ZeroOrMore(self) + if other[0] == 1: + return OneOrMore(self) + else: + return self*other[0] + ZeroOrMore(self) + elif isinstance(other[0],int) and isinstance(other[1],int): + minElements, optElements = other + optElements -= minElements + else: + raise TypeError("cannot multiply 'ParserElement' and ('%s','%s') objects", type(other[0]),type(other[1])) + else: + raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other)) + + if minElements < 0: + raise ValueError("cannot multiply ParserElement by negative value") + if optElements < 0: + raise ValueError("second tuple value must be greater or equal to first tuple value") + if minElements == optElements == 0: + raise ValueError("cannot multiply ParserElement by 0 or (0,0)") + + if (optElements): + def makeOptionalList(n): + if n>1: + return Optional(self + makeOptionalList(n-1)) + else: + return Optional(self) + if minElements: + if minElements == 1: + ret = self + makeOptionalList(optElements) + else: + ret = And([self]*minElements) + makeOptionalList(optElements) + else: + ret = makeOptionalList(optElements) + else: + if minElements == 1: + ret = self + else: + ret = And([self]*minElements) + return ret + + def __rmul__(self, other): + return self.__mul__(other) + + def __or__(self, other ): + """ + Implementation of | operator - returns C{L{MatchFirst}} + """ + if isinstance( other, basestring ): + other = ParserElement._literalStringClass( other ) + if not isinstance( other, ParserElement ): + warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), + SyntaxWarning, stacklevel=2) + return None + return MatchFirst( [ self, other ] ) + + def __ror__(self, other ): + """ + Implementation of | operator when left operand is not a C{L{ParserElement}} + """ + if isinstance( other, basestring ): + other = ParserElement._literalStringClass( other ) + if not isinstance( other, ParserElement ): + warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), + SyntaxWarning, stacklevel=2) + return None + return other | self + + def __xor__(self, other ): + """ + Implementation of ^ operator - returns C{L{Or}} + """ + if isinstance( other, basestring ): + other = ParserElement._literalStringClass( other ) + if not isinstance( other, ParserElement ): + warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), + SyntaxWarning, stacklevel=2) + return None + return Or( [ self, other ] ) + + def __rxor__(self, other ): + """ + Implementation of ^ operator when left operand is not a C{L{ParserElement}} + """ + if isinstance( other, basestring ): + other = ParserElement._literalStringClass( other ) + if not isinstance( other, ParserElement ): + warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), + SyntaxWarning, stacklevel=2) + return None + return other ^ self + + def __and__(self, other ): + """ + Implementation of & operator - returns C{L{Each}} + """ + if isinstance( other, basestring ): + other = ParserElement._literalStringClass( other ) + if not isinstance( other, ParserElement ): + warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), + SyntaxWarning, stacklevel=2) + return None + return Each( [ self, other ] ) + + def __rand__(self, other ): + """ + Implementation of & operator when left operand is not a C{L{ParserElement}} + """ + if isinstance( other, basestring ): + other = ParserElement._literalStringClass( other ) + if not isinstance( other, ParserElement ): + warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), + SyntaxWarning, stacklevel=2) + return None + return other & self + + def __invert__( self ): + """ + Implementation of ~ operator - returns C{L{NotAny}} + """ + return NotAny( self ) + + def __call__(self, name=None): + """ + Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}. + + If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be + passed as C{True}. + + If C{name} is omitted, same as calling C{L{copy}}. + + Example:: + # these are equivalent + userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno") + userdata = Word(alphas)("name") + Word(nums+"-")("socsecno") + """ + if name is not None: + return self.setResultsName(name) + else: + return self.copy() + + def suppress( self ): + """ + Suppresses the output of this C{ParserElement}; useful to keep punctuation from + cluttering up returned output. + """ + return Suppress( self ) + + def leaveWhitespace( self ): + """ + Disables the skipping of whitespace before matching the characters in the + C{ParserElement}'s defined pattern. This is normally only used internally by + the pyparsing module, but may be needed in some whitespace-sensitive grammars. + """ + self.skipWhitespace = False + return self + + def setWhitespaceChars( self, chars ): + """ + Overrides the default whitespace chars + """ + self.skipWhitespace = True + self.whiteChars = chars + self.copyDefaultWhiteChars = False + return self + + def parseWithTabs( self ): + """ + Overrides default behavior to expand C{}s to spaces before parsing the input string. + Must be called before C{parseString} when the input grammar contains elements that + match C{} characters. + """ + self.keepTabs = True + return self + + def ignore( self, other ): + """ + Define expression to be ignored (e.g., comments) while doing pattern + matching; may be called repeatedly, to define multiple comment or other + ignorable patterns. + + Example:: + patt = OneOrMore(Word(alphas)) + patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj'] + + patt.ignore(cStyleComment) + patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd'] + """ + if isinstance(other, basestring): + other = Suppress(other) + + if isinstance( other, Suppress ): + if other not in self.ignoreExprs: + self.ignoreExprs.append(other) + else: + self.ignoreExprs.append( Suppress( other.copy() ) ) + return self + + def setDebugActions( self, startAction, successAction, exceptionAction ): + """ + Enable display of debugging messages while doing pattern matching. + """ + self.debugActions = (startAction or _defaultStartDebugAction, + successAction or _defaultSuccessDebugAction, + exceptionAction or _defaultExceptionDebugAction) + self.debug = True + return self + + def setDebug( self, flag=True ): + """ + Enable display of debugging messages while doing pattern matching. + Set C{flag} to True to enable, False to disable. + + Example:: + wd = Word(alphas).setName("alphaword") + integer = Word(nums).setName("numword") + term = wd | integer + + # turn on debugging for wd + wd.setDebug() + + OneOrMore(term).parseString("abc 123 xyz 890") + + prints:: + Match alphaword at loc 0(1,1) + Matched alphaword -> ['abc'] + Match alphaword at loc 3(1,4) + Exception raised:Expected alphaword (at char 4), (line:1, col:5) + Match alphaword at loc 7(1,8) + Matched alphaword -> ['xyz'] + Match alphaword at loc 11(1,12) + Exception raised:Expected alphaword (at char 12), (line:1, col:13) + Match alphaword at loc 15(1,16) + Exception raised:Expected alphaword (at char 15), (line:1, col:16) + + The output shown is that produced by the default debug actions - custom debug actions can be + specified using L{setDebugActions}. Prior to attempting + to match the C{wd} expression, the debugging message C{"Match at loc (,)"} + is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"} + message is shown. Also note the use of L{setName} to assign a human-readable name to the expression, + which makes debugging and exception messages easier to understand - for instance, the default + name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}. + """ + if flag: + self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction ) + else: + self.debug = False + return self + + def __str__( self ): + return self.name + + def __repr__( self ): + return _ustr(self) + + def streamline( self ): + self.streamlined = True + self.strRepr = None + return self + + def checkRecursion( self, parseElementList ): + pass + + def validate( self, validateTrace=[] ): + """ + Check defined expressions for valid structure, check for infinite recursive definitions. + """ + self.checkRecursion( [] ) + + def parseFile( self, file_or_filename, parseAll=False ): + """ + Execute the parse expression on the given file or filename. + If a filename is specified (instead of a file object), + the entire file is opened, read, and closed before parsing. + """ + try: + file_contents = file_or_filename.read() + except AttributeError: + with open(file_or_filename, "r") as f: + file_contents = f.read() + try: + return self.parseString(file_contents, parseAll) + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + else: + # catch and re-raise exception from here, clears out pyparsing internal stack trace + raise exc + + def __eq__(self,other): + if isinstance(other, ParserElement): + return self is other or vars(self) == vars(other) + elif isinstance(other, basestring): + return self.matches(other) + else: + return super(ParserElement,self)==other + + def __ne__(self,other): + return not (self == other) + + def __hash__(self): + return hash(id(self)) + + def __req__(self,other): + return self == other + + def __rne__(self,other): + return not (self == other) + + def matches(self, testString, parseAll=True): + """ + Method for quick testing of a parser against a test string. Good for simple + inline microtests of sub expressions while building up larger parser. + + Parameters: + - testString - to test against this expression for a match + - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests + + Example:: + expr = Word(nums) + assert expr.matches("100") + """ + try: + self.parseString(_ustr(testString), parseAll=parseAll) + return True + except ParseBaseException: + return False + + def runTests(self, tests, parseAll=True, comment='#', fullDump=True, printResults=True, failureTests=False): + """ + Execute the parse expression on a series of test strings, showing each + test, the parsed results or where the parse failed. Quick and easy way to + run a parse expression against a list of sample strings. + + Parameters: + - tests - a list of separate test strings, or a multiline string of test strings + - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests + - comment - (default=C{'#'}) - expression for indicating embedded comments in the test + string; pass None to disable comment filtering + - fullDump - (default=C{True}) - dump results as list followed by results names in nested outline; + if False, only dump nested list + - printResults - (default=C{True}) prints test output to stdout + - failureTests - (default=C{False}) indicates if these tests are expected to fail parsing + + Returns: a (success, results) tuple, where success indicates that all tests succeeded + (or failed if C{failureTests} is True), and the results contain a list of lines of each + test's output + + Example:: + number_expr = pyparsing_common.number.copy() + + result = number_expr.runTests(''' + # unsigned integer + 100 + # negative integer + -100 + # float with scientific notation + 6.02e23 + # integer with scientific notation + 1e-12 + ''') + print("Success" if result[0] else "Failed!") + + result = number_expr.runTests(''' + # stray character + 100Z + # missing leading digit before '.' + -.100 + # too many '.' + 3.14.159 + ''', failureTests=True) + print("Success" if result[0] else "Failed!") + prints:: + # unsigned integer + 100 + [100] + + # negative integer + -100 + [-100] + + # float with scientific notation + 6.02e23 + [6.02e+23] + + # integer with scientific notation + 1e-12 + [1e-12] + + Success + + # stray character + 100Z + ^ + FAIL: Expected end of text (at char 3), (line:1, col:4) + + # missing leading digit before '.' + -.100 + ^ + FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1) + + # too many '.' + 3.14.159 + ^ + FAIL: Expected end of text (at char 4), (line:1, col:5) + + Success + + Each test string must be on a single line. If you want to test a string that spans multiple + lines, create a test like this:: + + expr.runTest(r"this is a test\\n of strings that spans \\n 3 lines") + + (Note that this is a raw string literal, you must include the leading 'r'.) + """ + if isinstance(tests, basestring): + tests = list(map(str.strip, tests.rstrip().splitlines())) + if isinstance(comment, basestring): + comment = Literal(comment) + allResults = [] + comments = [] + success = True + for t in tests: + if comment is not None and comment.matches(t, False) or comments and not t: + comments.append(t) + continue + if not t: + continue + out = ['\n'.join(comments), t] + comments = [] + try: + t = t.replace(r'\n','\n') + result = self.parseString(t, parseAll=parseAll) + out.append(result.dump(full=fullDump)) + success = success and not failureTests + except ParseBaseException as pe: + fatal = "(FATAL)" if isinstance(pe, ParseFatalException) else "" + if '\n' in t: + out.append(line(pe.loc, t)) + out.append(' '*(col(pe.loc,t)-1) + '^' + fatal) + else: + out.append(' '*pe.loc + '^' + fatal) + out.append("FAIL: " + str(pe)) + success = success and failureTests + result = pe + except Exception as exc: + out.append("FAIL-EXCEPTION: " + str(exc)) + success = success and failureTests + result = exc + + if printResults: + if fullDump: + out.append('') + print('\n'.join(out)) + + allResults.append((t, result)) + + return success, allResults + + +class Token(ParserElement): + """ + Abstract C{ParserElement} subclass, for defining atomic matching patterns. + """ + def __init__( self ): + super(Token,self).__init__( savelist=False ) + + +class Empty(Token): + """ + An empty token, will always match. + """ + def __init__( self ): + super(Empty,self).__init__() + self.name = "Empty" + self.mayReturnEmpty = True + self.mayIndexError = False + + +class NoMatch(Token): + """ + A token that will never match. + """ + def __init__( self ): + super(NoMatch,self).__init__() + self.name = "NoMatch" + self.mayReturnEmpty = True + self.mayIndexError = False + self.errmsg = "Unmatchable token" + + def parseImpl( self, instring, loc, doActions=True ): + raise ParseException(instring, loc, self.errmsg, self) + + +class Literal(Token): + """ + Token to exactly match a specified string. + + Example:: + Literal('blah').parseString('blah') # -> ['blah'] + Literal('blah').parseString('blahfooblah') # -> ['blah'] + Literal('blah').parseString('bla') # -> Exception: Expected "blah" + + For case-insensitive matching, use L{CaselessLiteral}. + + For keyword matching (force word break before and after the matched string), + use L{Keyword} or L{CaselessKeyword}. + """ + def __init__( self, matchString ): + super(Literal,self).__init__() + self.match = matchString + self.matchLen = len(matchString) + try: + self.firstMatchChar = matchString[0] + except IndexError: + warnings.warn("null string passed to Literal; use Empty() instead", + SyntaxWarning, stacklevel=2) + self.__class__ = Empty + self.name = '"%s"' % _ustr(self.match) + self.errmsg = "Expected " + self.name + self.mayReturnEmpty = False + self.mayIndexError = False + + # Performance tuning: this routine gets called a *lot* + # if this is a single character match string and the first character matches, + # short-circuit as quickly as possible, and avoid calling startswith + #~ @profile + def parseImpl( self, instring, loc, doActions=True ): + if (instring[loc] == self.firstMatchChar and + (self.matchLen==1 or instring.startswith(self.match,loc)) ): + return loc+self.matchLen, self.match + raise ParseException(instring, loc, self.errmsg, self) +_L = Literal +ParserElement._literalStringClass = Literal + +class Keyword(Token): + """ + Token to exactly match a specified string as a keyword, that is, it must be + immediately followed by a non-keyword character. Compare with C{L{Literal}}: + - C{Literal("if")} will match the leading C{'if'} in C{'ifAndOnlyIf'}. + - C{Keyword("if")} will not; it will only match the leading C{'if'} in C{'if x=1'}, or C{'if(y==2)'} + Accepts two optional constructor arguments in addition to the keyword string: + - C{identChars} is a string of characters that would be valid identifier characters, + defaulting to all alphanumerics + "_" and "$" + - C{caseless} allows case-insensitive matching, default is C{False}. + + Example:: + Keyword("start").parseString("start") # -> ['start'] + Keyword("start").parseString("starting") # -> Exception + + For case-insensitive matching, use L{CaselessKeyword}. + """ + DEFAULT_KEYWORD_CHARS = alphanums+"_$" + + def __init__( self, matchString, identChars=None, caseless=False ): + super(Keyword,self).__init__() + if identChars is None: + identChars = Keyword.DEFAULT_KEYWORD_CHARS + self.match = matchString + self.matchLen = len(matchString) + try: + self.firstMatchChar = matchString[0] + except IndexError: + warnings.warn("null string passed to Keyword; use Empty() instead", + SyntaxWarning, stacklevel=2) + self.name = '"%s"' % self.match + self.errmsg = "Expected " + self.name + self.mayReturnEmpty = False + self.mayIndexError = False + self.caseless = caseless + if caseless: + self.caselessmatch = matchString.upper() + identChars = identChars.upper() + self.identChars = set(identChars) + + def parseImpl( self, instring, loc, doActions=True ): + if self.caseless: + if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and + (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) and + (loc == 0 or instring[loc-1].upper() not in self.identChars) ): + return loc+self.matchLen, self.match + else: + if (instring[loc] == self.firstMatchChar and + (self.matchLen==1 or instring.startswith(self.match,loc)) and + (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen] not in self.identChars) and + (loc == 0 or instring[loc-1] not in self.identChars) ): + return loc+self.matchLen, self.match + raise ParseException(instring, loc, self.errmsg, self) + + def copy(self): + c = super(Keyword,self).copy() + c.identChars = Keyword.DEFAULT_KEYWORD_CHARS + return c + + @staticmethod + def setDefaultKeywordChars( chars ): + """Overrides the default Keyword chars + """ + Keyword.DEFAULT_KEYWORD_CHARS = chars + +class CaselessLiteral(Literal): + """ + Token to match a specified string, ignoring case of letters. + Note: the matched results will always be in the case of the given + match string, NOT the case of the input text. + + Example:: + OneOrMore(CaselessLiteral("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD', 'CMD'] + + (Contrast with example for L{CaselessKeyword}.) + """ + def __init__( self, matchString ): + super(CaselessLiteral,self).__init__( matchString.upper() ) + # Preserve the defining literal. + self.returnString = matchString + self.name = "'%s'" % self.returnString + self.errmsg = "Expected " + self.name + + def parseImpl( self, instring, loc, doActions=True ): + if instring[ loc:loc+self.matchLen ].upper() == self.match: + return loc+self.matchLen, self.returnString + raise ParseException(instring, loc, self.errmsg, self) + +class CaselessKeyword(Keyword): + """ + Caseless version of L{Keyword}. + + Example:: + OneOrMore(CaselessKeyword("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD'] + + (Contrast with example for L{CaselessLiteral}.) + """ + def __init__( self, matchString, identChars=None ): + super(CaselessKeyword,self).__init__( matchString, identChars, caseless=True ) + + def parseImpl( self, instring, loc, doActions=True ): + if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and + (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) ): + return loc+self.matchLen, self.match + raise ParseException(instring, loc, self.errmsg, self) + +class CloseMatch(Token): + """ + A variation on L{Literal} which matches "close" matches, that is, + strings with at most 'n' mismatching characters. C{CloseMatch} takes parameters: + - C{match_string} - string to be matched + - C{maxMismatches} - (C{default=1}) maximum number of mismatches allowed to count as a match + + The results from a successful parse will contain the matched text from the input string and the following named results: + - C{mismatches} - a list of the positions within the match_string where mismatches were found + - C{original} - the original match_string used to compare against the input string + + If C{mismatches} is an empty list, then the match was an exact match. + + Example:: + patt = CloseMatch("ATCATCGAATGGA") + patt.parseString("ATCATCGAAXGGA") # -> (['ATCATCGAAXGGA'], {'mismatches': [[9]], 'original': ['ATCATCGAATGGA']}) + patt.parseString("ATCAXCGAAXGGA") # -> Exception: Expected 'ATCATCGAATGGA' (with up to 1 mismatches) (at char 0), (line:1, col:1) + + # exact match + patt.parseString("ATCATCGAATGGA") # -> (['ATCATCGAATGGA'], {'mismatches': [[]], 'original': ['ATCATCGAATGGA']}) + + # close match allowing up to 2 mismatches + patt = CloseMatch("ATCATCGAATGGA", maxMismatches=2) + patt.parseString("ATCAXCGAAXGGA") # -> (['ATCAXCGAAXGGA'], {'mismatches': [[4, 9]], 'original': ['ATCATCGAATGGA']}) + """ + def __init__(self, match_string, maxMismatches=1): + super(CloseMatch,self).__init__() + self.name = match_string + self.match_string = match_string + self.maxMismatches = maxMismatches + self.errmsg = "Expected %r (with up to %d mismatches)" % (self.match_string, self.maxMismatches) + self.mayIndexError = False + self.mayReturnEmpty = False + + def parseImpl( self, instring, loc, doActions=True ): + start = loc + instrlen = len(instring) + maxloc = start + len(self.match_string) + + if maxloc <= instrlen: + match_string = self.match_string + match_stringloc = 0 + mismatches = [] + maxMismatches = self.maxMismatches + + for match_stringloc,s_m in enumerate(zip(instring[loc:maxloc], self.match_string)): + src,mat = s_m + if src != mat: + mismatches.append(match_stringloc) + if len(mismatches) > maxMismatches: + break + else: + loc = match_stringloc + 1 + results = ParseResults([instring[start:loc]]) + results['original'] = self.match_string + results['mismatches'] = mismatches + return loc, results + + raise ParseException(instring, loc, self.errmsg, self) + + +class Word(Token): + """ + Token for matching words composed of allowed character sets. + Defined with string containing all allowed initial characters, + an optional string containing allowed body characters (if omitted, + defaults to the initial character set), and an optional minimum, + maximum, and/or exact length. The default value for C{min} is 1 (a + minimum value < 1 is not valid); the default values for C{max} and C{exact} + are 0, meaning no maximum or exact length restriction. An optional + C{excludeChars} parameter can list characters that might be found in + the input C{bodyChars} string; useful to define a word of all printables + except for one or two characters, for instance. + + L{srange} is useful for defining custom character set strings for defining + C{Word} expressions, using range notation from regular expression character sets. + + A common mistake is to use C{Word} to match a specific literal string, as in + C{Word("Address")}. Remember that C{Word} uses the string argument to define + I{sets} of matchable characters. This expression would match "Add", "AAA", + "dAred", or any other word made up of the characters 'A', 'd', 'r', 'e', and 's'. + To match an exact literal string, use L{Literal} or L{Keyword}. + + pyparsing includes helper strings for building Words: + - L{alphas} + - L{nums} + - L{alphanums} + - L{hexnums} + - L{alphas8bit} (alphabetic characters in ASCII range 128-255 - accented, tilded, umlauted, etc.) + - L{punc8bit} (non-alphabetic characters in ASCII range 128-255 - currency, symbols, superscripts, diacriticals, etc.) + - L{printables} (any non-whitespace character) + + Example:: + # a word composed of digits + integer = Word(nums) # equivalent to Word("0123456789") or Word(srange("0-9")) + + # a word with a leading capital, and zero or more lowercase + capital_word = Word(alphas.upper(), alphas.lower()) + + # hostnames are alphanumeric, with leading alpha, and '-' + hostname = Word(alphas, alphanums+'-') + + # roman numeral (not a strict parser, accepts invalid mix of characters) + roman = Word("IVXLCDM") + + # any string of non-whitespace characters, except for ',' + csv_value = Word(printables, excludeChars=",") + """ + def __init__( self, initChars, bodyChars=None, min=1, max=0, exact=0, asKeyword=False, excludeChars=None ): + super(Word,self).__init__() + if excludeChars: + initChars = ''.join(c for c in initChars if c not in excludeChars) + if bodyChars: + bodyChars = ''.join(c for c in bodyChars if c not in excludeChars) + self.initCharsOrig = initChars + self.initChars = set(initChars) + if bodyChars : + self.bodyCharsOrig = bodyChars + self.bodyChars = set(bodyChars) + else: + self.bodyCharsOrig = initChars + self.bodyChars = set(initChars) + + self.maxSpecified = max > 0 + + if min < 1: + raise ValueError("cannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permitted") + + self.minLen = min + + if max > 0: + self.maxLen = max + else: + self.maxLen = _MAX_INT + + if exact > 0: + self.maxLen = exact + self.minLen = exact + + self.name = _ustr(self) + self.errmsg = "Expected " + self.name + self.mayIndexError = False + self.asKeyword = asKeyword + + if ' ' not in self.initCharsOrig+self.bodyCharsOrig and (min==1 and max==0 and exact==0): + if self.bodyCharsOrig == self.initCharsOrig: + self.reString = "[%s]+" % _escapeRegexRangeChars(self.initCharsOrig) + elif len(self.initCharsOrig) == 1: + self.reString = "%s[%s]*" % \ + (re.escape(self.initCharsOrig), + _escapeRegexRangeChars(self.bodyCharsOrig),) + else: + self.reString = "[%s][%s]*" % \ + (_escapeRegexRangeChars(self.initCharsOrig), + _escapeRegexRangeChars(self.bodyCharsOrig),) + if self.asKeyword: + self.reString = r"\b"+self.reString+r"\b" + try: + self.re = re.compile( self.reString ) + except Exception: + self.re = None + + def parseImpl( self, instring, loc, doActions=True ): + if self.re: + result = self.re.match(instring,loc) + if not result: + raise ParseException(instring, loc, self.errmsg, self) + + loc = result.end() + return loc, result.group() + + if not(instring[ loc ] in self.initChars): + raise ParseException(instring, loc, self.errmsg, self) + + start = loc + loc += 1 + instrlen = len(instring) + bodychars = self.bodyChars + maxloc = start + self.maxLen + maxloc = min( maxloc, instrlen ) + while loc < maxloc and instring[loc] in bodychars: + loc += 1 + + throwException = False + if loc - start < self.minLen: + throwException = True + if self.maxSpecified and loc < instrlen and instring[loc] in bodychars: + throwException = True + if self.asKeyword: + if (start>0 and instring[start-1] in bodychars) or (loc4: + return s[:4]+"..." + else: + return s + + if ( self.initCharsOrig != self.bodyCharsOrig ): + self.strRepr = "W:(%s,%s)" % ( charsAsStr(self.initCharsOrig), charsAsStr(self.bodyCharsOrig) ) + else: + self.strRepr = "W:(%s)" % charsAsStr(self.initCharsOrig) + + return self.strRepr + + +class Regex(Token): + r""" + Token for matching strings that match a given regular expression. + Defined with string specifying the regular expression in a form recognized by the inbuilt Python re module. + If the given regex contains named groups (defined using C{(?P...)}), these will be preserved as + named parse results. + + Example:: + realnum = Regex(r"[+-]?\d+\.\d*") + date = Regex(r'(?P\d{4})-(?P\d\d?)-(?P\d\d?)') + # ref: http://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression + roman = Regex(r"M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})") + """ + compiledREtype = type(re.compile("[A-Z]")) + def __init__( self, pattern, flags=0): + """The parameters C{pattern} and C{flags} are passed to the C{re.compile()} function as-is. See the Python C{re} module for an explanation of the acceptable patterns and flags.""" + super(Regex,self).__init__() + + if isinstance(pattern, basestring): + if not pattern: + warnings.warn("null string passed to Regex; use Empty() instead", + SyntaxWarning, stacklevel=2) + + self.pattern = pattern + self.flags = flags + + try: + self.re = re.compile(self.pattern, self.flags) + self.reString = self.pattern + except sre_constants.error: + warnings.warn("invalid pattern (%s) passed to Regex" % pattern, + SyntaxWarning, stacklevel=2) + raise + + elif isinstance(pattern, Regex.compiledREtype): + self.re = pattern + self.pattern = \ + self.reString = str(pattern) + self.flags = flags + + else: + raise ValueError("Regex may only be constructed with a string or a compiled RE object") + + self.name = _ustr(self) + self.errmsg = "Expected " + self.name + self.mayIndexError = False + self.mayReturnEmpty = True + + def parseImpl( self, instring, loc, doActions=True ): + result = self.re.match(instring,loc) + if not result: + raise ParseException(instring, loc, self.errmsg, self) + + loc = result.end() + d = result.groupdict() + ret = ParseResults(result.group()) + if d: + for k in d: + ret[k] = d[k] + return loc,ret + + def __str__( self ): + try: + return super(Regex,self).__str__() + except Exception: + pass + + if self.strRepr is None: + self.strRepr = "Re:(%s)" % repr(self.pattern) + + return self.strRepr + + +class QuotedString(Token): + r""" + Token for matching strings that are delimited by quoting characters. + + Defined with the following parameters: + - quoteChar - string of one or more characters defining the quote delimiting string + - escChar - character to escape quotes, typically backslash (default=C{None}) + - escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=C{None}) + - multiline - boolean indicating whether quotes can span multiple lines (default=C{False}) + - unquoteResults - boolean indicating whether the matched text should be unquoted (default=C{True}) + - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=C{None} => same as quoteChar) + - convertWhitespaceEscapes - convert escaped whitespace (C{'\t'}, C{'\n'}, etc.) to actual whitespace (default=C{True}) + + Example:: + qs = QuotedString('"') + print(qs.searchString('lsjdf "This is the quote" sldjf')) + complex_qs = QuotedString('{{', endQuoteChar='}}') + print(complex_qs.searchString('lsjdf {{This is the "quote"}} sldjf')) + sql_qs = QuotedString('"', escQuote='""') + print(sql_qs.searchString('lsjdf "This is the quote with ""embedded"" quotes" sldjf')) + prints:: + [['This is the quote']] + [['This is the "quote"']] + [['This is the quote with "embedded" quotes']] + """ + def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None, convertWhitespaceEscapes=True): + super(QuotedString,self).__init__() + + # remove white space from quote chars - wont work anyway + quoteChar = quoteChar.strip() + if not quoteChar: + warnings.warn("quoteChar cannot be the empty string",SyntaxWarning,stacklevel=2) + raise SyntaxError() + + if endQuoteChar is None: + endQuoteChar = quoteChar + else: + endQuoteChar = endQuoteChar.strip() + if not endQuoteChar: + warnings.warn("endQuoteChar cannot be the empty string",SyntaxWarning,stacklevel=2) + raise SyntaxError() + + self.quoteChar = quoteChar + self.quoteCharLen = len(quoteChar) + self.firstQuoteChar = quoteChar[0] + self.endQuoteChar = endQuoteChar + self.endQuoteCharLen = len(endQuoteChar) + self.escChar = escChar + self.escQuote = escQuote + self.unquoteResults = unquoteResults + self.convertWhitespaceEscapes = convertWhitespaceEscapes + + if multiline: + self.flags = re.MULTILINE | re.DOTALL + self.pattern = r'%s(?:[^%s%s]' % \ + ( re.escape(self.quoteChar), + _escapeRegexRangeChars(self.endQuoteChar[0]), + (escChar is not None and _escapeRegexRangeChars(escChar) or '') ) + else: + self.flags = 0 + self.pattern = r'%s(?:[^%s\n\r%s]' % \ + ( re.escape(self.quoteChar), + _escapeRegexRangeChars(self.endQuoteChar[0]), + (escChar is not None and _escapeRegexRangeChars(escChar) or '') ) + if len(self.endQuoteChar) > 1: + self.pattern += ( + '|(?:' + ')|(?:'.join("%s[^%s]" % (re.escape(self.endQuoteChar[:i]), + _escapeRegexRangeChars(self.endQuoteChar[i])) + for i in range(len(self.endQuoteChar)-1,0,-1)) + ')' + ) + if escQuote: + self.pattern += (r'|(?:%s)' % re.escape(escQuote)) + if escChar: + self.pattern += (r'|(?:%s.)' % re.escape(escChar)) + self.escCharReplacePattern = re.escape(self.escChar)+"(.)" + self.pattern += (r')*%s' % re.escape(self.endQuoteChar)) + + try: + self.re = re.compile(self.pattern, self.flags) + self.reString = self.pattern + except sre_constants.error: + warnings.warn("invalid pattern (%s) passed to Regex" % self.pattern, + SyntaxWarning, stacklevel=2) + raise + + self.name = _ustr(self) + self.errmsg = "Expected " + self.name + self.mayIndexError = False + self.mayReturnEmpty = True + + def parseImpl( self, instring, loc, doActions=True ): + result = instring[loc] == self.firstQuoteChar and self.re.match(instring,loc) or None + if not result: + raise ParseException(instring, loc, self.errmsg, self) + + loc = result.end() + ret = result.group() + + if self.unquoteResults: + + # strip off quotes + ret = ret[self.quoteCharLen:-self.endQuoteCharLen] + + if isinstance(ret,basestring): + # replace escaped whitespace + if '\\' in ret and self.convertWhitespaceEscapes: + ws_map = { + r'\t' : '\t', + r'\n' : '\n', + r'\f' : '\f', + r'\r' : '\r', + } + for wslit,wschar in ws_map.items(): + ret = ret.replace(wslit, wschar) + + # replace escaped characters + if self.escChar: + ret = re.sub(self.escCharReplacePattern, r"\g<1>", ret) + + # replace escaped quotes + if self.escQuote: + ret = ret.replace(self.escQuote, self.endQuoteChar) + + return loc, ret + + def __str__( self ): + try: + return super(QuotedString,self).__str__() + except Exception: + pass + + if self.strRepr is None: + self.strRepr = "quoted string, starting with %s ending with %s" % (self.quoteChar, self.endQuoteChar) + + return self.strRepr + + +class CharsNotIn(Token): + """ + Token for matching words composed of characters I{not} in a given set (will + include whitespace in matched characters if not listed in the provided exclusion set - see example). + Defined with string containing all disallowed characters, and an optional + minimum, maximum, and/or exact length. The default value for C{min} is 1 (a + minimum value < 1 is not valid); the default values for C{max} and C{exact} + are 0, meaning no maximum or exact length restriction. + + Example:: + # define a comma-separated-value as anything that is not a ',' + csv_value = CharsNotIn(',') + print(delimitedList(csv_value).parseString("dkls,lsdkjf,s12 34,@!#,213")) + prints:: + ['dkls', 'lsdkjf', 's12 34', '@!#', '213'] + """ + def __init__( self, notChars, min=1, max=0, exact=0 ): + super(CharsNotIn,self).__init__() + self.skipWhitespace = False + self.notChars = notChars + + if min < 1: + raise ValueError("cannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permitted") + + self.minLen = min + + if max > 0: + self.maxLen = max + else: + self.maxLen = _MAX_INT + + if exact > 0: + self.maxLen = exact + self.minLen = exact + + self.name = _ustr(self) + self.errmsg = "Expected " + self.name + self.mayReturnEmpty = ( self.minLen == 0 ) + self.mayIndexError = False + + def parseImpl( self, instring, loc, doActions=True ): + if instring[loc] in self.notChars: + raise ParseException(instring, loc, self.errmsg, self) + + start = loc + loc += 1 + notchars = self.notChars + maxlen = min( start+self.maxLen, len(instring) ) + while loc < maxlen and \ + (instring[loc] not in notchars): + loc += 1 + + if loc - start < self.minLen: + raise ParseException(instring, loc, self.errmsg, self) + + return loc, instring[start:loc] + + def __str__( self ): + try: + return super(CharsNotIn, self).__str__() + except Exception: + pass + + if self.strRepr is None: + if len(self.notChars) > 4: + self.strRepr = "!W:(%s...)" % self.notChars[:4] + else: + self.strRepr = "!W:(%s)" % self.notChars + + return self.strRepr + +class White(Token): + """ + Special matching class for matching whitespace. Normally, whitespace is ignored + by pyparsing grammars. This class is included when some whitespace structures + are significant. Define with a string containing the whitespace characters to be + matched; default is C{" \\t\\r\\n"}. Also takes optional C{min}, C{max}, and C{exact} arguments, + as defined for the C{L{Word}} class. + """ + whiteStrs = { + " " : "", + "\t": "", + "\n": "", + "\r": "", + "\f": "", + } + def __init__(self, ws=" \t\r\n", min=1, max=0, exact=0): + super(White,self).__init__() + self.matchWhite = ws + self.setWhitespaceChars( "".join(c for c in self.whiteChars if c not in self.matchWhite) ) + #~ self.leaveWhitespace() + self.name = ("".join(White.whiteStrs[c] for c in self.matchWhite)) + self.mayReturnEmpty = True + self.errmsg = "Expected " + self.name + + self.minLen = min + + if max > 0: + self.maxLen = max + else: + self.maxLen = _MAX_INT + + if exact > 0: + self.maxLen = exact + self.minLen = exact + + def parseImpl( self, instring, loc, doActions=True ): + if not(instring[ loc ] in self.matchWhite): + raise ParseException(instring, loc, self.errmsg, self) + start = loc + loc += 1 + maxloc = start + self.maxLen + maxloc = min( maxloc, len(instring) ) + while loc < maxloc and instring[loc] in self.matchWhite: + loc += 1 + + if loc - start < self.minLen: + raise ParseException(instring, loc, self.errmsg, self) + + return loc, instring[start:loc] + + +class _PositionToken(Token): + def __init__( self ): + super(_PositionToken,self).__init__() + self.name=self.__class__.__name__ + self.mayReturnEmpty = True + self.mayIndexError = False + +class GoToColumn(_PositionToken): + """ + Token to advance to a specific column of input text; useful for tabular report scraping. + """ + def __init__( self, colno ): + super(GoToColumn,self).__init__() + self.col = colno + + def preParse( self, instring, loc ): + if col(loc,instring) != self.col: + instrlen = len(instring) + if self.ignoreExprs: + loc = self._skipIgnorables( instring, loc ) + while loc < instrlen and instring[loc].isspace() and col( loc, instring ) != self.col : + loc += 1 + return loc + + def parseImpl( self, instring, loc, doActions=True ): + thiscol = col( loc, instring ) + if thiscol > self.col: + raise ParseException( instring, loc, "Text not in expected column", self ) + newloc = loc + self.col - thiscol + ret = instring[ loc: newloc ] + return newloc, ret + + +class LineStart(_PositionToken): + """ + Matches if current position is at the beginning of a line within the parse string + + Example:: + + test = '''\ + AAA this line + AAA and this line + AAA but not this one + B AAA and definitely not this one + ''' + + for t in (LineStart() + 'AAA' + restOfLine).searchString(test): + print(t) + + Prints:: + ['AAA', ' this line'] + ['AAA', ' and this line'] + + """ + def __init__( self ): + super(LineStart,self).__init__() + self.errmsg = "Expected start of line" + + def parseImpl( self, instring, loc, doActions=True ): + if col(loc, instring) == 1: + return loc, [] + raise ParseException(instring, loc, self.errmsg, self) + +class LineEnd(_PositionToken): + """ + Matches if current position is at the end of a line within the parse string + """ + def __init__( self ): + super(LineEnd,self).__init__() + self.setWhitespaceChars( ParserElement.DEFAULT_WHITE_CHARS.replace("\n","") ) + self.errmsg = "Expected end of line" + + def parseImpl( self, instring, loc, doActions=True ): + if loc len(instring): + return loc, [] + else: + raise ParseException(instring, loc, self.errmsg, self) + +class WordStart(_PositionToken): + """ + Matches if the current position is at the beginning of a Word, and + is not preceded by any character in a given set of C{wordChars} + (default=C{printables}). To emulate the C{\b} behavior of regular expressions, + use C{WordStart(alphanums)}. C{WordStart} will also match at the beginning of + the string being parsed, or at the beginning of a line. + """ + def __init__(self, wordChars = printables): + super(WordStart,self).__init__() + self.wordChars = set(wordChars) + self.errmsg = "Not at the start of a word" + + def parseImpl(self, instring, loc, doActions=True ): + if loc != 0: + if (instring[loc-1] in self.wordChars or + instring[loc] not in self.wordChars): + raise ParseException(instring, loc, self.errmsg, self) + return loc, [] + +class WordEnd(_PositionToken): + """ + Matches if the current position is at the end of a Word, and + is not followed by any character in a given set of C{wordChars} + (default=C{printables}). To emulate the C{\b} behavior of regular expressions, + use C{WordEnd(alphanums)}. C{WordEnd} will also match at the end of + the string being parsed, or at the end of a line. + """ + def __init__(self, wordChars = printables): + super(WordEnd,self).__init__() + self.wordChars = set(wordChars) + self.skipWhitespace = False + self.errmsg = "Not at the end of a word" + + def parseImpl(self, instring, loc, doActions=True ): + instrlen = len(instring) + if instrlen>0 and loc maxExcLoc: + maxException = err + maxExcLoc = err.loc + except IndexError: + if len(instring) > maxExcLoc: + maxException = ParseException(instring,len(instring),e.errmsg,self) + maxExcLoc = len(instring) + else: + # save match among all matches, to retry longest to shortest + matches.append((loc2, e)) + + if matches: + matches.sort(key=lambda x: -x[0]) + for _,e in matches: + try: + return e._parse( instring, loc, doActions ) + except ParseException as err: + err.__traceback__ = None + if err.loc > maxExcLoc: + maxException = err + maxExcLoc = err.loc + + if maxException is not None: + maxException.msg = self.errmsg + raise maxException + else: + raise ParseException(instring, loc, "no defined alternatives to match", self) + + + def __ixor__(self, other ): + if isinstance( other, basestring ): + other = ParserElement._literalStringClass( other ) + return self.append( other ) #Or( [ self, other ] ) + + def __str__( self ): + if hasattr(self,"name"): + return self.name + + if self.strRepr is None: + self.strRepr = "{" + " ^ ".join(_ustr(e) for e in self.exprs) + "}" + + return self.strRepr + + def checkRecursion( self, parseElementList ): + subRecCheckList = parseElementList[:] + [ self ] + for e in self.exprs: + e.checkRecursion( subRecCheckList ) + + +class MatchFirst(ParseExpression): + """ + Requires that at least one C{ParseExpression} is found. + If two expressions match, the first one listed is the one that will match. + May be constructed using the C{'|'} operator. + + Example:: + # construct MatchFirst using '|' operator + + # watch the order of expressions to match + number = Word(nums) | Combine(Word(nums) + '.' + Word(nums)) + print(number.searchString("123 3.1416 789")) # Fail! -> [['123'], ['3'], ['1416'], ['789']] + + # put more selective expression first + number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums) + print(number.searchString("123 3.1416 789")) # Better -> [['123'], ['3.1416'], ['789']] + """ + def __init__( self, exprs, savelist = False ): + super(MatchFirst,self).__init__(exprs, savelist) + if self.exprs: + self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs) + else: + self.mayReturnEmpty = True + + def parseImpl( self, instring, loc, doActions=True ): + maxExcLoc = -1 + maxException = None + for e in self.exprs: + try: + ret = e._parse( instring, loc, doActions ) + return ret + except ParseException as err: + if err.loc > maxExcLoc: + maxException = err + maxExcLoc = err.loc + except IndexError: + if len(instring) > maxExcLoc: + maxException = ParseException(instring,len(instring),e.errmsg,self) + maxExcLoc = len(instring) + + # only got here if no expression matched, raise exception for match that made it the furthest + else: + if maxException is not None: + maxException.msg = self.errmsg + raise maxException + else: + raise ParseException(instring, loc, "no defined alternatives to match", self) + + def __ior__(self, other ): + if isinstance( other, basestring ): + other = ParserElement._literalStringClass( other ) + return self.append( other ) #MatchFirst( [ self, other ] ) + + def __str__( self ): + if hasattr(self,"name"): + return self.name + + if self.strRepr is None: + self.strRepr = "{" + " | ".join(_ustr(e) for e in self.exprs) + "}" + + return self.strRepr + + def checkRecursion( self, parseElementList ): + subRecCheckList = parseElementList[:] + [ self ] + for e in self.exprs: + e.checkRecursion( subRecCheckList ) + + +class Each(ParseExpression): + """ + Requires all given C{ParseExpression}s to be found, but in any order. + Expressions may be separated by whitespace. + May be constructed using the C{'&'} operator. + + Example:: + color = oneOf("RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN") + shape_type = oneOf("SQUARE CIRCLE TRIANGLE STAR HEXAGON OCTAGON") + integer = Word(nums) + shape_attr = "shape:" + shape_type("shape") + posn_attr = "posn:" + Group(integer("x") + ',' + integer("y"))("posn") + color_attr = "color:" + color("color") + size_attr = "size:" + integer("size") + + # use Each (using operator '&') to accept attributes in any order + # (shape and posn are required, color and size are optional) + shape_spec = shape_attr & posn_attr & Optional(color_attr) & Optional(size_attr) + + shape_spec.runTests(''' + shape: SQUARE color: BLACK posn: 100, 120 + shape: CIRCLE size: 50 color: BLUE posn: 50,80 + color:GREEN size:20 shape:TRIANGLE posn:20,40 + ''' + ) + prints:: + shape: SQUARE color: BLACK posn: 100, 120 + ['shape:', 'SQUARE', 'color:', 'BLACK', 'posn:', ['100', ',', '120']] + - color: BLACK + - posn: ['100', ',', '120'] + - x: 100 + - y: 120 + - shape: SQUARE + + + shape: CIRCLE size: 50 color: BLUE posn: 50,80 + ['shape:', 'CIRCLE', 'size:', '50', 'color:', 'BLUE', 'posn:', ['50', ',', '80']] + - color: BLUE + - posn: ['50', ',', '80'] + - x: 50 + - y: 80 + - shape: CIRCLE + - size: 50 + + + color: GREEN size: 20 shape: TRIANGLE posn: 20,40 + ['color:', 'GREEN', 'size:', '20', 'shape:', 'TRIANGLE', 'posn:', ['20', ',', '40']] + - color: GREEN + - posn: ['20', ',', '40'] + - x: 20 + - y: 40 + - shape: TRIANGLE + - size: 20 + """ + def __init__( self, exprs, savelist = True ): + super(Each,self).__init__(exprs, savelist) + self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs) + self.skipWhitespace = True + self.initExprGroups = True + + def parseImpl( self, instring, loc, doActions=True ): + if self.initExprGroups: + self.opt1map = dict((id(e.expr),e) for e in self.exprs if isinstance(e,Optional)) + opt1 = [ e.expr for e in self.exprs if isinstance(e,Optional) ] + opt2 = [ e for e in self.exprs if e.mayReturnEmpty and not isinstance(e,Optional)] + self.optionals = opt1 + opt2 + self.multioptionals = [ e.expr for e in self.exprs if isinstance(e,ZeroOrMore) ] + self.multirequired = [ e.expr for e in self.exprs if isinstance(e,OneOrMore) ] + self.required = [ e for e in self.exprs if not isinstance(e,(Optional,ZeroOrMore,OneOrMore)) ] + self.required += self.multirequired + self.initExprGroups = False + tmpLoc = loc + tmpReqd = self.required[:] + tmpOpt = self.optionals[:] + matchOrder = [] + + keepMatching = True + while keepMatching: + tmpExprs = tmpReqd + tmpOpt + self.multioptionals + self.multirequired + failed = [] + for e in tmpExprs: + try: + tmpLoc = e.tryParse( instring, tmpLoc ) + except ParseException: + failed.append(e) + else: + matchOrder.append(self.opt1map.get(id(e),e)) + if e in tmpReqd: + tmpReqd.remove(e) + elif e in tmpOpt: + tmpOpt.remove(e) + if len(failed) == len(tmpExprs): + keepMatching = False + + if tmpReqd: + missing = ", ".join(_ustr(e) for e in tmpReqd) + raise ParseException(instring,loc,"Missing one or more required elements (%s)" % missing ) + + # add any unmatched Optionals, in case they have default values defined + matchOrder += [e for e in self.exprs if isinstance(e,Optional) and e.expr in tmpOpt] + + resultlist = [] + for e in matchOrder: + loc,results = e._parse(instring,loc,doActions) + resultlist.append(results) + + finalResults = sum(resultlist, ParseResults([])) + return loc, finalResults + + def __str__( self ): + if hasattr(self,"name"): + return self.name + + if self.strRepr is None: + self.strRepr = "{" + " & ".join(_ustr(e) for e in self.exprs) + "}" + + return self.strRepr + + def checkRecursion( self, parseElementList ): + subRecCheckList = parseElementList[:] + [ self ] + for e in self.exprs: + e.checkRecursion( subRecCheckList ) + + +class ParseElementEnhance(ParserElement): + """ + Abstract subclass of C{ParserElement}, for combining and post-processing parsed tokens. + """ + def __init__( self, expr, savelist=False ): + super(ParseElementEnhance,self).__init__(savelist) + if isinstance( expr, basestring ): + if issubclass(ParserElement._literalStringClass, Token): + expr = ParserElement._literalStringClass(expr) + else: + expr = ParserElement._literalStringClass(Literal(expr)) + self.expr = expr + self.strRepr = None + if expr is not None: + self.mayIndexError = expr.mayIndexError + self.mayReturnEmpty = expr.mayReturnEmpty + self.setWhitespaceChars( expr.whiteChars ) + self.skipWhitespace = expr.skipWhitespace + self.saveAsList = expr.saveAsList + self.callPreparse = expr.callPreparse + self.ignoreExprs.extend(expr.ignoreExprs) + + def parseImpl( self, instring, loc, doActions=True ): + if self.expr is not None: + return self.expr._parse( instring, loc, doActions, callPreParse=False ) + else: + raise ParseException("",loc,self.errmsg,self) + + def leaveWhitespace( self ): + self.skipWhitespace = False + self.expr = self.expr.copy() + if self.expr is not None: + self.expr.leaveWhitespace() + return self + + def ignore( self, other ): + if isinstance( other, Suppress ): + if other not in self.ignoreExprs: + super( ParseElementEnhance, self).ignore( other ) + if self.expr is not None: + self.expr.ignore( self.ignoreExprs[-1] ) + else: + super( ParseElementEnhance, self).ignore( other ) + if self.expr is not None: + self.expr.ignore( self.ignoreExprs[-1] ) + return self + + def streamline( self ): + super(ParseElementEnhance,self).streamline() + if self.expr is not None: + self.expr.streamline() + return self + + def checkRecursion( self, parseElementList ): + if self in parseElementList: + raise RecursiveGrammarException( parseElementList+[self] ) + subRecCheckList = parseElementList[:] + [ self ] + if self.expr is not None: + self.expr.checkRecursion( subRecCheckList ) + + def validate( self, validateTrace=[] ): + tmp = validateTrace[:]+[self] + if self.expr is not None: + self.expr.validate(tmp) + self.checkRecursion( [] ) + + def __str__( self ): + try: + return super(ParseElementEnhance,self).__str__() + except Exception: + pass + + if self.strRepr is None and self.expr is not None: + self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.expr) ) + return self.strRepr + + +class FollowedBy(ParseElementEnhance): + """ + Lookahead matching of the given parse expression. C{FollowedBy} + does I{not} advance the parsing position within the input string, it only + verifies that the specified parse expression matches at the current + position. C{FollowedBy} always returns a null token list. + + Example:: + # use FollowedBy to match a label only if it is followed by a ':' + data_word = Word(alphas) + label = data_word + FollowedBy(':') + attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) + + OneOrMore(attr_expr).parseString("shape: SQUARE color: BLACK posn: upper left").pprint() + prints:: + [['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']] + """ + def __init__( self, expr ): + super(FollowedBy,self).__init__(expr) + self.mayReturnEmpty = True + + def parseImpl( self, instring, loc, doActions=True ): + self.expr.tryParse( instring, loc ) + return loc, [] + + +class NotAny(ParseElementEnhance): + """ + Lookahead to disallow matching with the given parse expression. C{NotAny} + does I{not} advance the parsing position within the input string, it only + verifies that the specified parse expression does I{not} match at the current + position. Also, C{NotAny} does I{not} skip over leading whitespace. C{NotAny} + always returns a null token list. May be constructed using the '~' operator. + + Example:: + + """ + def __init__( self, expr ): + super(NotAny,self).__init__(expr) + #~ self.leaveWhitespace() + self.skipWhitespace = False # do NOT use self.leaveWhitespace(), don't want to propagate to exprs + self.mayReturnEmpty = True + self.errmsg = "Found unwanted token, "+_ustr(self.expr) + + def parseImpl( self, instring, loc, doActions=True ): + if self.expr.canParseNext(instring, loc): + raise ParseException(instring, loc, self.errmsg, self) + return loc, [] + + def __str__( self ): + if hasattr(self,"name"): + return self.name + + if self.strRepr is None: + self.strRepr = "~{" + _ustr(self.expr) + "}" + + return self.strRepr + +class _MultipleMatch(ParseElementEnhance): + def __init__( self, expr, stopOn=None): + super(_MultipleMatch, self).__init__(expr) + self.saveAsList = True + ender = stopOn + if isinstance(ender, basestring): + ender = ParserElement._literalStringClass(ender) + self.not_ender = ~ender if ender is not None else None + + def parseImpl( self, instring, loc, doActions=True ): + self_expr_parse = self.expr._parse + self_skip_ignorables = self._skipIgnorables + check_ender = self.not_ender is not None + if check_ender: + try_not_ender = self.not_ender.tryParse + + # must be at least one (but first see if we are the stopOn sentinel; + # if so, fail) + if check_ender: + try_not_ender(instring, loc) + loc, tokens = self_expr_parse( instring, loc, doActions, callPreParse=False ) + try: + hasIgnoreExprs = (not not self.ignoreExprs) + while 1: + if check_ender: + try_not_ender(instring, loc) + if hasIgnoreExprs: + preloc = self_skip_ignorables( instring, loc ) + else: + preloc = loc + loc, tmptokens = self_expr_parse( instring, preloc, doActions ) + if tmptokens or tmptokens.haskeys(): + tokens += tmptokens + except (ParseException,IndexError): + pass + + return loc, tokens + +class OneOrMore(_MultipleMatch): + """ + Repetition of one or more of the given expression. + + Parameters: + - expr - expression that must match one or more times + - stopOn - (default=C{None}) - expression for a terminating sentinel + (only required if the sentinel would ordinarily match the repetition + expression) + + Example:: + data_word = Word(alphas) + label = data_word + FollowedBy(':') + attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join)) + + text = "shape: SQUARE posn: upper left color: BLACK" + OneOrMore(attr_expr).parseString(text).pprint() # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']] + + # use stopOn attribute for OneOrMore to avoid reading label string as part of the data + attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) + OneOrMore(attr_expr).parseString(text).pprint() # Better -> [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']] + + # could also be written as + (attr_expr * (1,)).parseString(text).pprint() + """ + + def __str__( self ): + if hasattr(self,"name"): + return self.name + + if self.strRepr is None: + self.strRepr = "{" + _ustr(self.expr) + "}..." + + return self.strRepr + +class ZeroOrMore(_MultipleMatch): + """ + Optional repetition of zero or more of the given expression. + + Parameters: + - expr - expression that must match zero or more times + - stopOn - (default=C{None}) - expression for a terminating sentinel + (only required if the sentinel would ordinarily match the repetition + expression) + + Example: similar to L{OneOrMore} + """ + def __init__( self, expr, stopOn=None): + super(ZeroOrMore,self).__init__(expr, stopOn=stopOn) + self.mayReturnEmpty = True + + def parseImpl( self, instring, loc, doActions=True ): + try: + return super(ZeroOrMore, self).parseImpl(instring, loc, doActions) + except (ParseException,IndexError): + return loc, [] + + def __str__( self ): + if hasattr(self,"name"): + return self.name + + if self.strRepr is None: + self.strRepr = "[" + _ustr(self.expr) + "]..." + + return self.strRepr + +class _NullToken(object): + def __bool__(self): + return False + __nonzero__ = __bool__ + def __str__(self): + return "" + +_optionalNotMatched = _NullToken() +class Optional(ParseElementEnhance): + """ + Optional matching of the given expression. + + Parameters: + - expr - expression that must match zero or more times + - default (optional) - value to be returned if the optional expression is not found. + + Example:: + # US postal code can be a 5-digit zip, plus optional 4-digit qualifier + zip = Combine(Word(nums, exact=5) + Optional('-' + Word(nums, exact=4))) + zip.runTests(''' + # traditional ZIP code + 12345 + + # ZIP+4 form + 12101-0001 + + # invalid ZIP + 98765- + ''') + prints:: + # traditional ZIP code + 12345 + ['12345'] + + # ZIP+4 form + 12101-0001 + ['12101-0001'] + + # invalid ZIP + 98765- + ^ + FAIL: Expected end of text (at char 5), (line:1, col:6) + """ + def __init__( self, expr, default=_optionalNotMatched ): + super(Optional,self).__init__( expr, savelist=False ) + self.saveAsList = self.expr.saveAsList + self.defaultValue = default + self.mayReturnEmpty = True + + def parseImpl( self, instring, loc, doActions=True ): + try: + loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False ) + except (ParseException,IndexError): + if self.defaultValue is not _optionalNotMatched: + if self.expr.resultsName: + tokens = ParseResults([ self.defaultValue ]) + tokens[self.expr.resultsName] = self.defaultValue + else: + tokens = [ self.defaultValue ] + else: + tokens = [] + return loc, tokens + + def __str__( self ): + if hasattr(self,"name"): + return self.name + + if self.strRepr is None: + self.strRepr = "[" + _ustr(self.expr) + "]" + + return self.strRepr + +class SkipTo(ParseElementEnhance): + """ + Token for skipping over all undefined text until the matched expression is found. + + Parameters: + - expr - target expression marking the end of the data to be skipped + - include - (default=C{False}) if True, the target expression is also parsed + (the skipped text and target expression are returned as a 2-element list). + - ignore - (default=C{None}) used to define grammars (typically quoted strings and + comments) that might contain false matches to the target expression + - failOn - (default=C{None}) define expressions that are not allowed to be + included in the skipped test; if found before the target expression is found, + the SkipTo is not a match + + Example:: + report = ''' + Outstanding Issues Report - 1 Jan 2000 + + # | Severity | Description | Days Open + -----+----------+-------------------------------------------+----------- + 101 | Critical | Intermittent system crash | 6 + 94 | Cosmetic | Spelling error on Login ('log|n') | 14 + 79 | Minor | System slow when running too many reports | 47 + ''' + integer = Word(nums) + SEP = Suppress('|') + # use SkipTo to simply match everything up until the next SEP + # - ignore quoted strings, so that a '|' character inside a quoted string does not match + # - parse action will call token.strip() for each matched token, i.e., the description body + string_data = SkipTo(SEP, ignore=quotedString) + string_data.setParseAction(tokenMap(str.strip)) + ticket_expr = (integer("issue_num") + SEP + + string_data("sev") + SEP + + string_data("desc") + SEP + + integer("days_open")) + + for tkt in ticket_expr.searchString(report): + print tkt.dump() + prints:: + ['101', 'Critical', 'Intermittent system crash', '6'] + - days_open: 6 + - desc: Intermittent system crash + - issue_num: 101 + - sev: Critical + ['94', 'Cosmetic', "Spelling error on Login ('log|n')", '14'] + - days_open: 14 + - desc: Spelling error on Login ('log|n') + - issue_num: 94 + - sev: Cosmetic + ['79', 'Minor', 'System slow when running too many reports', '47'] + - days_open: 47 + - desc: System slow when running too many reports + - issue_num: 79 + - sev: Minor + """ + def __init__( self, other, include=False, ignore=None, failOn=None ): + super( SkipTo, self ).__init__( other ) + self.ignoreExpr = ignore + self.mayReturnEmpty = True + self.mayIndexError = False + self.includeMatch = include + self.asList = False + if isinstance(failOn, basestring): + self.failOn = ParserElement._literalStringClass(failOn) + else: + self.failOn = failOn + self.errmsg = "No match found for "+_ustr(self.expr) + + def parseImpl( self, instring, loc, doActions=True ): + startloc = loc + instrlen = len(instring) + expr = self.expr + expr_parse = self.expr._parse + self_failOn_canParseNext = self.failOn.canParseNext if self.failOn is not None else None + self_ignoreExpr_tryParse = self.ignoreExpr.tryParse if self.ignoreExpr is not None else None + + tmploc = loc + while tmploc <= instrlen: + if self_failOn_canParseNext is not None: + # break if failOn expression matches + if self_failOn_canParseNext(instring, tmploc): + break + + if self_ignoreExpr_tryParse is not None: + # advance past ignore expressions + while 1: + try: + tmploc = self_ignoreExpr_tryParse(instring, tmploc) + except ParseBaseException: + break + + try: + expr_parse(instring, tmploc, doActions=False, callPreParse=False) + except (ParseException, IndexError): + # no match, advance loc in string + tmploc += 1 + else: + # matched skipto expr, done + break + + else: + # ran off the end of the input string without matching skipto expr, fail + raise ParseException(instring, loc, self.errmsg, self) + + # build up return values + loc = tmploc + skiptext = instring[startloc:loc] + skipresult = ParseResults(skiptext) + + if self.includeMatch: + loc, mat = expr_parse(instring,loc,doActions,callPreParse=False) + skipresult += mat + + return loc, skipresult + +class Forward(ParseElementEnhance): + """ + Forward declaration of an expression to be defined later - + used for recursive grammars, such as algebraic infix notation. + When the expression is known, it is assigned to the C{Forward} variable using the '<<' operator. + + Note: take care when assigning to C{Forward} not to overlook precedence of operators. + Specifically, '|' has a lower precedence than '<<', so that:: + fwdExpr << a | b | c + will actually be evaluated as:: + (fwdExpr << a) | b | c + thereby leaving b and c out as parseable alternatives. It is recommended that you + explicitly group the values inserted into the C{Forward}:: + fwdExpr << (a | b | c) + Converting to use the '<<=' operator instead will avoid this problem. + + See L{ParseResults.pprint} for an example of a recursive parser created using + C{Forward}. + """ + def __init__( self, other=None ): + super(Forward,self).__init__( other, savelist=False ) + + def __lshift__( self, other ): + if isinstance( other, basestring ): + other = ParserElement._literalStringClass(other) + self.expr = other + self.strRepr = None + self.mayIndexError = self.expr.mayIndexError + self.mayReturnEmpty = self.expr.mayReturnEmpty + self.setWhitespaceChars( self.expr.whiteChars ) + self.skipWhitespace = self.expr.skipWhitespace + self.saveAsList = self.expr.saveAsList + self.ignoreExprs.extend(self.expr.ignoreExprs) + return self + + def __ilshift__(self, other): + return self << other + + def leaveWhitespace( self ): + self.skipWhitespace = False + return self + + def streamline( self ): + if not self.streamlined: + self.streamlined = True + if self.expr is not None: + self.expr.streamline() + return self + + def validate( self, validateTrace=[] ): + if self not in validateTrace: + tmp = validateTrace[:]+[self] + if self.expr is not None: + self.expr.validate(tmp) + self.checkRecursion([]) + + def __str__( self ): + if hasattr(self,"name"): + return self.name + return self.__class__.__name__ + ": ..." + + # stubbed out for now - creates awful memory and perf issues + self._revertClass = self.__class__ + self.__class__ = _ForwardNoRecurse + try: + if self.expr is not None: + retString = _ustr(self.expr) + else: + retString = "None" + finally: + self.__class__ = self._revertClass + return self.__class__.__name__ + ": " + retString + + def copy(self): + if self.expr is not None: + return super(Forward,self).copy() + else: + ret = Forward() + ret <<= self + return ret + +class _ForwardNoRecurse(Forward): + def __str__( self ): + return "..." + +class TokenConverter(ParseElementEnhance): + """ + Abstract subclass of C{ParseExpression}, for converting parsed results. + """ + def __init__( self, expr, savelist=False ): + super(TokenConverter,self).__init__( expr )#, savelist ) + self.saveAsList = False + +class Combine(TokenConverter): + """ + Converter to concatenate all matching tokens to a single string. + By default, the matching patterns must also be contiguous in the input string; + this can be disabled by specifying C{'adjacent=False'} in the constructor. + + Example:: + real = Word(nums) + '.' + Word(nums) + print(real.parseString('3.1416')) # -> ['3', '.', '1416'] + # will also erroneously match the following + print(real.parseString('3. 1416')) # -> ['3', '.', '1416'] + + real = Combine(Word(nums) + '.' + Word(nums)) + print(real.parseString('3.1416')) # -> ['3.1416'] + # no match when there are internal spaces + print(real.parseString('3. 1416')) # -> Exception: Expected W:(0123...) + """ + def __init__( self, expr, joinString="", adjacent=True ): + super(Combine,self).__init__( expr ) + # suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself + if adjacent: + self.leaveWhitespace() + self.adjacent = adjacent + self.skipWhitespace = True + self.joinString = joinString + self.callPreparse = True + + def ignore( self, other ): + if self.adjacent: + ParserElement.ignore(self, other) + else: + super( Combine, self).ignore( other ) + return self + + def postParse( self, instring, loc, tokenlist ): + retToks = tokenlist.copy() + del retToks[:] + retToks += ParseResults([ "".join(tokenlist._asStringList(self.joinString)) ], modal=self.modalResults) + + if self.resultsName and retToks.haskeys(): + return [ retToks ] + else: + return retToks + +class Group(TokenConverter): + """ + Converter to return the matched tokens as a list - useful for returning tokens of C{L{ZeroOrMore}} and C{L{OneOrMore}} expressions. + + Example:: + ident = Word(alphas) + num = Word(nums) + term = ident | num + func = ident + Optional(delimitedList(term)) + print(func.parseString("fn a,b,100")) # -> ['fn', 'a', 'b', '100'] + + func = ident + Group(Optional(delimitedList(term))) + print(func.parseString("fn a,b,100")) # -> ['fn', ['a', 'b', '100']] + """ + def __init__( self, expr ): + super(Group,self).__init__( expr ) + self.saveAsList = True + + def postParse( self, instring, loc, tokenlist ): + return [ tokenlist ] + +class Dict(TokenConverter): + """ + Converter to return a repetitive expression as a list, but also as a dictionary. + Each element can also be referenced using the first token in the expression as its key. + Useful for tabular report scraping when the first column can be used as a item key. + + Example:: + data_word = Word(alphas) + label = data_word + FollowedBy(':') + attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join)) + + text = "shape: SQUARE posn: upper left color: light blue texture: burlap" + attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) + + # print attributes as plain groups + print(OneOrMore(attr_expr).parseString(text).dump()) + + # instead of OneOrMore(expr), parse using Dict(OneOrMore(Group(expr))) - Dict will auto-assign names + result = Dict(OneOrMore(Group(attr_expr))).parseString(text) + print(result.dump()) + + # access named fields as dict entries, or output as dict + print(result['shape']) + print(result.asDict()) + prints:: + ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap'] + + [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] + - color: light blue + - posn: upper left + - shape: SQUARE + - texture: burlap + SQUARE + {'color': 'light blue', 'posn': 'upper left', 'texture': 'burlap', 'shape': 'SQUARE'} + See more examples at L{ParseResults} of accessing fields by results name. + """ + def __init__( self, expr ): + super(Dict,self).__init__( expr ) + self.saveAsList = True + + def postParse( self, instring, loc, tokenlist ): + for i,tok in enumerate(tokenlist): + if len(tok) == 0: + continue + ikey = tok[0] + if isinstance(ikey,int): + ikey = _ustr(tok[0]).strip() + if len(tok)==1: + tokenlist[ikey] = _ParseResultsWithOffset("",i) + elif len(tok)==2 and not isinstance(tok[1],ParseResults): + tokenlist[ikey] = _ParseResultsWithOffset(tok[1],i) + else: + dictvalue = tok.copy() #ParseResults(i) + del dictvalue[0] + if len(dictvalue)!= 1 or (isinstance(dictvalue,ParseResults) and dictvalue.haskeys()): + tokenlist[ikey] = _ParseResultsWithOffset(dictvalue,i) + else: + tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0],i) + + if self.resultsName: + return [ tokenlist ] + else: + return tokenlist + + +class Suppress(TokenConverter): + """ + Converter for ignoring the results of a parsed expression. + + Example:: + source = "a, b, c,d" + wd = Word(alphas) + wd_list1 = wd + ZeroOrMore(',' + wd) + print(wd_list1.parseString(source)) + + # often, delimiters that are useful during parsing are just in the + # way afterward - use Suppress to keep them out of the parsed output + wd_list2 = wd + ZeroOrMore(Suppress(',') + wd) + print(wd_list2.parseString(source)) + prints:: + ['a', ',', 'b', ',', 'c', ',', 'd'] + ['a', 'b', 'c', 'd'] + (See also L{delimitedList}.) + """ + def postParse( self, instring, loc, tokenlist ): + return [] + + def suppress( self ): + return self + + +class OnlyOnce(object): + """ + Wrapper for parse actions, to ensure they are only called once. + """ + def __init__(self, methodCall): + self.callable = _trim_arity(methodCall) + self.called = False + def __call__(self,s,l,t): + if not self.called: + results = self.callable(s,l,t) + self.called = True + return results + raise ParseException(s,l,"") + def reset(self): + self.called = False + +def traceParseAction(f): + """ + Decorator for debugging parse actions. + + When the parse action is called, this decorator will print C{">> entering I{method-name}(line:I{current_source_line}, I{parse_location}, I{matched_tokens})".} + When the parse action completes, the decorator will print C{"<<"} followed by the returned value, or any exception that the parse action raised. + + Example:: + wd = Word(alphas) + + @traceParseAction + def remove_duplicate_chars(tokens): + return ''.join(sorted(set(''.join(tokens)))) + + wds = OneOrMore(wd).setParseAction(remove_duplicate_chars) + print(wds.parseString("slkdjs sld sldd sdlf sdljf")) + prints:: + >>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {})) + <3: + thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc + sys.stderr.write( ">>entering %s(line: '%s', %d, %r)\n" % (thisFunc,line(l,s),l,t) ) + try: + ret = f(*paArgs) + except Exception as exc: + sys.stderr.write( "< ['aa', 'bb', 'cc'] + delimitedList(Word(hexnums), delim=':', combine=True).parseString("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE'] + """ + dlName = _ustr(expr)+" ["+_ustr(delim)+" "+_ustr(expr)+"]..." + if combine: + return Combine( expr + ZeroOrMore( delim + expr ) ).setName(dlName) + else: + return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName) + +def countedArray( expr, intExpr=None ): + """ + Helper to define a counted list of expressions. + This helper defines a pattern of the form:: + integer expr expr expr... + where the leading integer tells how many expr expressions follow. + The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed. + + If C{intExpr} is specified, it should be a pyparsing expression that produces an integer value. + + Example:: + countedArray(Word(alphas)).parseString('2 ab cd ef') # -> ['ab', 'cd'] + + # in this parser, the leading integer value is given in binary, + # '10' indicating that 2 values are in the array + binaryConstant = Word('01').setParseAction(lambda t: int(t[0], 2)) + countedArray(Word(alphas), intExpr=binaryConstant).parseString('10 ab cd ef') # -> ['ab', 'cd'] + """ + arrayExpr = Forward() + def countFieldParseAction(s,l,t): + n = t[0] + arrayExpr << (n and Group(And([expr]*n)) or Group(empty)) + return [] + if intExpr is None: + intExpr = Word(nums).setParseAction(lambda t:int(t[0])) + else: + intExpr = intExpr.copy() + intExpr.setName("arrayLen") + intExpr.addParseAction(countFieldParseAction, callDuringTry=True) + return ( intExpr + arrayExpr ).setName('(len) ' + _ustr(expr) + '...') + +def _flatten(L): + ret = [] + for i in L: + if isinstance(i,list): + ret.extend(_flatten(i)) + else: + ret.append(i) + return ret + +def matchPreviousLiteral(expr): + """ + Helper to define an expression that is indirectly defined from + the tokens matched in a previous expression, that is, it looks + for a 'repeat' of a previous expression. For example:: + first = Word(nums) + second = matchPreviousLiteral(first) + matchExpr = first + ":" + second + will match C{"1:1"}, but not C{"1:2"}. Because this matches a + previous literal, will also match the leading C{"1:1"} in C{"1:10"}. + If this is not desired, use C{matchPreviousExpr}. + Do I{not} use with packrat parsing enabled. + """ + rep = Forward() + def copyTokenToRepeater(s,l,t): + if t: + if len(t) == 1: + rep << t[0] + else: + # flatten t tokens + tflat = _flatten(t.asList()) + rep << And(Literal(tt) for tt in tflat) + else: + rep << Empty() + expr.addParseAction(copyTokenToRepeater, callDuringTry=True) + rep.setName('(prev) ' + _ustr(expr)) + return rep + +def matchPreviousExpr(expr): + """ + Helper to define an expression that is indirectly defined from + the tokens matched in a previous expression, that is, it looks + for a 'repeat' of a previous expression. For example:: + first = Word(nums) + second = matchPreviousExpr(first) + matchExpr = first + ":" + second + will match C{"1:1"}, but not C{"1:2"}. Because this matches by + expressions, will I{not} match the leading C{"1:1"} in C{"1:10"}; + the expressions are evaluated first, and then compared, so + C{"1"} is compared with C{"10"}. + Do I{not} use with packrat parsing enabled. + """ + rep = Forward() + e2 = expr.copy() + rep <<= e2 + def copyTokenToRepeater(s,l,t): + matchTokens = _flatten(t.asList()) + def mustMatchTheseTokens(s,l,t): + theseTokens = _flatten(t.asList()) + if theseTokens != matchTokens: + raise ParseException("",0,"") + rep.setParseAction( mustMatchTheseTokens, callDuringTry=True ) + expr.addParseAction(copyTokenToRepeater, callDuringTry=True) + rep.setName('(prev) ' + _ustr(expr)) + return rep + +def _escapeRegexRangeChars(s): + #~ escape these chars: ^-] + for c in r"\^-]": + s = s.replace(c,_bslash+c) + s = s.replace("\n",r"\n") + s = s.replace("\t",r"\t") + return _ustr(s) + +def oneOf( strs, caseless=False, useRegex=True ): + """ + Helper to quickly define a set of alternative Literals, and makes sure to do + longest-first testing when there is a conflict, regardless of the input order, + but returns a C{L{MatchFirst}} for best performance. + + Parameters: + - strs - a string of space-delimited literals, or a collection of string literals + - caseless - (default=C{False}) - treat all literals as caseless + - useRegex - (default=C{True}) - as an optimization, will generate a Regex + object; otherwise, will generate a C{MatchFirst} object (if C{caseless=True}, or + if creating a C{Regex} raises an exception) + + Example:: + comp_oper = oneOf("< = > <= >= !=") + var = Word(alphas) + number = Word(nums) + term = var | number + comparison_expr = term + comp_oper + term + print(comparison_expr.searchString("B = 12 AA=23 B<=AA AA>12")) + prints:: + [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']] + """ + if caseless: + isequal = ( lambda a,b: a.upper() == b.upper() ) + masks = ( lambda a,b: b.upper().startswith(a.upper()) ) + parseElementClass = CaselessLiteral + else: + isequal = ( lambda a,b: a == b ) + masks = ( lambda a,b: b.startswith(a) ) + parseElementClass = Literal + + symbols = [] + if isinstance(strs,basestring): + symbols = strs.split() + elif isinstance(strs, Iterable): + symbols = list(strs) + else: + warnings.warn("Invalid argument to oneOf, expected string or iterable", + SyntaxWarning, stacklevel=2) + if not symbols: + return NoMatch() + + i = 0 + while i < len(symbols)-1: + cur = symbols[i] + for j,other in enumerate(symbols[i+1:]): + if ( isequal(other, cur) ): + del symbols[i+j+1] + break + elif ( masks(cur, other) ): + del symbols[i+j+1] + symbols.insert(i,other) + cur = other + break + else: + i += 1 + + if not caseless and useRegex: + #~ print (strs,"->", "|".join( [ _escapeRegexChars(sym) for sym in symbols] )) + try: + if len(symbols)==len("".join(symbols)): + return Regex( "[%s]" % "".join(_escapeRegexRangeChars(sym) for sym in symbols) ).setName(' | '.join(symbols)) + else: + return Regex( "|".join(re.escape(sym) for sym in symbols) ).setName(' | '.join(symbols)) + except Exception: + warnings.warn("Exception creating Regex for oneOf, building MatchFirst", + SyntaxWarning, stacklevel=2) + + + # last resort, just use MatchFirst + return MatchFirst(parseElementClass(sym) for sym in symbols).setName(' | '.join(symbols)) + +def dictOf( key, value ): + """ + Helper to easily and clearly define a dictionary by specifying the respective patterns + for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens + in the proper order. The key pattern can include delimiting markers or punctuation, + as long as they are suppressed, thereby leaving the significant key text. The value + pattern can include named results, so that the C{Dict} results can include named token + fields. + + Example:: + text = "shape: SQUARE posn: upper left color: light blue texture: burlap" + attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) + print(OneOrMore(attr_expr).parseString(text).dump()) + + attr_label = label + attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join) + + # similar to Dict, but simpler call format + result = dictOf(attr_label, attr_value).parseString(text) + print(result.dump()) + print(result['shape']) + print(result.shape) # object attribute access works too + print(result.asDict()) + prints:: + [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] + - color: light blue + - posn: upper left + - shape: SQUARE + - texture: burlap + SQUARE + SQUARE + {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'} + """ + return Dict( ZeroOrMore( Group ( key + value ) ) ) + +def originalTextFor(expr, asString=True): + """ + Helper to return the original, untokenized text for a given expression. Useful to + restore the parsed fields of an HTML start tag into the raw tag text itself, or to + revert separate tokens with intervening whitespace back to the original matching + input text. By default, returns astring containing the original parsed text. + + If the optional C{asString} argument is passed as C{False}, then the return value is a + C{L{ParseResults}} containing any results names that were originally matched, and a + single token containing the original matched text from the input string. So if + the expression passed to C{L{originalTextFor}} contains expressions with defined + results names, you must set C{asString} to C{False} if you want to preserve those + results name values. + + Example:: + src = "this is test bold text normal text " + for tag in ("b","i"): + opener,closer = makeHTMLTags(tag) + patt = originalTextFor(opener + SkipTo(closer) + closer) + print(patt.searchString(src)[0]) + prints:: + [' bold text '] + ['text'] + """ + locMarker = Empty().setParseAction(lambda s,loc,t: loc) + endlocMarker = locMarker.copy() + endlocMarker.callPreparse = False + matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end") + if asString: + extractText = lambda s,l,t: s[t._original_start:t._original_end] + else: + def extractText(s,l,t): + t[:] = [s[t.pop('_original_start'):t.pop('_original_end')]] + matchExpr.setParseAction(extractText) + matchExpr.ignoreExprs = expr.ignoreExprs + return matchExpr + +def ungroup(expr): + """ + Helper to undo pyparsing's default grouping of And expressions, even + if all but one are non-empty. + """ + return TokenConverter(expr).setParseAction(lambda t:t[0]) + +def locatedExpr(expr): + """ + Helper to decorate a returned token with its starting and ending locations in the input string. + This helper adds the following results names: + - locn_start = location where matched expression begins + - locn_end = location where matched expression ends + - value = the actual parsed results + + Be careful if the input text contains C{} characters, you may want to call + C{L{ParserElement.parseWithTabs}} + + Example:: + wd = Word(alphas) + for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"): + print(match) + prints:: + [[0, 'ljsdf', 5]] + [[8, 'lksdjjf', 15]] + [[18, 'lkkjj', 23]] + """ + locator = Empty().setParseAction(lambda s,l,t: l) + return Group(locator("locn_start") + expr("value") + locator.copy().leaveWhitespace()("locn_end")) + + +# convenience constants for positional expressions +empty = Empty().setName("empty") +lineStart = LineStart().setName("lineStart") +lineEnd = LineEnd().setName("lineEnd") +stringStart = StringStart().setName("stringStart") +stringEnd = StringEnd().setName("stringEnd") + +_escapedPunc = Word( _bslash, r"\[]-*.$+^?()~ ", exact=2 ).setParseAction(lambda s,l,t:t[0][1]) +_escapedHexChar = Regex(r"\\0?[xX][0-9a-fA-F]+").setParseAction(lambda s,l,t:unichr(int(t[0].lstrip(r'\0x'),16))) +_escapedOctChar = Regex(r"\\0[0-7]+").setParseAction(lambda s,l,t:unichr(int(t[0][1:],8))) +_singleChar = _escapedPunc | _escapedHexChar | _escapedOctChar | CharsNotIn(r'\]', exact=1) +_charRange = Group(_singleChar + Suppress("-") + _singleChar) +_reBracketExpr = Literal("[") + Optional("^").setResultsName("negate") + Group( OneOrMore( _charRange | _singleChar ) ).setResultsName("body") + "]" + +def srange(s): + r""" + Helper to easily define string ranges for use in Word construction. Borrows + syntax from regexp '[]' string range definitions:: + srange("[0-9]") -> "0123456789" + srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz" + srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_" + The input string must be enclosed in []'s, and the returned string is the expanded + character set joined into a single string. + The values enclosed in the []'s may be: + - a single character + - an escaped character with a leading backslash (such as C{\-} or C{\]}) + - an escaped hex character with a leading C{'\x'} (C{\x21}, which is a C{'!'} character) + (C{\0x##} is also supported for backwards compatibility) + - an escaped octal character with a leading C{'\0'} (C{\041}, which is a C{'!'} character) + - a range of any of the above, separated by a dash (C{'a-z'}, etc.) + - any combination of the above (C{'aeiouy'}, C{'a-zA-Z0-9_$'}, etc.) + """ + _expanded = lambda p: p if not isinstance(p,ParseResults) else ''.join(unichr(c) for c in range(ord(p[0]),ord(p[1])+1)) + try: + return "".join(_expanded(part) for part in _reBracketExpr.parseString(s).body) + except Exception: + return "" + +def matchOnlyAtCol(n): + """ + Helper method for defining parse actions that require matching at a specific + column in the input text. + """ + def verifyCol(strg,locn,toks): + if col(locn,strg) != n: + raise ParseException(strg,locn,"matched token not at column %d" % n) + return verifyCol + +def replaceWith(replStr): + """ + Helper method for common parse actions that simply return a literal value. Especially + useful when used with C{L{transformString}()}. + + Example:: + num = Word(nums).setParseAction(lambda toks: int(toks[0])) + na = oneOf("N/A NA").setParseAction(replaceWith(math.nan)) + term = na | num + + OneOrMore(term).parseString("324 234 N/A 234") # -> [324, 234, nan, 234] + """ + return lambda s,l,t: [replStr] + +def removeQuotes(s,l,t): + """ + Helper parse action for removing quotation marks from parsed quoted strings. + + Example:: + # by default, quotation marks are included in parsed results + quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"] + + # use removeQuotes to strip quotation marks from parsed results + quotedString.setParseAction(removeQuotes) + quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"] + """ + return t[0][1:-1] + +def tokenMap(func, *args): + """ + Helper to define a parse action by mapping a function to all elements of a ParseResults list.If any additional + args are passed, they are forwarded to the given function as additional arguments after + the token, as in C{hex_integer = Word(hexnums).setParseAction(tokenMap(int, 16))}, which will convert the + parsed data to an integer using base 16. + + Example (compare the last to example in L{ParserElement.transformString}:: + hex_ints = OneOrMore(Word(hexnums)).setParseAction(tokenMap(int, 16)) + hex_ints.runTests(''' + 00 11 22 aa FF 0a 0d 1a + ''') + + upperword = Word(alphas).setParseAction(tokenMap(str.upper)) + OneOrMore(upperword).runTests(''' + my kingdom for a horse + ''') + + wd = Word(alphas).setParseAction(tokenMap(str.title)) + OneOrMore(wd).setParseAction(' '.join).runTests(''' + now is the winter of our discontent made glorious summer by this sun of york + ''') + prints:: + 00 11 22 aa FF 0a 0d 1a + [0, 17, 34, 170, 255, 10, 13, 26] + + my kingdom for a horse + ['MY', 'KINGDOM', 'FOR', 'A', 'HORSE'] + + now is the winter of our discontent made glorious summer by this sun of york + ['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York'] + """ + def pa(s,l,t): + return [func(tokn, *args) for tokn in t] + + try: + func_name = getattr(func, '__name__', + getattr(func, '__class__').__name__) + except Exception: + func_name = str(func) + pa.__name__ = func_name + + return pa + +upcaseTokens = tokenMap(lambda t: _ustr(t).upper()) +"""(Deprecated) Helper parse action to convert tokens to upper case. Deprecated in favor of L{pyparsing_common.upcaseTokens}""" + +downcaseTokens = tokenMap(lambda t: _ustr(t).lower()) +"""(Deprecated) Helper parse action to convert tokens to lower case. Deprecated in favor of L{pyparsing_common.downcaseTokens}""" + +def _makeTags(tagStr, xml): + """Internal helper to construct opening and closing tag expressions, given a tag name""" + if isinstance(tagStr,basestring): + resname = tagStr + tagStr = Keyword(tagStr, caseless=not xml) + else: + resname = tagStr.name + + tagAttrName = Word(alphas,alphanums+"_-:") + if (xml): + tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes ) + openTag = Suppress("<") + tagStr("tag") + \ + Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttrValue ))) + \ + Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">") + else: + printablesLessRAbrack = "".join(c for c in printables if c not in ">") + tagAttrValue = quotedString.copy().setParseAction( removeQuotes ) | Word(printablesLessRAbrack) + openTag = Suppress("<") + tagStr("tag") + \ + Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + \ + Optional( Suppress("=") + tagAttrValue ) ))) + \ + Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">") + closeTag = Combine(_L("") + + openTag = openTag.setResultsName("start"+"".join(resname.replace(":"," ").title().split())).setName("<%s>" % resname) + closeTag = closeTag.setResultsName("end"+"".join(resname.replace(":"," ").title().split())).setName("" % resname) + openTag.tag = resname + closeTag.tag = resname + return openTag, closeTag + +def makeHTMLTags(tagStr): + """ + Helper to construct opening and closing tag expressions for HTML, given a tag name. Matches + tags in either upper or lower case, attributes with namespaces and with quoted or unquoted values. + + Example:: + text = 'More info at the pyparsing wiki page' + # makeHTMLTags returns pyparsing expressions for the opening and closing tags as a 2-tuple + a,a_end = makeHTMLTags("A") + link_expr = a + SkipTo(a_end)("link_text") + a_end + + for link in link_expr.searchString(text): + # attributes in the tag (like "href" shown here) are also accessible as named results + print(link.link_text, '->', link.href) + prints:: + pyparsing -> http://pyparsing.wikispaces.com + """ + return _makeTags( tagStr, False ) + +def makeXMLTags(tagStr): + """ + Helper to construct opening and closing tag expressions for XML, given a tag name. Matches + tags only in the given upper/lower case. + + Example: similar to L{makeHTMLTags} + """ + return _makeTags( tagStr, True ) + +def withAttribute(*args,**attrDict): + """ + Helper to create a validating parse action to be used with start tags created + with C{L{makeXMLTags}} or C{L{makeHTMLTags}}. Use C{withAttribute} to qualify a starting tag + with a required attribute value, to avoid false matches on common tags such as + C{} or C{
}. + + Call C{withAttribute} with a series of attribute names and values. Specify the list + of filter attributes names and values as: + - keyword arguments, as in C{(align="right")}, or + - as an explicit dict with C{**} operator, when an attribute name is also a Python + reserved word, as in C{**{"class":"Customer", "align":"right"}} + - a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") ) + For attribute names with a namespace prefix, you must use the second form. Attribute + names are matched insensitive to upper/lower case. + + If just testing for C{class} (with or without a namespace), use C{L{withClass}}. + + To verify that the attribute exists, but without specifying a value, pass + C{withAttribute.ANY_VALUE} as the value. + + Example:: + html = ''' +
+ Some text +
1 4 0 1 0
+
1,3 2,3 1,1
+
this has no type
+
+ + ''' + div,div_end = makeHTMLTags("div") + + # only match div tag having a type attribute with value "grid" + div_grid = div().setParseAction(withAttribute(type="grid")) + grid_expr = div_grid + SkipTo(div | div_end)("body") + for grid_header in grid_expr.searchString(html): + print(grid_header.body) + + # construct a match with any div tag having a type attribute, regardless of the value + div_any_type = div().setParseAction(withAttribute(type=withAttribute.ANY_VALUE)) + div_expr = div_any_type + SkipTo(div | div_end)("body") + for div_header in div_expr.searchString(html): + print(div_header.body) + prints:: + 1 4 0 1 0 + + 1 4 0 1 0 + 1,3 2,3 1,1 + """ + if args: + attrs = args[:] + else: + attrs = attrDict.items() + attrs = [(k,v) for k,v in attrs] + def pa(s,l,tokens): + for attrName,attrValue in attrs: + if attrName not in tokens: + raise ParseException(s,l,"no matching attribute " + attrName) + if attrValue != withAttribute.ANY_VALUE and tokens[attrName] != attrValue: + raise ParseException(s,l,"attribute '%s' has value '%s', must be '%s'" % + (attrName, tokens[attrName], attrValue)) + return pa +withAttribute.ANY_VALUE = object() + +def withClass(classname, namespace=''): + """ + Simplified version of C{L{withAttribute}} when matching on a div class - made + difficult because C{class} is a reserved word in Python. + + Example:: + html = ''' +
+ Some text +
1 4 0 1 0
+
1,3 2,3 1,1
+
this <div> has no class
+
+ + ''' + div,div_end = makeHTMLTags("div") + div_grid = div().setParseAction(withClass("grid")) + + grid_expr = div_grid + SkipTo(div | div_end)("body") + for grid_header in grid_expr.searchString(html): + print(grid_header.body) + + div_any_type = div().setParseAction(withClass(withAttribute.ANY_VALUE)) + div_expr = div_any_type + SkipTo(div | div_end)("body") + for div_header in div_expr.searchString(html): + print(div_header.body) + prints:: + 1 4 0 1 0 + + 1 4 0 1 0 + 1,3 2,3 1,1 + """ + classattr = "%s:class" % namespace if namespace else "class" + return withAttribute(**{classattr : classname}) + +opAssoc = _Constants() +opAssoc.LEFT = object() +opAssoc.RIGHT = object() + +def infixNotation( baseExpr, opList, lpar=Suppress('('), rpar=Suppress(')') ): + """ + Helper method for constructing grammars of expressions made up of + operators working in a precedence hierarchy. Operators may be unary or + binary, left- or right-associative. Parse actions can also be attached + to operator expressions. The generated parser will also recognize the use + of parentheses to override operator precedences (see example below). + + Note: if you define a deep operator list, you may see performance issues + when using infixNotation. See L{ParserElement.enablePackrat} for a + mechanism to potentially improve your parser performance. + + Parameters: + - baseExpr - expression representing the most basic element for the nested + - opList - list of tuples, one for each operator precedence level in the + expression grammar; each tuple is of the form + (opExpr, numTerms, rightLeftAssoc, parseAction), where: + - opExpr is the pyparsing expression for the operator; + may also be a string, which will be converted to a Literal; + if numTerms is 3, opExpr is a tuple of two expressions, for the + two operators separating the 3 terms + - numTerms is the number of terms for this operator (must + be 1, 2, or 3) + - rightLeftAssoc is the indicator whether the operator is + right or left associative, using the pyparsing-defined + constants C{opAssoc.RIGHT} and C{opAssoc.LEFT}. + - parseAction is the parse action to be associated with + expressions matching this operator expression (the + parse action tuple member may be omitted); if the parse action + is passed a tuple or list of functions, this is equivalent to + calling C{setParseAction(*fn)} (L{ParserElement.setParseAction}) + - lpar - expression for matching left-parentheses (default=C{Suppress('(')}) + - rpar - expression for matching right-parentheses (default=C{Suppress(')')}) + + Example:: + # simple example of four-function arithmetic with ints and variable names + integer = pyparsing_common.signed_integer + varname = pyparsing_common.identifier + + arith_expr = infixNotation(integer | varname, + [ + ('-', 1, opAssoc.RIGHT), + (oneOf('* /'), 2, opAssoc.LEFT), + (oneOf('+ -'), 2, opAssoc.LEFT), + ]) + + arith_expr.runTests(''' + 5+3*6 + (5+3)*6 + -2--11 + ''', fullDump=False) + prints:: + 5+3*6 + [[5, '+', [3, '*', 6]]] + + (5+3)*6 + [[[5, '+', 3], '*', 6]] + + -2--11 + [[['-', 2], '-', ['-', 11]]] + """ + ret = Forward() + lastExpr = baseExpr | ( lpar + ret + rpar ) + for i,operDef in enumerate(opList): + opExpr,arity,rightLeftAssoc,pa = (operDef + (None,))[:4] + termName = "%s term" % opExpr if arity < 3 else "%s%s term" % opExpr + if arity == 3: + if opExpr is None or len(opExpr) != 2: + raise ValueError("if numterms=3, opExpr must be a tuple or list of two expressions") + opExpr1, opExpr2 = opExpr + thisExpr = Forward().setName(termName) + if rightLeftAssoc == opAssoc.LEFT: + if arity == 1: + matchExpr = FollowedBy(lastExpr + opExpr) + Group( lastExpr + OneOrMore( opExpr ) ) + elif arity == 2: + if opExpr is not None: + matchExpr = FollowedBy(lastExpr + opExpr + lastExpr) + Group( lastExpr + OneOrMore( opExpr + lastExpr ) ) + else: + matchExpr = FollowedBy(lastExpr+lastExpr) + Group( lastExpr + OneOrMore(lastExpr) ) + elif arity == 3: + matchExpr = FollowedBy(lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr) + \ + Group( lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr ) + else: + raise ValueError("operator must be unary (1), binary (2), or ternary (3)") + elif rightLeftAssoc == opAssoc.RIGHT: + if arity == 1: + # try to avoid LR with this extra test + if not isinstance(opExpr, Optional): + opExpr = Optional(opExpr) + matchExpr = FollowedBy(opExpr.expr + thisExpr) + Group( opExpr + thisExpr ) + elif arity == 2: + if opExpr is not None: + matchExpr = FollowedBy(lastExpr + opExpr + thisExpr) + Group( lastExpr + OneOrMore( opExpr + thisExpr ) ) + else: + matchExpr = FollowedBy(lastExpr + thisExpr) + Group( lastExpr + OneOrMore( thisExpr ) ) + elif arity == 3: + matchExpr = FollowedBy(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr) + \ + Group( lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr ) + else: + raise ValueError("operator must be unary (1), binary (2), or ternary (3)") + else: + raise ValueError("operator must indicate right or left associativity") + if pa: + if isinstance(pa, (tuple, list)): + matchExpr.setParseAction(*pa) + else: + matchExpr.setParseAction(pa) + thisExpr <<= ( matchExpr.setName(termName) | lastExpr ) + lastExpr = thisExpr + ret <<= lastExpr + return ret + +operatorPrecedence = infixNotation +"""(Deprecated) Former name of C{L{infixNotation}}, will be dropped in a future release.""" + +dblQuotedString = Combine(Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*')+'"').setName("string enclosed in double quotes") +sglQuotedString = Combine(Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*")+"'").setName("string enclosed in single quotes") +quotedString = Combine(Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*')+'"'| + Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*")+"'").setName("quotedString using single or double quotes") +unicodeString = Combine(_L('u') + quotedString.copy()).setName("unicode string literal") + +def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString.copy()): + """ + Helper method for defining nested lists enclosed in opening and closing + delimiters ("(" and ")" are the default). + + Parameters: + - opener - opening character for a nested list (default=C{"("}); can also be a pyparsing expression + - closer - closing character for a nested list (default=C{")"}); can also be a pyparsing expression + - content - expression for items within the nested lists (default=C{None}) + - ignoreExpr - expression for ignoring opening and closing delimiters (default=C{quotedString}) + + If an expression is not provided for the content argument, the nested + expression will capture all whitespace-delimited content between delimiters + as a list of separate values. + + Use the C{ignoreExpr} argument to define expressions that may contain + opening or closing characters that should not be treated as opening + or closing characters for nesting, such as quotedString or a comment + expression. Specify multiple expressions using an C{L{Or}} or C{L{MatchFirst}}. + The default is L{quotedString}, but if no expressions are to be ignored, + then pass C{None} for this argument. + + Example:: + data_type = oneOf("void int short long char float double") + decl_data_type = Combine(data_type + Optional(Word('*'))) + ident = Word(alphas+'_', alphanums+'_') + number = pyparsing_common.number + arg = Group(decl_data_type + ident) + LPAR,RPAR = map(Suppress, "()") + + code_body = nestedExpr('{', '}', ignoreExpr=(quotedString | cStyleComment)) + + c_function = (decl_data_type("type") + + ident("name") + + LPAR + Optional(delimitedList(arg), [])("args") + RPAR + + code_body("body")) + c_function.ignore(cStyleComment) + + source_code = ''' + int is_odd(int x) { + return (x%2); + } + + int dec_to_hex(char hchar) { + if (hchar >= '0' && hchar <= '9') { + return (ord(hchar)-ord('0')); + } else { + return (10+ord(hchar)-ord('A')); + } + } + ''' + for func in c_function.searchString(source_code): + print("%(name)s (%(type)s) args: %(args)s" % func) + + prints:: + is_odd (int) args: [['int', 'x']] + dec_to_hex (int) args: [['char', 'hchar']] + """ + if opener == closer: + raise ValueError("opening and closing strings cannot be the same") + if content is None: + if isinstance(opener,basestring) and isinstance(closer,basestring): + if len(opener) == 1 and len(closer)==1: + if ignoreExpr is not None: + content = (Combine(OneOrMore(~ignoreExpr + + CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS,exact=1)) + ).setParseAction(lambda t:t[0].strip())) + else: + content = (empty.copy()+CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS + ).setParseAction(lambda t:t[0].strip())) + else: + if ignoreExpr is not None: + content = (Combine(OneOrMore(~ignoreExpr + + ~Literal(opener) + ~Literal(closer) + + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS,exact=1)) + ).setParseAction(lambda t:t[0].strip())) + else: + content = (Combine(OneOrMore(~Literal(opener) + ~Literal(closer) + + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS,exact=1)) + ).setParseAction(lambda t:t[0].strip())) + else: + raise ValueError("opening and closing arguments must be strings if no content expression is given") + ret = Forward() + if ignoreExpr is not None: + ret <<= Group( Suppress(opener) + ZeroOrMore( ignoreExpr | ret | content ) + Suppress(closer) ) + else: + ret <<= Group( Suppress(opener) + ZeroOrMore( ret | content ) + Suppress(closer) ) + ret.setName('nested %s%s expression' % (opener,closer)) + return ret + +def indentedBlock(blockStatementExpr, indentStack, indent=True): + """ + Helper method for defining space-delimited indentation blocks, such as + those used to define block statements in Python source code. + + Parameters: + - blockStatementExpr - expression defining syntax of statement that + is repeated within the indented block + - indentStack - list created by caller to manage indentation stack + (multiple statementWithIndentedBlock expressions within a single grammar + should share a common indentStack) + - indent - boolean indicating whether block must be indented beyond the + the current level; set to False for block of left-most statements + (default=C{True}) + + A valid block must contain at least one C{blockStatement}. + + Example:: + data = ''' + def A(z): + A1 + B = 100 + G = A2 + A2 + A3 + B + def BB(a,b,c): + BB1 + def BBA(): + bba1 + bba2 + bba3 + C + D + def spam(x,y): + def eggs(z): + pass + ''' + + + indentStack = [1] + stmt = Forward() + + identifier = Word(alphas, alphanums) + funcDecl = ("def" + identifier + Group( "(" + Optional( delimitedList(identifier) ) + ")" ) + ":") + func_body = indentedBlock(stmt, indentStack) + funcDef = Group( funcDecl + func_body ) + + rvalue = Forward() + funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")") + rvalue << (funcCall | identifier | Word(nums)) + assignment = Group(identifier + "=" + rvalue) + stmt << ( funcDef | assignment | identifier ) + + module_body = OneOrMore(stmt) + + parseTree = module_body.parseString(data) + parseTree.pprint() + prints:: + [['def', + 'A', + ['(', 'z', ')'], + ':', + [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]], + 'B', + ['def', + 'BB', + ['(', 'a', 'b', 'c', ')'], + ':', + [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]], + 'C', + 'D', + ['def', + 'spam', + ['(', 'x', 'y', ')'], + ':', + [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]] + """ + def checkPeerIndent(s,l,t): + if l >= len(s): return + curCol = col(l,s) + if curCol != indentStack[-1]: + if curCol > indentStack[-1]: + raise ParseFatalException(s,l,"illegal nesting") + raise ParseException(s,l,"not a peer entry") + + def checkSubIndent(s,l,t): + curCol = col(l,s) + if curCol > indentStack[-1]: + indentStack.append( curCol ) + else: + raise ParseException(s,l,"not a subentry") + + def checkUnindent(s,l,t): + if l >= len(s): return + curCol = col(l,s) + if not(indentStack and curCol < indentStack[-1] and curCol <= indentStack[-2]): + raise ParseException(s,l,"not an unindent") + indentStack.pop() + + NL = OneOrMore(LineEnd().setWhitespaceChars("\t ").suppress()) + INDENT = (Empty() + Empty().setParseAction(checkSubIndent)).setName('INDENT') + PEER = Empty().setParseAction(checkPeerIndent).setName('') + UNDENT = Empty().setParseAction(checkUnindent).setName('UNINDENT') + if indent: + smExpr = Group( Optional(NL) + + #~ FollowedBy(blockStatementExpr) + + INDENT + (OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) + UNDENT) + else: + smExpr = Group( Optional(NL) + + (OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) ) + blockStatementExpr.ignore(_bslash + LineEnd()) + return smExpr.setName('indented block') + +alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]") +punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]") + +anyOpenTag,anyCloseTag = makeHTMLTags(Word(alphas,alphanums+"_:").setName('any tag')) +_htmlEntityMap = dict(zip("gt lt amp nbsp quot apos".split(),'><& "\'')) +commonHTMLEntity = Regex('&(?P' + '|'.join(_htmlEntityMap.keys()) +");").setName("common HTML entity") +def replaceHTMLEntity(t): + """Helper parser action to replace common HTML entities with their special characters""" + return _htmlEntityMap.get(t.entity) + +# it's easy to get these comment structures wrong - they're very common, so may as well make them available +cStyleComment = Combine(Regex(r"/\*(?:[^*]|\*(?!/))*") + '*/').setName("C style comment") +"Comment of the form C{/* ... */}" + +htmlComment = Regex(r"").setName("HTML comment") +"Comment of the form C{}" + +restOfLine = Regex(r".*").leaveWhitespace().setName("rest of line") +dblSlashComment = Regex(r"//(?:\\\n|[^\n])*").setName("// comment") +"Comment of the form C{// ... (to end of line)}" + +cppStyleComment = Combine(Regex(r"/\*(?:[^*]|\*(?!/))*") + '*/'| dblSlashComment).setName("C++ style comment") +"Comment of either form C{L{cStyleComment}} or C{L{dblSlashComment}}" + +javaStyleComment = cppStyleComment +"Same as C{L{cppStyleComment}}" + +pythonStyleComment = Regex(r"#.*").setName("Python style comment") +"Comment of the form C{# ... (to end of line)}" + +_commasepitem = Combine(OneOrMore(Word(printables, excludeChars=',') + + Optional( Word(" \t") + + ~Literal(",") + ~LineEnd() ) ) ).streamline().setName("commaItem") +commaSeparatedList = delimitedList( Optional( quotedString.copy() | _commasepitem, default="") ).setName("commaSeparatedList") +"""(Deprecated) Predefined expression of 1 or more printable words or quoted strings, separated by commas. + This expression is deprecated in favor of L{pyparsing_common.comma_separated_list}.""" + +# some other useful expressions - using lower-case class name since we are really using this as a namespace +class pyparsing_common: + """ + Here are some common low-level expressions that may be useful in jump-starting parser development: + - numeric forms (L{integers}, L{reals}, L{scientific notation}) + - common L{programming identifiers} + - network addresses (L{MAC}, L{IPv4}, L{IPv6}) + - ISO8601 L{dates} and L{datetime} + - L{UUID} + - L{comma-separated list} + Parse actions: + - C{L{convertToInteger}} + - C{L{convertToFloat}} + - C{L{convertToDate}} + - C{L{convertToDatetime}} + - C{L{stripHTMLTags}} + - C{L{upcaseTokens}} + - C{L{downcaseTokens}} + + Example:: + pyparsing_common.number.runTests(''' + # any int or real number, returned as the appropriate type + 100 + -100 + +100 + 3.14159 + 6.02e23 + 1e-12 + ''') + + pyparsing_common.fnumber.runTests(''' + # any int or real number, returned as float + 100 + -100 + +100 + 3.14159 + 6.02e23 + 1e-12 + ''') + + pyparsing_common.hex_integer.runTests(''' + # hex numbers + 100 + FF + ''') + + pyparsing_common.fraction.runTests(''' + # fractions + 1/2 + -3/4 + ''') + + pyparsing_common.mixed_integer.runTests(''' + # mixed fractions + 1 + 1/2 + -3/4 + 1-3/4 + ''') + + import uuid + pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID)) + pyparsing_common.uuid.runTests(''' + # uuid + 12345678-1234-5678-1234-567812345678 + ''') + prints:: + # any int or real number, returned as the appropriate type + 100 + [100] + + -100 + [-100] + + +100 + [100] + + 3.14159 + [3.14159] + + 6.02e23 + [6.02e+23] + + 1e-12 + [1e-12] + + # any int or real number, returned as float + 100 + [100.0] + + -100 + [-100.0] + + +100 + [100.0] + + 3.14159 + [3.14159] + + 6.02e23 + [6.02e+23] + + 1e-12 + [1e-12] + + # hex numbers + 100 + [256] + + FF + [255] + + # fractions + 1/2 + [0.5] + + -3/4 + [-0.75] + + # mixed fractions + 1 + [1] + + 1/2 + [0.5] + + -3/4 + [-0.75] + + 1-3/4 + [1.75] + + # uuid + 12345678-1234-5678-1234-567812345678 + [UUID('12345678-1234-5678-1234-567812345678')] + """ + + convertToInteger = tokenMap(int) + """ + Parse action for converting parsed integers to Python int + """ + + convertToFloat = tokenMap(float) + """ + Parse action for converting parsed numbers to Python float + """ + + integer = Word(nums).setName("integer").setParseAction(convertToInteger) + """expression that parses an unsigned integer, returns an int""" + + hex_integer = Word(hexnums).setName("hex integer").setParseAction(tokenMap(int,16)) + """expression that parses a hexadecimal integer, returns an int""" + + signed_integer = Regex(r'[+-]?\d+').setName("signed integer").setParseAction(convertToInteger) + """expression that parses an integer with optional leading sign, returns an int""" + + fraction = (signed_integer().setParseAction(convertToFloat) + '/' + signed_integer().setParseAction(convertToFloat)).setName("fraction") + """fractional expression of an integer divided by an integer, returns a float""" + fraction.addParseAction(lambda t: t[0]/t[-1]) + + mixed_integer = (fraction | signed_integer + Optional(Optional('-').suppress() + fraction)).setName("fraction or mixed integer-fraction") + """mixed integer of the form 'integer - fraction', with optional leading integer, returns float""" + mixed_integer.addParseAction(sum) + + real = Regex(r'[+-]?\d+\.\d*').setName("real number").setParseAction(convertToFloat) + """expression that parses a floating point number and returns a float""" + + sci_real = Regex(r'[+-]?\d+([eE][+-]?\d+|\.\d*([eE][+-]?\d+)?)').setName("real number with scientific notation").setParseAction(convertToFloat) + """expression that parses a floating point number with optional scientific notation and returns a float""" + + # streamlining this expression makes the docs nicer-looking + number = (sci_real | real | signed_integer).streamline() + """any numeric expression, returns the corresponding Python type""" + + fnumber = Regex(r'[+-]?\d+\.?\d*([eE][+-]?\d+)?').setName("fnumber").setParseAction(convertToFloat) + """any int or real number, returned as float""" + + identifier = Word(alphas+'_', alphanums+'_').setName("identifier") + """typical code identifier (leading alpha or '_', followed by 0 or more alphas, nums, or '_')""" + + ipv4_address = Regex(r'(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}').setName("IPv4 address") + "IPv4 address (C{0.0.0.0 - 255.255.255.255})" + + _ipv6_part = Regex(r'[0-9a-fA-F]{1,4}').setName("hex_integer") + _full_ipv6_address = (_ipv6_part + (':' + _ipv6_part)*7).setName("full IPv6 address") + _short_ipv6_address = (Optional(_ipv6_part + (':' + _ipv6_part)*(0,6)) + "::" + Optional(_ipv6_part + (':' + _ipv6_part)*(0,6))).setName("short IPv6 address") + _short_ipv6_address.addCondition(lambda t: sum(1 for tt in t if pyparsing_common._ipv6_part.matches(tt)) < 8) + _mixed_ipv6_address = ("::ffff:" + ipv4_address).setName("mixed IPv6 address") + ipv6_address = Combine((_full_ipv6_address | _mixed_ipv6_address | _short_ipv6_address).setName("IPv6 address")).setName("IPv6 address") + "IPv6 address (long, short, or mixed form)" + + mac_address = Regex(r'[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\1[0-9a-fA-F]{2}){4}').setName("MAC address") + "MAC address xx:xx:xx:xx:xx (may also have '-' or '.' delimiters)" + + @staticmethod + def convertToDate(fmt="%Y-%m-%d"): + """ + Helper to create a parse action for converting parsed date string to Python datetime.date + + Params - + - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"}) + + Example:: + date_expr = pyparsing_common.iso8601_date.copy() + date_expr.setParseAction(pyparsing_common.convertToDate()) + print(date_expr.parseString("1999-12-31")) + prints:: + [datetime.date(1999, 12, 31)] + """ + def cvt_fn(s,l,t): + try: + return datetime.strptime(t[0], fmt).date() + except ValueError as ve: + raise ParseException(s, l, str(ve)) + return cvt_fn + + @staticmethod + def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"): + """ + Helper to create a parse action for converting parsed datetime string to Python datetime.datetime + + Params - + - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%dT%H:%M:%S.%f"}) + + Example:: + dt_expr = pyparsing_common.iso8601_datetime.copy() + dt_expr.setParseAction(pyparsing_common.convertToDatetime()) + print(dt_expr.parseString("1999-12-31T23:59:59.999")) + prints:: + [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)] + """ + def cvt_fn(s,l,t): + try: + return datetime.strptime(t[0], fmt) + except ValueError as ve: + raise ParseException(s, l, str(ve)) + return cvt_fn + + iso8601_date = Regex(r'(?P\d{4})(?:-(?P\d\d)(?:-(?P\d\d))?)?').setName("ISO8601 date") + "ISO8601 date (C{yyyy-mm-dd})" + + iso8601_datetime = Regex(r'(?P\d{4})-(?P\d\d)-(?P\d\d)[T ](?P\d\d):(?P\d\d)(:(?P\d\d(\.\d*)?)?)?(?PZ|[+-]\d\d:?\d\d)?').setName("ISO8601 datetime") + "ISO8601 datetime (C{yyyy-mm-ddThh:mm:ss.s(Z|+-00:00)}) - trailing seconds, milliseconds, and timezone optional; accepts separating C{'T'} or C{' '}" + + uuid = Regex(r'[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}').setName("UUID") + "UUID (C{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx})" + + _html_stripper = anyOpenTag.suppress() | anyCloseTag.suppress() + @staticmethod + def stripHTMLTags(s, l, tokens): + """ + Parse action to remove HTML tags from web page HTML source + + Example:: + # strip HTML links from normal text + text = 'More info at the
pyparsing wiki page' + td,td_end = makeHTMLTags("TD") + table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end + + print(table_text.parseString(text).body) # -> 'More info at the pyparsing wiki page' + """ + return pyparsing_common._html_stripper.transformString(tokens[0]) + + _commasepitem = Combine(OneOrMore(~Literal(",") + ~LineEnd() + Word(printables, excludeChars=',') + + Optional( White(" \t") ) ) ).streamline().setName("commaItem") + comma_separated_list = delimitedList( Optional( quotedString.copy() | _commasepitem, default="") ).setName("comma separated list") + """Predefined expression of 1 or more printable words or quoted strings, separated by commas.""" + + upcaseTokens = staticmethod(tokenMap(lambda t: _ustr(t).upper())) + """Parse action to convert tokens to upper case.""" + + downcaseTokens = staticmethod(tokenMap(lambda t: _ustr(t).lower())) + """Parse action to convert tokens to lower case.""" + + +if __name__ == "__main__": + + selectToken = CaselessLiteral("select") + fromToken = CaselessLiteral("from") + + ident = Word(alphas, alphanums + "_$") + + columnName = delimitedList(ident, ".", combine=True).setParseAction(upcaseTokens) + columnNameList = Group(delimitedList(columnName)).setName("columns") + columnSpec = ('*' | columnNameList) + + tableName = delimitedList(ident, ".", combine=True).setParseAction(upcaseTokens) + tableNameList = Group(delimitedList(tableName)).setName("tables") + + simpleSQL = selectToken("command") + columnSpec("columns") + fromToken + tableNameList("tables") + + # demo runTests method, including embedded comments in test string + simpleSQL.runTests(""" + # '*' as column list and dotted table name + select * from SYS.XYZZY + + # caseless match on "SELECT", and casts back to "select" + SELECT * from XYZZY, ABC + + # list of column names, and mixed case SELECT keyword + Select AA,BB,CC from Sys.dual + + # multiple tables + Select A, B, C from Sys.dual, Table2 + + # invalid SELECT keyword - should fail + Xelect A, B, C from Sys.dual + + # incomplete command - should fail + Select + + # invalid column name - should fail + Select ^^^ frox Sys.dual + + """) + + pyparsing_common.number.runTests(""" + 100 + -100 + +100 + 3.14159 + 6.02e23 + 1e-12 + """) + + # any int or real number, returned as float + pyparsing_common.fnumber.runTests(""" + 100 + -100 + +100 + 3.14159 + 6.02e23 + 1e-12 + """) + + pyparsing_common.hex_integer.runTests(""" + 100 + FF + """) + + import uuid + pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID)) + pyparsing_common.uuid.runTests(""" + 12345678-1234-5678-1234-567812345678 + """) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_vendor/six.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_vendor/six.py new file mode 100644 index 0000000000000000000000000000000000000000..190c0239cd7d7af82a6e0cbc8d68053fa2e3dfaf --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/_vendor/six.py @@ -0,0 +1,868 @@ +"""Utilities for writing code that runs on Python 2 and 3""" + +# Copyright (c) 2010-2015 Benjamin Peterson +# +# 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. + +from __future__ import absolute_import + +import functools +import itertools +import operator +import sys +import types + +__author__ = "Benjamin Peterson " +__version__ = "1.10.0" + + +# Useful for very coarse version differentiation. +PY2 = sys.version_info[0] == 2 +PY3 = sys.version_info[0] == 3 +PY34 = sys.version_info[0:2] >= (3, 4) + +if PY3: + string_types = str, + integer_types = int, + class_types = type, + text_type = str + binary_type = bytes + + MAXSIZE = sys.maxsize +else: + string_types = basestring, + integer_types = (int, long) + class_types = (type, types.ClassType) + text_type = unicode + binary_type = str + + if sys.platform.startswith("java"): + # Jython always uses 32 bits. + MAXSIZE = int((1 << 31) - 1) + else: + # It's possible to have sizeof(long) != sizeof(Py_ssize_t). + class X(object): + + def __len__(self): + return 1 << 31 + try: + len(X()) + except OverflowError: + # 32-bit + MAXSIZE = int((1 << 31) - 1) + else: + # 64-bit + MAXSIZE = int((1 << 63) - 1) + del X + + +def _add_doc(func, doc): + """Add documentation to a function.""" + func.__doc__ = doc + + +def _import_module(name): + """Import module, returning the module after the last dot.""" + __import__(name) + return sys.modules[name] + + +class _LazyDescr(object): + + def __init__(self, name): + self.name = name + + def __get__(self, obj, tp): + result = self._resolve() + setattr(obj, self.name, result) # Invokes __set__. + try: + # This is a bit ugly, but it avoids running this again by + # removing this descriptor. + delattr(obj.__class__, self.name) + except AttributeError: + pass + return result + + +class MovedModule(_LazyDescr): + + def __init__(self, name, old, new=None): + super(MovedModule, self).__init__(name) + if PY3: + if new is None: + new = name + self.mod = new + else: + self.mod = old + + def _resolve(self): + return _import_module(self.mod) + + def __getattr__(self, attr): + _module = self._resolve() + value = getattr(_module, attr) + setattr(self, attr, value) + return value + + +class _LazyModule(types.ModuleType): + + def __init__(self, name): + super(_LazyModule, self).__init__(name) + self.__doc__ = self.__class__.__doc__ + + def __dir__(self): + attrs = ["__doc__", "__name__"] + attrs += [attr.name for attr in self._moved_attributes] + return attrs + + # Subclasses should override this + _moved_attributes = [] + + +class MovedAttribute(_LazyDescr): + + def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): + super(MovedAttribute, self).__init__(name) + if PY3: + if new_mod is None: + new_mod = name + self.mod = new_mod + if new_attr is None: + if old_attr is None: + new_attr = name + else: + new_attr = old_attr + self.attr = new_attr + else: + self.mod = old_mod + if old_attr is None: + old_attr = name + self.attr = old_attr + + def _resolve(self): + module = _import_module(self.mod) + return getattr(module, self.attr) + + +class _SixMetaPathImporter(object): + + """ + A meta path importer to import six.moves and its submodules. + + This class implements a PEP302 finder and loader. It should be compatible + with Python 2.5 and all existing versions of Python3 + """ + + def __init__(self, six_module_name): + self.name = six_module_name + self.known_modules = {} + + def _add_module(self, mod, *fullnames): + for fullname in fullnames: + self.known_modules[self.name + "." + fullname] = mod + + def _get_module(self, fullname): + return self.known_modules[self.name + "." + fullname] + + def find_module(self, fullname, path=None): + if fullname in self.known_modules: + return self + return None + + def __get_module(self, fullname): + try: + return self.known_modules[fullname] + except KeyError: + raise ImportError("This loader does not know module " + fullname) + + def load_module(self, fullname): + try: + # in case of a reload + return sys.modules[fullname] + except KeyError: + pass + mod = self.__get_module(fullname) + if isinstance(mod, MovedModule): + mod = mod._resolve() + else: + mod.__loader__ = self + sys.modules[fullname] = mod + return mod + + def is_package(self, fullname): + """ + Return true, if the named module is a package. + + We need this method to get correct spec objects with + Python 3.4 (see PEP451) + """ + return hasattr(self.__get_module(fullname), "__path__") + + def get_code(self, fullname): + """Return None + + Required, if is_package is implemented""" + self.__get_module(fullname) # eventually raises ImportError + return None + get_source = get_code # same as get_code + +_importer = _SixMetaPathImporter(__name__) + + +class _MovedItems(_LazyModule): + + """Lazy loading of moved objects""" + __path__ = [] # mark as package + + +_moved_attributes = [ + MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), + MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), + MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), + MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), + MovedAttribute("intern", "__builtin__", "sys"), + MovedAttribute("map", "itertools", "builtins", "imap", "map"), + MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), + MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), + MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), + MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"), + MovedAttribute("reduce", "__builtin__", "functools"), + MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), + MovedAttribute("StringIO", "StringIO", "io"), + MovedAttribute("UserDict", "UserDict", "collections"), + MovedAttribute("UserList", "UserList", "collections"), + MovedAttribute("UserString", "UserString", "collections"), + MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), + MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), + MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), + MovedModule("builtins", "__builtin__"), + MovedModule("configparser", "ConfigParser"), + MovedModule("copyreg", "copy_reg"), + MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), + MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), + MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), + MovedModule("http_cookies", "Cookie", "http.cookies"), + MovedModule("html_entities", "htmlentitydefs", "html.entities"), + MovedModule("html_parser", "HTMLParser", "html.parser"), + MovedModule("http_client", "httplib", "http.client"), + MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), + MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), + MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), + MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), + MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), + MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), + MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), + MovedModule("cPickle", "cPickle", "pickle"), + MovedModule("queue", "Queue"), + MovedModule("reprlib", "repr"), + MovedModule("socketserver", "SocketServer"), + MovedModule("_thread", "thread", "_thread"), + MovedModule("tkinter", "Tkinter"), + MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), + MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), + MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), + MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), + MovedModule("tkinter_tix", "Tix", "tkinter.tix"), + MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), + MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), + MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), + MovedModule("tkinter_colorchooser", "tkColorChooser", + "tkinter.colorchooser"), + MovedModule("tkinter_commondialog", "tkCommonDialog", + "tkinter.commondialog"), + MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), + MovedModule("tkinter_font", "tkFont", "tkinter.font"), + MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), + MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", + "tkinter.simpledialog"), + MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), + MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), + MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), + MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), + MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), + MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), +] +# Add windows specific modules. +if sys.platform == "win32": + _moved_attributes += [ + MovedModule("winreg", "_winreg"), + ] + +for attr in _moved_attributes: + setattr(_MovedItems, attr.name, attr) + if isinstance(attr, MovedModule): + _importer._add_module(attr, "moves." + attr.name) +del attr + +_MovedItems._moved_attributes = _moved_attributes + +moves = _MovedItems(__name__ + ".moves") +_importer._add_module(moves, "moves") + + +class Module_six_moves_urllib_parse(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_parse""" + + +_urllib_parse_moved_attributes = [ + MovedAttribute("ParseResult", "urlparse", "urllib.parse"), + MovedAttribute("SplitResult", "urlparse", "urllib.parse"), + MovedAttribute("parse_qs", "urlparse", "urllib.parse"), + MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), + MovedAttribute("urldefrag", "urlparse", "urllib.parse"), + MovedAttribute("urljoin", "urlparse", "urllib.parse"), + MovedAttribute("urlparse", "urlparse", "urllib.parse"), + MovedAttribute("urlsplit", "urlparse", "urllib.parse"), + MovedAttribute("urlunparse", "urlparse", "urllib.parse"), + MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), + MovedAttribute("quote", "urllib", "urllib.parse"), + MovedAttribute("quote_plus", "urllib", "urllib.parse"), + MovedAttribute("unquote", "urllib", "urllib.parse"), + MovedAttribute("unquote_plus", "urllib", "urllib.parse"), + MovedAttribute("urlencode", "urllib", "urllib.parse"), + MovedAttribute("splitquery", "urllib", "urllib.parse"), + MovedAttribute("splittag", "urllib", "urllib.parse"), + MovedAttribute("splituser", "urllib", "urllib.parse"), + MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), + MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), + MovedAttribute("uses_params", "urlparse", "urllib.parse"), + MovedAttribute("uses_query", "urlparse", "urllib.parse"), + MovedAttribute("uses_relative", "urlparse", "urllib.parse"), +] +for attr in _urllib_parse_moved_attributes: + setattr(Module_six_moves_urllib_parse, attr.name, attr) +del attr + +Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes + +_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), + "moves.urllib_parse", "moves.urllib.parse") + + +class Module_six_moves_urllib_error(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_error""" + + +_urllib_error_moved_attributes = [ + MovedAttribute("URLError", "urllib2", "urllib.error"), + MovedAttribute("HTTPError", "urllib2", "urllib.error"), + MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), +] +for attr in _urllib_error_moved_attributes: + setattr(Module_six_moves_urllib_error, attr.name, attr) +del attr + +Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes + +_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), + "moves.urllib_error", "moves.urllib.error") + + +class Module_six_moves_urllib_request(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_request""" + + +_urllib_request_moved_attributes = [ + MovedAttribute("urlopen", "urllib2", "urllib.request"), + MovedAttribute("install_opener", "urllib2", "urllib.request"), + MovedAttribute("build_opener", "urllib2", "urllib.request"), + MovedAttribute("pathname2url", "urllib", "urllib.request"), + MovedAttribute("url2pathname", "urllib", "urllib.request"), + MovedAttribute("getproxies", "urllib", "urllib.request"), + MovedAttribute("Request", "urllib2", "urllib.request"), + MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), + MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), + MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), + MovedAttribute("BaseHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), + MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), + MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), + MovedAttribute("FileHandler", "urllib2", "urllib.request"), + MovedAttribute("FTPHandler", "urllib2", "urllib.request"), + MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), + MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), + MovedAttribute("urlretrieve", "urllib", "urllib.request"), + MovedAttribute("urlcleanup", "urllib", "urllib.request"), + MovedAttribute("URLopener", "urllib", "urllib.request"), + MovedAttribute("FancyURLopener", "urllib", "urllib.request"), + MovedAttribute("proxy_bypass", "urllib", "urllib.request"), +] +for attr in _urllib_request_moved_attributes: + setattr(Module_six_moves_urllib_request, attr.name, attr) +del attr + +Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes + +_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), + "moves.urllib_request", "moves.urllib.request") + + +class Module_six_moves_urllib_response(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_response""" + + +_urllib_response_moved_attributes = [ + MovedAttribute("addbase", "urllib", "urllib.response"), + MovedAttribute("addclosehook", "urllib", "urllib.response"), + MovedAttribute("addinfo", "urllib", "urllib.response"), + MovedAttribute("addinfourl", "urllib", "urllib.response"), +] +for attr in _urllib_response_moved_attributes: + setattr(Module_six_moves_urllib_response, attr.name, attr) +del attr + +Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes + +_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), + "moves.urllib_response", "moves.urllib.response") + + +class Module_six_moves_urllib_robotparser(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_robotparser""" + + +_urllib_robotparser_moved_attributes = [ + MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), +] +for attr in _urllib_robotparser_moved_attributes: + setattr(Module_six_moves_urllib_robotparser, attr.name, attr) +del attr + +Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes + +_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), + "moves.urllib_robotparser", "moves.urllib.robotparser") + + +class Module_six_moves_urllib(types.ModuleType): + + """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" + __path__ = [] # mark as package + parse = _importer._get_module("moves.urllib_parse") + error = _importer._get_module("moves.urllib_error") + request = _importer._get_module("moves.urllib_request") + response = _importer._get_module("moves.urllib_response") + robotparser = _importer._get_module("moves.urllib_robotparser") + + def __dir__(self): + return ['parse', 'error', 'request', 'response', 'robotparser'] + +_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), + "moves.urllib") + + +def add_move(move): + """Add an item to six.moves.""" + setattr(_MovedItems, move.name, move) + + +def remove_move(name): + """Remove item from six.moves.""" + try: + delattr(_MovedItems, name) + except AttributeError: + try: + del moves.__dict__[name] + except KeyError: + raise AttributeError("no such move, %r" % (name,)) + + +if PY3: + _meth_func = "__func__" + _meth_self = "__self__" + + _func_closure = "__closure__" + _func_code = "__code__" + _func_defaults = "__defaults__" + _func_globals = "__globals__" +else: + _meth_func = "im_func" + _meth_self = "im_self" + + _func_closure = "func_closure" + _func_code = "func_code" + _func_defaults = "func_defaults" + _func_globals = "func_globals" + + +try: + advance_iterator = next +except NameError: + def advance_iterator(it): + return it.next() +next = advance_iterator + + +try: + callable = callable +except NameError: + def callable(obj): + return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) + + +if PY3: + def get_unbound_function(unbound): + return unbound + + create_bound_method = types.MethodType + + def create_unbound_method(func, cls): + return func + + Iterator = object +else: + def get_unbound_function(unbound): + return unbound.im_func + + def create_bound_method(func, obj): + return types.MethodType(func, obj, obj.__class__) + + def create_unbound_method(func, cls): + return types.MethodType(func, None, cls) + + class Iterator(object): + + def next(self): + return type(self).__next__(self) + + callable = callable +_add_doc(get_unbound_function, + """Get the function out of a possibly unbound function""") + + +get_method_function = operator.attrgetter(_meth_func) +get_method_self = operator.attrgetter(_meth_self) +get_function_closure = operator.attrgetter(_func_closure) +get_function_code = operator.attrgetter(_func_code) +get_function_defaults = operator.attrgetter(_func_defaults) +get_function_globals = operator.attrgetter(_func_globals) + + +if PY3: + def iterkeys(d, **kw): + return iter(d.keys(**kw)) + + def itervalues(d, **kw): + return iter(d.values(**kw)) + + def iteritems(d, **kw): + return iter(d.items(**kw)) + + def iterlists(d, **kw): + return iter(d.lists(**kw)) + + viewkeys = operator.methodcaller("keys") + + viewvalues = operator.methodcaller("values") + + viewitems = operator.methodcaller("items") +else: + def iterkeys(d, **kw): + return d.iterkeys(**kw) + + def itervalues(d, **kw): + return d.itervalues(**kw) + + def iteritems(d, **kw): + return d.iteritems(**kw) + + def iterlists(d, **kw): + return d.iterlists(**kw) + + viewkeys = operator.methodcaller("viewkeys") + + viewvalues = operator.methodcaller("viewvalues") + + viewitems = operator.methodcaller("viewitems") + +_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") +_add_doc(itervalues, "Return an iterator over the values of a dictionary.") +_add_doc(iteritems, + "Return an iterator over the (key, value) pairs of a dictionary.") +_add_doc(iterlists, + "Return an iterator over the (key, [values]) pairs of a dictionary.") + + +if PY3: + def b(s): + return s.encode("latin-1") + + def u(s): + return s + unichr = chr + import struct + int2byte = struct.Struct(">B").pack + del struct + byte2int = operator.itemgetter(0) + indexbytes = operator.getitem + iterbytes = iter + import io + StringIO = io.StringIO + BytesIO = io.BytesIO + _assertCountEqual = "assertCountEqual" + if sys.version_info[1] <= 1: + _assertRaisesRegex = "assertRaisesRegexp" + _assertRegex = "assertRegexpMatches" + else: + _assertRaisesRegex = "assertRaisesRegex" + _assertRegex = "assertRegex" +else: + def b(s): + return s + # Workaround for standalone backslash + + def u(s): + return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") + unichr = unichr + int2byte = chr + + def byte2int(bs): + return ord(bs[0]) + + def indexbytes(buf, i): + return ord(buf[i]) + iterbytes = functools.partial(itertools.imap, ord) + import StringIO + StringIO = BytesIO = StringIO.StringIO + _assertCountEqual = "assertItemsEqual" + _assertRaisesRegex = "assertRaisesRegexp" + _assertRegex = "assertRegexpMatches" +_add_doc(b, """Byte literal""") +_add_doc(u, """Text literal""") + + +def assertCountEqual(self, *args, **kwargs): + return getattr(self, _assertCountEqual)(*args, **kwargs) + + +def assertRaisesRegex(self, *args, **kwargs): + return getattr(self, _assertRaisesRegex)(*args, **kwargs) + + +def assertRegex(self, *args, **kwargs): + return getattr(self, _assertRegex)(*args, **kwargs) + + +if PY3: + exec_ = getattr(moves.builtins, "exec") + + def reraise(tp, value, tb=None): + if value is None: + value = tp() + if value.__traceback__ is not tb: + raise value.with_traceback(tb) + raise value + +else: + def exec_(_code_, _globs_=None, _locs_=None): + """Execute code in a namespace.""" + if _globs_ is None: + frame = sys._getframe(1) + _globs_ = frame.f_globals + if _locs_ is None: + _locs_ = frame.f_locals + del frame + elif _locs_ is None: + _locs_ = _globs_ + exec("""exec _code_ in _globs_, _locs_""") + + exec_("""def reraise(tp, value, tb=None): + raise tp, value, tb +""") + + +if sys.version_info[:2] == (3, 2): + exec_("""def raise_from(value, from_value): + if from_value is None: + raise value + raise value from from_value +""") +elif sys.version_info[:2] > (3, 2): + exec_("""def raise_from(value, from_value): + raise value from from_value +""") +else: + def raise_from(value, from_value): + raise value + + +print_ = getattr(moves.builtins, "print", None) +if print_ is None: + def print_(*args, **kwargs): + """The new-style print function for Python 2.4 and 2.5.""" + fp = kwargs.pop("file", sys.stdout) + if fp is None: + return + + def write(data): + if not isinstance(data, basestring): + data = str(data) + # If the file has an encoding, encode unicode with it. + if (isinstance(fp, file) and + isinstance(data, unicode) and + fp.encoding is not None): + errors = getattr(fp, "errors", None) + if errors is None: + errors = "strict" + data = data.encode(fp.encoding, errors) + fp.write(data) + want_unicode = False + sep = kwargs.pop("sep", None) + if sep is not None: + if isinstance(sep, unicode): + want_unicode = True + elif not isinstance(sep, str): + raise TypeError("sep must be None or a string") + end = kwargs.pop("end", None) + if end is not None: + if isinstance(end, unicode): + want_unicode = True + elif not isinstance(end, str): + raise TypeError("end must be None or a string") + if kwargs: + raise TypeError("invalid keyword arguments to print()") + if not want_unicode: + for arg in args: + if isinstance(arg, unicode): + want_unicode = True + break + if want_unicode: + newline = unicode("\n") + space = unicode(" ") + else: + newline = "\n" + space = " " + if sep is None: + sep = space + if end is None: + end = newline + for i, arg in enumerate(args): + if i: + write(sep) + write(arg) + write(end) +if sys.version_info[:2] < (3, 3): + _print = print_ + + def print_(*args, **kwargs): + fp = kwargs.get("file", sys.stdout) + flush = kwargs.pop("flush", False) + _print(*args, **kwargs) + if flush and fp is not None: + fp.flush() + +_add_doc(reraise, """Reraise an exception.""") + +if sys.version_info[0:2] < (3, 4): + def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, + updated=functools.WRAPPER_UPDATES): + def wrapper(f): + f = functools.wraps(wrapped, assigned, updated)(f) + f.__wrapped__ = wrapped + return f + return wrapper +else: + wraps = functools.wraps + + +def with_metaclass(meta, *bases): + """Create a base class with a metaclass.""" + # This requires a bit of explanation: the basic idea is to make a dummy + # metaclass for one level of class instantiation that replaces itself with + # the actual metaclass. + class metaclass(meta): + + def __new__(cls, name, this_bases, d): + return meta(name, bases, d) + return type.__new__(metaclass, 'temporary_class', (), {}) + + +def add_metaclass(metaclass): + """Class decorator for creating a class with a metaclass.""" + def wrapper(cls): + orig_vars = cls.__dict__.copy() + slots = orig_vars.get('__slots__') + if slots is not None: + if isinstance(slots, str): + slots = [slots] + for slots_var in slots: + orig_vars.pop(slots_var) + orig_vars.pop('__dict__', None) + orig_vars.pop('__weakref__', None) + return metaclass(cls.__name__, cls.__bases__, orig_vars) + return wrapper + + +def python_2_unicode_compatible(klass): + """ + A decorator that defines __unicode__ and __str__ methods under Python 2. + Under Python 3 it does nothing. + + To support Python 2 and 3 with a single code base, define a __str__ method + returning text and apply this decorator to the class. + """ + if PY2: + if '__str__' not in klass.__dict__: + raise ValueError("@python_2_unicode_compatible cannot be applied " + "to %s because it doesn't define __str__()." % + klass.__name__) + klass.__unicode__ = klass.__str__ + klass.__str__ = lambda self: self.__unicode__().encode('utf-8') + return klass + + +# Complete the moves implementation. +# This code is at the end of this module to speed up module loading. +# Turn this module into a package. +__path__ = [] # required for PEP 302 and PEP 451 +__package__ = __name__ # see PEP 366 @ReservedAssignment +if globals().get("__spec__") is not None: + __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable +# Remove other six meta path importers, since they cause problems. This can +# happen if six is removed from sys.modules and then reloaded. (Setuptools does +# this for some reason.) +if sys.meta_path: + for i, importer in enumerate(sys.meta_path): + # Here's some real nastiness: Another "instance" of the six module might + # be floating around. Therefore, we can't use isinstance() to check for + # the six meta path importer, since the other six instance will have + # inserted an importer with different class. + if (type(importer).__name__ == "_SixMetaPathImporter" and + importer.name == __name__): + del sys.meta_path[i] + break + del i, importer +# Finally, add the importer to the meta path import hook. +sys.meta_path.append(_importer) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/__init__.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe619e2e676f6e0cf95b2af63cdab33ed386f6b0 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/__init__.py @@ -0,0 +1,18 @@ +__all__ = [ + 'alias', 'bdist_egg', 'bdist_rpm', 'build_ext', 'build_py', 'develop', + 'easy_install', 'egg_info', 'install', 'install_lib', 'rotate', 'saveopts', + 'sdist', 'setopt', 'test', 'install_egg_info', 'install_scripts', + 'register', 'bdist_wininst', 'upload_docs', 'upload', 'build_clib', + 'dist_info', +] + +from distutils.command.bdist import bdist +import sys + +from setuptools.command import install_scripts + +if 'egg' not in bdist.format_commands: + bdist.format_command['egg'] = ('bdist_egg', "Python .egg file") + bdist.format_commands.append('egg') + +del bdist, sys diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/dist_info.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/dist_info.py new file mode 100644 index 0000000000000000000000000000000000000000..c45258fa03a3ddd6a73db4514365f8741d16ca86 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/dist_info.py @@ -0,0 +1,36 @@ +""" +Create a dist_info directory +As defined in the wheel specification +""" + +import os + +from distutils.core import Command +from distutils import log + + +class dist_info(Command): + + description = 'create a .dist-info directory' + + user_options = [ + ('egg-base=', 'e', "directory containing .egg-info directories" + " (default: top of the source tree)"), + ] + + def initialize_options(self): + self.egg_base = None + + def finalize_options(self): + pass + + def run(self): + egg_info = self.get_finalized_command('egg_info') + egg_info.egg_base = self.egg_base + egg_info.finalize_options() + egg_info.run() + dist_info_dir = egg_info.egg_info[:-len('.egg-info')] + '.dist-info' + log.info("creating '{}'".format(os.path.abspath(dist_info_dir))) + + bdist_wheel = self.get_finalized_command('bdist_wheel') + bdist_wheel.egg2dist(egg_info.egg_info, dist_info_dir) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/easy_install.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/easy_install.py new file mode 100644 index 0000000000000000000000000000000000000000..06c98271ba0b2cfd1e9c5a4e5a2590a6b52b382b --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/easy_install.py @@ -0,0 +1,2342 @@ +#!/usr/bin/env python +""" +Easy Install +------------ + +A tool for doing automatic download/extract/build of distutils-based Python +packages. For detailed documentation, see the accompanying EasyInstall.txt +file, or visit the `EasyInstall home page`__. + +__ https://setuptools.readthedocs.io/en/latest/easy_install.html + +""" + +from glob import glob +from distutils.util import get_platform +from distutils.util import convert_path, subst_vars +from distutils.errors import ( + DistutilsArgError, DistutilsOptionError, + DistutilsError, DistutilsPlatformError, +) +from distutils.command.install import INSTALL_SCHEMES, SCHEME_KEYS +from distutils import log, dir_util +from distutils.command.build_scripts import first_line_re +from distutils.spawn import find_executable +import sys +import os +import zipimport +import shutil +import tempfile +import zipfile +import re +import stat +import random +import textwrap +import warnings +import site +import struct +import contextlib +import subprocess +import shlex +import io + + +from sysconfig import get_config_vars, get_path + +from setuptools import SetuptoolsDeprecationWarning + +from setuptools.extern import six +from setuptools.extern.six.moves import configparser, map + +from setuptools import Command +from setuptools.sandbox import run_setup +from setuptools.py27compat import rmtree_safe +from setuptools.command import setopt +from setuptools.archive_util import unpack_archive +from setuptools.package_index import ( + PackageIndex, parse_requirement_arg, URL_SCHEME, +) +from setuptools.command import bdist_egg, egg_info +from setuptools.wheel import Wheel +from pkg_resources import ( + yield_lines, normalize_path, resource_string, ensure_directory, + get_distribution, find_distributions, Environment, Requirement, + Distribution, PathMetadata, EggMetadata, WorkingSet, DistributionNotFound, + VersionConflict, DEVELOP_DIST, +) +import pkg_resources.py31compat + +__metaclass__ = type + +# Turn on PEP440Warnings +warnings.filterwarnings("default", category=pkg_resources.PEP440Warning) + +__all__ = [ + 'samefile', 'easy_install', 'PthDistributions', 'extract_wininst_cfg', + 'main', 'get_exe_prefixes', +] + + +def is_64bit(): + return struct.calcsize("P") == 8 + + +def samefile(p1, p2): + """ + Determine if two paths reference the same file. + + Augments os.path.samefile to work on Windows and + suppresses errors if the path doesn't exist. + """ + both_exist = os.path.exists(p1) and os.path.exists(p2) + use_samefile = hasattr(os.path, 'samefile') and both_exist + if use_samefile: + return os.path.samefile(p1, p2) + norm_p1 = os.path.normpath(os.path.normcase(p1)) + norm_p2 = os.path.normpath(os.path.normcase(p2)) + return norm_p1 == norm_p2 + + +if six.PY2: + + def _to_bytes(s): + return s + + def isascii(s): + try: + six.text_type(s, 'ascii') + return True + except UnicodeError: + return False +else: + + def _to_bytes(s): + return s.encode('utf8') + + def isascii(s): + try: + s.encode('ascii') + return True + except UnicodeError: + return False + + +_one_liner = lambda text: textwrap.dedent(text).strip().replace('\n', '; ') + + +class easy_install(Command): + """Manage a download/build/install process""" + description = "Find/get/install Python packages" + command_consumes_arguments = True + + user_options = [ + ('prefix=', None, "installation prefix"), + ("zip-ok", "z", "install package as a zipfile"), + ("multi-version", "m", "make apps have to require() a version"), + ("upgrade", "U", "force upgrade (searches PyPI for latest versions)"), + ("install-dir=", "d", "install package to DIR"), + ("script-dir=", "s", "install scripts to DIR"), + ("exclude-scripts", "x", "Don't install scripts"), + ("always-copy", "a", "Copy all needed packages to install dir"), + ("index-url=", "i", "base URL of Python Package Index"), + ("find-links=", "f", "additional URL(s) to search for packages"), + ("build-directory=", "b", + "download/extract/build in DIR; keep the results"), + ('optimize=', 'O', + "also compile with optimization: -O1 for \"python -O\", " + "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"), + ('record=', None, + "filename in which to record list of installed files"), + ('always-unzip', 'Z', "don't install as a zipfile, no matter what"), + ('site-dirs=', 'S', "list of directories where .pth files work"), + ('editable', 'e', "Install specified packages in editable form"), + ('no-deps', 'N', "don't install dependencies"), + ('allow-hosts=', 'H', "pattern(s) that hostnames must match"), + ('local-snapshots-ok', 'l', + "allow building eggs from local checkouts"), + ('version', None, "print version information and exit"), + ('no-find-links', None, + "Don't load find-links defined in packages being installed") + ] + boolean_options = [ + 'zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy', + 'editable', + 'no-deps', 'local-snapshots-ok', 'version' + ] + + if site.ENABLE_USER_SITE: + help_msg = "install in user site-package '%s'" % site.USER_SITE + user_options.append(('user', None, help_msg)) + boolean_options.append('user') + + negative_opt = {'always-unzip': 'zip-ok'} + create_index = PackageIndex + + def initialize_options(self): + # the --user option seems to be an opt-in one, + # so the default should be False. + self.user = 0 + self.zip_ok = self.local_snapshots_ok = None + self.install_dir = self.script_dir = self.exclude_scripts = None + self.index_url = None + self.find_links = None + self.build_directory = None + self.args = None + self.optimize = self.record = None + self.upgrade = self.always_copy = self.multi_version = None + self.editable = self.no_deps = self.allow_hosts = None + self.root = self.prefix = self.no_report = None + self.version = None + self.install_purelib = None # for pure module distributions + self.install_platlib = None # non-pure (dists w/ extensions) + self.install_headers = None # for C/C++ headers + self.install_lib = None # set to either purelib or platlib + self.install_scripts = None + self.install_data = None + self.install_base = None + self.install_platbase = None + if site.ENABLE_USER_SITE: + self.install_userbase = site.USER_BASE + self.install_usersite = site.USER_SITE + else: + self.install_userbase = None + self.install_usersite = None + self.no_find_links = None + + # Options not specifiable via command line + self.package_index = None + self.pth_file = self.always_copy_from = None + self.site_dirs = None + self.installed_projects = {} + self.sitepy_installed = False + # Always read easy_install options, even if we are subclassed, or have + # an independent instance created. This ensures that defaults will + # always come from the standard configuration file(s)' "easy_install" + # section, even if this is a "develop" or "install" command, or some + # other embedding. + self._dry_run = None + self.verbose = self.distribution.verbose + self.distribution._set_command_options( + self, self.distribution.get_option_dict('easy_install') + ) + + def delete_blockers(self, blockers): + extant_blockers = ( + filename for filename in blockers + if os.path.exists(filename) or os.path.islink(filename) + ) + list(map(self._delete_path, extant_blockers)) + + def _delete_path(self, path): + log.info("Deleting %s", path) + if self.dry_run: + return + + is_tree = os.path.isdir(path) and not os.path.islink(path) + remover = rmtree if is_tree else os.unlink + remover(path) + + @staticmethod + def _render_version(): + """ + Render the Setuptools version and installation details, then exit. + """ + ver = sys.version[:3] + dist = get_distribution('setuptools') + tmpl = 'setuptools {dist.version} from {dist.location} (Python {ver})' + print(tmpl.format(**locals())) + raise SystemExit() + + def finalize_options(self): + self.version and self._render_version() + + py_version = sys.version.split()[0] + prefix, exec_prefix = get_config_vars('prefix', 'exec_prefix') + + self.config_vars = { + 'dist_name': self.distribution.get_name(), + 'dist_version': self.distribution.get_version(), + 'dist_fullname': self.distribution.get_fullname(), + 'py_version': py_version, + 'py_version_short': py_version[0:3], + 'py_version_nodot': py_version[0] + py_version[2], + 'sys_prefix': prefix, + 'prefix': prefix, + 'sys_exec_prefix': exec_prefix, + 'exec_prefix': exec_prefix, + # Only python 3.2+ has abiflags + 'abiflags': getattr(sys, 'abiflags', ''), + } + + if site.ENABLE_USER_SITE: + self.config_vars['userbase'] = self.install_userbase + self.config_vars['usersite'] = self.install_usersite + + self._fix_install_dir_for_user_site() + + self.expand_basedirs() + self.expand_dirs() + + self._expand( + 'install_dir', 'script_dir', 'build_directory', + 'site_dirs', + ) + # If a non-default installation directory was specified, default the + # script directory to match it. + if self.script_dir is None: + self.script_dir = self.install_dir + + if self.no_find_links is None: + self.no_find_links = False + + # Let install_dir get set by install_lib command, which in turn + # gets its info from the install command, and takes into account + # --prefix and --home and all that other crud. + self.set_undefined_options( + 'install_lib', ('install_dir', 'install_dir') + ) + # Likewise, set default script_dir from 'install_scripts.install_dir' + self.set_undefined_options( + 'install_scripts', ('install_dir', 'script_dir') + ) + + if self.user and self.install_purelib: + self.install_dir = self.install_purelib + self.script_dir = self.install_scripts + # default --record from the install command + self.set_undefined_options('install', ('record', 'record')) + # Should this be moved to the if statement below? It's not used + # elsewhere + normpath = map(normalize_path, sys.path) + self.all_site_dirs = get_site_dirs() + if self.site_dirs is not None: + site_dirs = [ + os.path.expanduser(s.strip()) for s in + self.site_dirs.split(',') + ] + for d in site_dirs: + if not os.path.isdir(d): + log.warn("%s (in --site-dirs) does not exist", d) + elif normalize_path(d) not in normpath: + raise DistutilsOptionError( + d + " (in --site-dirs) is not on sys.path" + ) + else: + self.all_site_dirs.append(normalize_path(d)) + if not self.editable: + self.check_site_dir() + self.index_url = self.index_url or "https://pypi.org/simple/" + self.shadow_path = self.all_site_dirs[:] + for path_item in self.install_dir, normalize_path(self.script_dir): + if path_item not in self.shadow_path: + self.shadow_path.insert(0, path_item) + + if self.allow_hosts is not None: + hosts = [s.strip() for s in self.allow_hosts.split(',')] + else: + hosts = ['*'] + if self.package_index is None: + self.package_index = self.create_index( + self.index_url, search_path=self.shadow_path, hosts=hosts, + ) + self.local_index = Environment(self.shadow_path + sys.path) + + if self.find_links is not None: + if isinstance(self.find_links, six.string_types): + self.find_links = self.find_links.split() + else: + self.find_links = [] + if self.local_snapshots_ok: + self.package_index.scan_egg_links(self.shadow_path + sys.path) + if not self.no_find_links: + self.package_index.add_find_links(self.find_links) + self.set_undefined_options('install_lib', ('optimize', 'optimize')) + if not isinstance(self.optimize, int): + try: + self.optimize = int(self.optimize) + if not (0 <= self.optimize <= 2): + raise ValueError + except ValueError: + raise DistutilsOptionError("--optimize must be 0, 1, or 2") + + if self.editable and not self.build_directory: + raise DistutilsArgError( + "Must specify a build directory (-b) when using --editable" + ) + if not self.args: + raise DistutilsArgError( + "No urls, filenames, or requirements specified (see --help)") + + self.outputs = [] + + def _fix_install_dir_for_user_site(self): + """ + Fix the install_dir if "--user" was used. + """ + if not self.user or not site.ENABLE_USER_SITE: + return + + self.create_home_path() + if self.install_userbase is None: + msg = "User base directory is not specified" + raise DistutilsPlatformError(msg) + self.install_base = self.install_platbase = self.install_userbase + scheme_name = os.name.replace('posix', 'unix') + '_user' + self.select_scheme(scheme_name) + + def _expand_attrs(self, attrs): + for attr in attrs: + val = getattr(self, attr) + if val is not None: + if os.name == 'posix' or os.name == 'nt': + val = os.path.expanduser(val) + val = subst_vars(val, self.config_vars) + setattr(self, attr, val) + + def expand_basedirs(self): + """Calls `os.path.expanduser` on install_base, install_platbase and + root.""" + self._expand_attrs(['install_base', 'install_platbase', 'root']) + + def expand_dirs(self): + """Calls `os.path.expanduser` on install dirs.""" + dirs = [ + 'install_purelib', + 'install_platlib', + 'install_lib', + 'install_headers', + 'install_scripts', + 'install_data', + ] + self._expand_attrs(dirs) + + def run(self): + if self.verbose != self.distribution.verbose: + log.set_verbosity(self.verbose) + try: + for spec in self.args: + self.easy_install(spec, not self.no_deps) + if self.record: + outputs = self.outputs + if self.root: # strip any package prefix + root_len = len(self.root) + for counter in range(len(outputs)): + outputs[counter] = outputs[counter][root_len:] + from distutils import file_util + + self.execute( + file_util.write_file, (self.record, outputs), + "writing list of installed files to '%s'" % + self.record + ) + self.warn_deprecated_options() + finally: + log.set_verbosity(self.distribution.verbose) + + def pseudo_tempname(self): + """Return a pseudo-tempname base in the install directory. + This code is intentionally naive; if a malicious party can write to + the target directory you're already in deep doodoo. + """ + try: + pid = os.getpid() + except Exception: + pid = random.randint(0, sys.maxsize) + return os.path.join(self.install_dir, "test-easy-install-%s" % pid) + + def warn_deprecated_options(self): + pass + + def check_site_dir(self): + """Verify that self.install_dir is .pth-capable dir, if needed""" + + instdir = normalize_path(self.install_dir) + pth_file = os.path.join(instdir, 'easy-install.pth') + + # Is it a configured, PYTHONPATH, implicit, or explicit site dir? + is_site_dir = instdir in self.all_site_dirs + + if not is_site_dir and not self.multi_version: + # No? Then directly test whether it does .pth file processing + is_site_dir = self.check_pth_processing() + else: + # make sure we can write to target dir + testfile = self.pseudo_tempname() + '.write-test' + test_exists = os.path.exists(testfile) + try: + if test_exists: + os.unlink(testfile) + open(testfile, 'w').close() + os.unlink(testfile) + except (OSError, IOError): + self.cant_write_to_target() + + if not is_site_dir and not self.multi_version: + # Can't install non-multi to non-site dir + raise DistutilsError(self.no_default_version_msg()) + + if is_site_dir: + if self.pth_file is None: + self.pth_file = PthDistributions(pth_file, self.all_site_dirs) + else: + self.pth_file = None + + if instdir not in map(normalize_path, _pythonpath()): + # only PYTHONPATH dirs need a site.py, so pretend it's there + self.sitepy_installed = True + elif self.multi_version and not os.path.exists(pth_file): + self.sitepy_installed = True # don't need site.py in this case + self.pth_file = None # and don't create a .pth file + self.install_dir = instdir + + __cant_write_msg = textwrap.dedent(""" + can't create or remove files in install directory + + The following error occurred while trying to add or remove files in the + installation directory: + + %s + + The installation directory you specified (via --install-dir, --prefix, or + the distutils default setting) was: + + %s + """).lstrip() + + __not_exists_id = textwrap.dedent(""" + This directory does not currently exist. Please create it and try again, or + choose a different installation directory (using the -d or --install-dir + option). + """).lstrip() + + __access_msg = textwrap.dedent(""" + Perhaps your account does not have write access to this directory? If the + installation directory is a system-owned directory, you may need to sign in + as the administrator or "root" account. If you do not have administrative + access to this machine, you may wish to choose a different installation + directory, preferably one that is listed in your PYTHONPATH environment + variable. + + For information on other options, you may wish to consult the + documentation at: + + https://setuptools.readthedocs.io/en/latest/easy_install.html + + Please make the appropriate changes for your system and try again. + """).lstrip() + + def cant_write_to_target(self): + msg = self.__cant_write_msg % (sys.exc_info()[1], self.install_dir,) + + if not os.path.exists(self.install_dir): + msg += '\n' + self.__not_exists_id + else: + msg += '\n' + self.__access_msg + raise DistutilsError(msg) + + def check_pth_processing(self): + """Empirically verify whether .pth files are supported in inst. dir""" + instdir = self.install_dir + log.info("Checking .pth file support in %s", instdir) + pth_file = self.pseudo_tempname() + ".pth" + ok_file = pth_file + '.ok' + ok_exists = os.path.exists(ok_file) + tmpl = _one_liner(""" + import os + f = open({ok_file!r}, 'w') + f.write('OK') + f.close() + """) + '\n' + try: + if ok_exists: + os.unlink(ok_file) + dirname = os.path.dirname(ok_file) + pkg_resources.py31compat.makedirs(dirname, exist_ok=True) + f = open(pth_file, 'w') + except (OSError, IOError): + self.cant_write_to_target() + else: + try: + f.write(tmpl.format(**locals())) + f.close() + f = None + executable = sys.executable + if os.name == 'nt': + dirname, basename = os.path.split(executable) + alt = os.path.join(dirname, 'pythonw.exe') + use_alt = ( + basename.lower() == 'python.exe' and + os.path.exists(alt) + ) + if use_alt: + # use pythonw.exe to avoid opening a console window + executable = alt + + from distutils.spawn import spawn + + spawn([executable, '-E', '-c', 'pass'], 0) + + if os.path.exists(ok_file): + log.info( + "TEST PASSED: %s appears to support .pth files", + instdir + ) + return True + finally: + if f: + f.close() + if os.path.exists(ok_file): + os.unlink(ok_file) + if os.path.exists(pth_file): + os.unlink(pth_file) + if not self.multi_version: + log.warn("TEST FAILED: %s does NOT support .pth files", instdir) + return False + + def install_egg_scripts(self, dist): + """Write all the scripts for `dist`, unless scripts are excluded""" + if not self.exclude_scripts and dist.metadata_isdir('scripts'): + for script_name in dist.metadata_listdir('scripts'): + if dist.metadata_isdir('scripts/' + script_name): + # The "script" is a directory, likely a Python 3 + # __pycache__ directory, so skip it. + continue + self.install_script( + dist, script_name, + dist.get_metadata('scripts/' + script_name) + ) + self.install_wrapper_scripts(dist) + + def add_output(self, path): + if os.path.isdir(path): + for base, dirs, files in os.walk(path): + for filename in files: + self.outputs.append(os.path.join(base, filename)) + else: + self.outputs.append(path) + + def not_editable(self, spec): + if self.editable: + raise DistutilsArgError( + "Invalid argument %r: you can't use filenames or URLs " + "with --editable (except via the --find-links option)." + % (spec,) + ) + + def check_editable(self, spec): + if not self.editable: + return + + if os.path.exists(os.path.join(self.build_directory, spec.key)): + raise DistutilsArgError( + "%r already exists in %s; can't do a checkout there" % + (spec.key, self.build_directory) + ) + + @contextlib.contextmanager + def _tmpdir(self): + tmpdir = tempfile.mkdtemp(prefix=u"easy_install-") + try: + # cast to str as workaround for #709 and #710 and #712 + yield str(tmpdir) + finally: + os.path.exists(tmpdir) and rmtree(rmtree_safe(tmpdir)) + + def easy_install(self, spec, deps=False): + if not self.editable: + self.install_site_py() + + with self._tmpdir() as tmpdir: + if not isinstance(spec, Requirement): + if URL_SCHEME(spec): + # It's a url, download it to tmpdir and process + self.not_editable(spec) + dl = self.package_index.download(spec, tmpdir) + return self.install_item(None, dl, tmpdir, deps, True) + + elif os.path.exists(spec): + # Existing file or directory, just process it directly + self.not_editable(spec) + return self.install_item(None, spec, tmpdir, deps, True) + else: + spec = parse_requirement_arg(spec) + + self.check_editable(spec) + dist = self.package_index.fetch_distribution( + spec, tmpdir, self.upgrade, self.editable, + not self.always_copy, self.local_index + ) + if dist is None: + msg = "Could not find suitable distribution for %r" % spec + if self.always_copy: + msg += " (--always-copy skips system and development eggs)" + raise DistutilsError(msg) + elif dist.precedence == DEVELOP_DIST: + # .egg-info dists don't need installing, just process deps + self.process_distribution(spec, dist, deps, "Using") + return dist + else: + return self.install_item(spec, dist.location, tmpdir, deps) + + def install_item(self, spec, download, tmpdir, deps, install_needed=False): + + # Installation is also needed if file in tmpdir or is not an egg + install_needed = install_needed or self.always_copy + install_needed = install_needed or os.path.dirname(download) == tmpdir + install_needed = install_needed or not download.endswith('.egg') + install_needed = install_needed or ( + self.always_copy_from is not None and + os.path.dirname(normalize_path(download)) == + normalize_path(self.always_copy_from) + ) + + if spec and not install_needed: + # at this point, we know it's a local .egg, we just don't know if + # it's already installed. + for dist in self.local_index[spec.project_name]: + if dist.location == download: + break + else: + install_needed = True # it's not in the local index + + log.info("Processing %s", os.path.basename(download)) + + if install_needed: + dists = self.install_eggs(spec, download, tmpdir) + for dist in dists: + self.process_distribution(spec, dist, deps) + else: + dists = [self.egg_distribution(download)] + self.process_distribution(spec, dists[0], deps, "Using") + + if spec is not None: + for dist in dists: + if dist in spec: + return dist + + def select_scheme(self, name): + """Sets the install directories by applying the install schemes.""" + # it's the caller's problem if they supply a bad name! + scheme = INSTALL_SCHEMES[name] + for key in SCHEME_KEYS: + attrname = 'install_' + key + if getattr(self, attrname) is None: + setattr(self, attrname, scheme[key]) + + def process_distribution(self, requirement, dist, deps=True, *info): + self.update_pth(dist) + self.package_index.add(dist) + if dist in self.local_index[dist.key]: + self.local_index.remove(dist) + self.local_index.add(dist) + self.install_egg_scripts(dist) + self.installed_projects[dist.key] = dist + log.info(self.installation_report(requirement, dist, *info)) + if (dist.has_metadata('dependency_links.txt') and + not self.no_find_links): + self.package_index.add_find_links( + dist.get_metadata_lines('dependency_links.txt') + ) + if not deps and not self.always_copy: + return + elif requirement is not None and dist.key != requirement.key: + log.warn("Skipping dependencies for %s", dist) + return # XXX this is not the distribution we were looking for + elif requirement is None or dist not in requirement: + # if we wound up with a different version, resolve what we've got + distreq = dist.as_requirement() + requirement = Requirement(str(distreq)) + log.info("Processing dependencies for %s", requirement) + try: + distros = WorkingSet([]).resolve( + [requirement], self.local_index, self.easy_install + ) + except DistributionNotFound as e: + raise DistutilsError(str(e)) + except VersionConflict as e: + raise DistutilsError(e.report()) + if self.always_copy or self.always_copy_from: + # Force all the relevant distros to be copied or activated + for dist in distros: + if dist.key not in self.installed_projects: + self.easy_install(dist.as_requirement()) + log.info("Finished processing dependencies for %s", requirement) + + def should_unzip(self, dist): + if self.zip_ok is not None: + return not self.zip_ok + if dist.has_metadata('not-zip-safe'): + return True + if not dist.has_metadata('zip-safe'): + return True + return False + + def maybe_move(self, spec, dist_filename, setup_base): + dst = os.path.join(self.build_directory, spec.key) + if os.path.exists(dst): + msg = ( + "%r already exists in %s; build directory %s will not be kept" + ) + log.warn(msg, spec.key, self.build_directory, setup_base) + return setup_base + if os.path.isdir(dist_filename): + setup_base = dist_filename + else: + if os.path.dirname(dist_filename) == setup_base: + os.unlink(dist_filename) # get it out of the tmp dir + contents = os.listdir(setup_base) + if len(contents) == 1: + dist_filename = os.path.join(setup_base, contents[0]) + if os.path.isdir(dist_filename): + # if the only thing there is a directory, move it instead + setup_base = dist_filename + ensure_directory(dst) + shutil.move(setup_base, dst) + return dst + + def install_wrapper_scripts(self, dist): + if self.exclude_scripts: + return + for args in ScriptWriter.best().get_args(dist): + self.write_script(*args) + + def install_script(self, dist, script_name, script_text, dev_path=None): + """Generate a legacy script wrapper and install it""" + spec = str(dist.as_requirement()) + is_script = is_python_script(script_text, script_name) + + if is_script: + body = self._load_template(dev_path) % locals() + script_text = ScriptWriter.get_header(script_text) + body + self.write_script(script_name, _to_bytes(script_text), 'b') + + @staticmethod + def _load_template(dev_path): + """ + There are a couple of template scripts in the package. This + function loads one of them and prepares it for use. + """ + # See https://github.com/pypa/setuptools/issues/134 for info + # on script file naming and downstream issues with SVR4 + name = 'script.tmpl' + if dev_path: + name = name.replace('.tmpl', ' (dev).tmpl') + + raw_bytes = resource_string('setuptools', name) + return raw_bytes.decode('utf-8') + + def write_script(self, script_name, contents, mode="t", blockers=()): + """Write an executable file to the scripts directory""" + self.delete_blockers( # clean up old .py/.pyw w/o a script + [os.path.join(self.script_dir, x) for x in blockers] + ) + log.info("Installing %s script to %s", script_name, self.script_dir) + target = os.path.join(self.script_dir, script_name) + self.add_output(target) + + if self.dry_run: + return + + mask = current_umask() + ensure_directory(target) + if os.path.exists(target): + os.unlink(target) + with open(target, "w" + mode) as f: + f.write(contents) + chmod(target, 0o777 - mask) + + def install_eggs(self, spec, dist_filename, tmpdir): + # .egg dirs or files are already built, so just return them + if dist_filename.lower().endswith('.egg'): + return [self.install_egg(dist_filename, tmpdir)] + elif dist_filename.lower().endswith('.exe'): + return [self.install_exe(dist_filename, tmpdir)] + elif dist_filename.lower().endswith('.whl'): + return [self.install_wheel(dist_filename, tmpdir)] + + # Anything else, try to extract and build + setup_base = tmpdir + if os.path.isfile(dist_filename) and not dist_filename.endswith('.py'): + unpack_archive(dist_filename, tmpdir, self.unpack_progress) + elif os.path.isdir(dist_filename): + setup_base = os.path.abspath(dist_filename) + + if (setup_base.startswith(tmpdir) # something we downloaded + and self.build_directory and spec is not None): + setup_base = self.maybe_move(spec, dist_filename, setup_base) + + # Find the setup.py file + setup_script = os.path.join(setup_base, 'setup.py') + + if not os.path.exists(setup_script): + setups = glob(os.path.join(setup_base, '*', 'setup.py')) + if not setups: + raise DistutilsError( + "Couldn't find a setup script in %s" % + os.path.abspath(dist_filename) + ) + if len(setups) > 1: + raise DistutilsError( + "Multiple setup scripts in %s" % + os.path.abspath(dist_filename) + ) + setup_script = setups[0] + + # Now run it, and return the result + if self.editable: + log.info(self.report_editable(spec, setup_script)) + return [] + else: + return self.build_and_install(setup_script, setup_base) + + def egg_distribution(self, egg_path): + if os.path.isdir(egg_path): + metadata = PathMetadata(egg_path, os.path.join(egg_path, + 'EGG-INFO')) + else: + metadata = EggMetadata(zipimport.zipimporter(egg_path)) + return Distribution.from_filename(egg_path, metadata=metadata) + + def install_egg(self, egg_path, tmpdir): + destination = os.path.join( + self.install_dir, + os.path.basename(egg_path), + ) + destination = os.path.abspath(destination) + if not self.dry_run: + ensure_directory(destination) + + dist = self.egg_distribution(egg_path) + if not samefile(egg_path, destination): + if os.path.isdir(destination) and not os.path.islink(destination): + dir_util.remove_tree(destination, dry_run=self.dry_run) + elif os.path.exists(destination): + self.execute( + os.unlink, + (destination,), + "Removing " + destination, + ) + try: + new_dist_is_zipped = False + if os.path.isdir(egg_path): + if egg_path.startswith(tmpdir): + f, m = shutil.move, "Moving" + else: + f, m = shutil.copytree, "Copying" + elif self.should_unzip(dist): + self.mkpath(destination) + f, m = self.unpack_and_compile, "Extracting" + else: + new_dist_is_zipped = True + if egg_path.startswith(tmpdir): + f, m = shutil.move, "Moving" + else: + f, m = shutil.copy2, "Copying" + self.execute( + f, + (egg_path, destination), + (m + " %s to %s") % ( + os.path.basename(egg_path), + os.path.dirname(destination) + ), + ) + update_dist_caches( + destination, + fix_zipimporter_caches=new_dist_is_zipped, + ) + except Exception: + update_dist_caches(destination, fix_zipimporter_caches=False) + raise + + self.add_output(destination) + return self.egg_distribution(destination) + + def install_exe(self, dist_filename, tmpdir): + # See if it's valid, get data + cfg = extract_wininst_cfg(dist_filename) + if cfg is None: + raise DistutilsError( + "%s is not a valid distutils Windows .exe" % dist_filename + ) + # Create a dummy distribution object until we build the real distro + dist = Distribution( + None, + project_name=cfg.get('metadata', 'name'), + version=cfg.get('metadata', 'version'), platform=get_platform(), + ) + + # Convert the .exe to an unpacked egg + egg_path = os.path.join(tmpdir, dist.egg_name() + '.egg') + dist.location = egg_path + egg_tmp = egg_path + '.tmp' + _egg_info = os.path.join(egg_tmp, 'EGG-INFO') + pkg_inf = os.path.join(_egg_info, 'PKG-INFO') + ensure_directory(pkg_inf) # make sure EGG-INFO dir exists + dist._provider = PathMetadata(egg_tmp, _egg_info) # XXX + self.exe_to_egg(dist_filename, egg_tmp) + + # Write EGG-INFO/PKG-INFO + if not os.path.exists(pkg_inf): + f = open(pkg_inf, 'w') + f.write('Metadata-Version: 1.0\n') + for k, v in cfg.items('metadata'): + if k != 'target_version': + f.write('%s: %s\n' % (k.replace('_', '-').title(), v)) + f.close() + script_dir = os.path.join(_egg_info, 'scripts') + # delete entry-point scripts to avoid duping + self.delete_blockers([ + os.path.join(script_dir, args[0]) + for args in ScriptWriter.get_args(dist) + ]) + # Build .egg file from tmpdir + bdist_egg.make_zipfile( + egg_path, egg_tmp, verbose=self.verbose, dry_run=self.dry_run, + ) + # install the .egg + return self.install_egg(egg_path, tmpdir) + + def exe_to_egg(self, dist_filename, egg_tmp): + """Extract a bdist_wininst to the directories an egg would use""" + # Check for .pth file and set up prefix translations + prefixes = get_exe_prefixes(dist_filename) + to_compile = [] + native_libs = [] + top_level = {} + + def process(src, dst): + s = src.lower() + for old, new in prefixes: + if s.startswith(old): + src = new + src[len(old):] + parts = src.split('/') + dst = os.path.join(egg_tmp, *parts) + dl = dst.lower() + if dl.endswith('.pyd') or dl.endswith('.dll'): + parts[-1] = bdist_egg.strip_module(parts[-1]) + top_level[os.path.splitext(parts[0])[0]] = 1 + native_libs.append(src) + elif dl.endswith('.py') and old != 'SCRIPTS/': + top_level[os.path.splitext(parts[0])[0]] = 1 + to_compile.append(dst) + return dst + if not src.endswith('.pth'): + log.warn("WARNING: can't process %s", src) + return None + + # extract, tracking .pyd/.dll->native_libs and .py -> to_compile + unpack_archive(dist_filename, egg_tmp, process) + stubs = [] + for res in native_libs: + if res.lower().endswith('.pyd'): # create stubs for .pyd's + parts = res.split('/') + resource = parts[-1] + parts[-1] = bdist_egg.strip_module(parts[-1]) + '.py' + pyfile = os.path.join(egg_tmp, *parts) + to_compile.append(pyfile) + stubs.append(pyfile) + bdist_egg.write_stub(resource, pyfile) + self.byte_compile(to_compile) # compile .py's + bdist_egg.write_safety_flag( + os.path.join(egg_tmp, 'EGG-INFO'), + bdist_egg.analyze_egg(egg_tmp, stubs)) # write zip-safety flag + + for name in 'top_level', 'native_libs': + if locals()[name]: + txt = os.path.join(egg_tmp, 'EGG-INFO', name + '.txt') + if not os.path.exists(txt): + f = open(txt, 'w') + f.write('\n'.join(locals()[name]) + '\n') + f.close() + + def install_wheel(self, wheel_path, tmpdir): + wheel = Wheel(wheel_path) + assert wheel.is_compatible() + destination = os.path.join(self.install_dir, wheel.egg_name()) + destination = os.path.abspath(destination) + if not self.dry_run: + ensure_directory(destination) + if os.path.isdir(destination) and not os.path.islink(destination): + dir_util.remove_tree(destination, dry_run=self.dry_run) + elif os.path.exists(destination): + self.execute( + os.unlink, + (destination,), + "Removing " + destination, + ) + try: + self.execute( + wheel.install_as_egg, + (destination,), + ("Installing %s to %s") % ( + os.path.basename(wheel_path), + os.path.dirname(destination) + ), + ) + finally: + update_dist_caches(destination, fix_zipimporter_caches=False) + self.add_output(destination) + return self.egg_distribution(destination) + + __mv_warning = textwrap.dedent(""" + Because this distribution was installed --multi-version, before you can + import modules from this package in an application, you will need to + 'import pkg_resources' and then use a 'require()' call similar to one of + these examples, in order to select the desired version: + + pkg_resources.require("%(name)s") # latest installed version + pkg_resources.require("%(name)s==%(version)s") # this exact version + pkg_resources.require("%(name)s>=%(version)s") # this version or higher + """).lstrip() + + __id_warning = textwrap.dedent(""" + Note also that the installation directory must be on sys.path at runtime for + this to work. (e.g. by being the application's script directory, by being on + PYTHONPATH, or by being added to sys.path by your code.) + """) + + def installation_report(self, req, dist, what="Installed"): + """Helpful installation message for display to package users""" + msg = "\n%(what)s %(eggloc)s%(extras)s" + if self.multi_version and not self.no_report: + msg += '\n' + self.__mv_warning + if self.install_dir not in map(normalize_path, sys.path): + msg += '\n' + self.__id_warning + + eggloc = dist.location + name = dist.project_name + version = dist.version + extras = '' # TODO: self.report_extras(req, dist) + return msg % locals() + + __editable_msg = textwrap.dedent(""" + Extracted editable version of %(spec)s to %(dirname)s + + If it uses setuptools in its setup script, you can activate it in + "development" mode by going to that directory and running:: + + %(python)s setup.py develop + + See the setuptools documentation for the "develop" command for more info. + """).lstrip() + + def report_editable(self, spec, setup_script): + dirname = os.path.dirname(setup_script) + python = sys.executable + return '\n' + self.__editable_msg % locals() + + def run_setup(self, setup_script, setup_base, args): + sys.modules.setdefault('distutils.command.bdist_egg', bdist_egg) + sys.modules.setdefault('distutils.command.egg_info', egg_info) + + args = list(args) + if self.verbose > 2: + v = 'v' * (self.verbose - 1) + args.insert(0, '-' + v) + elif self.verbose < 2: + args.insert(0, '-q') + if self.dry_run: + args.insert(0, '-n') + log.info( + "Running %s %s", setup_script[len(setup_base) + 1:], ' '.join(args) + ) + try: + run_setup(setup_script, args) + except SystemExit as v: + raise DistutilsError("Setup script exited with %s" % (v.args[0],)) + + def build_and_install(self, setup_script, setup_base): + args = ['bdist_egg', '--dist-dir'] + + dist_dir = tempfile.mkdtemp( + prefix='egg-dist-tmp-', dir=os.path.dirname(setup_script) + ) + try: + self._set_fetcher_options(os.path.dirname(setup_script)) + args.append(dist_dir) + + self.run_setup(setup_script, setup_base, args) + all_eggs = Environment([dist_dir]) + eggs = [] + for key in all_eggs: + for dist in all_eggs[key]: + eggs.append(self.install_egg(dist.location, setup_base)) + if not eggs and not self.dry_run: + log.warn("No eggs found in %s (setup script problem?)", + dist_dir) + return eggs + finally: + rmtree(dist_dir) + log.set_verbosity(self.verbose) # restore our log verbosity + + def _set_fetcher_options(self, base): + """ + When easy_install is about to run bdist_egg on a source dist, that + source dist might have 'setup_requires' directives, requiring + additional fetching. Ensure the fetcher options given to easy_install + are available to that command as well. + """ + # find the fetch options from easy_install and write them out + # to the setup.cfg file. + ei_opts = self.distribution.get_option_dict('easy_install').copy() + fetch_directives = ( + 'find_links', 'site_dirs', 'index_url', 'optimize', + 'site_dirs', 'allow_hosts', + ) + fetch_options = {} + for key, val in ei_opts.items(): + if key not in fetch_directives: + continue + fetch_options[key.replace('_', '-')] = val[1] + # create a settings dictionary suitable for `edit_config` + settings = dict(easy_install=fetch_options) + cfg_filename = os.path.join(base, 'setup.cfg') + setopt.edit_config(cfg_filename, settings) + + def update_pth(self, dist): + if self.pth_file is None: + return + + for d in self.pth_file[dist.key]: # drop old entries + if self.multi_version or d.location != dist.location: + log.info("Removing %s from easy-install.pth file", d) + self.pth_file.remove(d) + if d.location in self.shadow_path: + self.shadow_path.remove(d.location) + + if not self.multi_version: + if dist.location in self.pth_file.paths: + log.info( + "%s is already the active version in easy-install.pth", + dist, + ) + else: + log.info("Adding %s to easy-install.pth file", dist) + self.pth_file.add(dist) # add new entry + if dist.location not in self.shadow_path: + self.shadow_path.append(dist.location) + + if not self.dry_run: + + self.pth_file.save() + + if dist.key == 'setuptools': + # Ensure that setuptools itself never becomes unavailable! + # XXX should this check for latest version? + filename = os.path.join(self.install_dir, 'setuptools.pth') + if os.path.islink(filename): + os.unlink(filename) + f = open(filename, 'wt') + f.write(self.pth_file.make_relative(dist.location) + '\n') + f.close() + + def unpack_progress(self, src, dst): + # Progress filter for unpacking + log.debug("Unpacking %s to %s", src, dst) + return dst # only unpack-and-compile skips files for dry run + + def unpack_and_compile(self, egg_path, destination): + to_compile = [] + to_chmod = [] + + def pf(src, dst): + if dst.endswith('.py') and not src.startswith('EGG-INFO/'): + to_compile.append(dst) + elif dst.endswith('.dll') or dst.endswith('.so'): + to_chmod.append(dst) + self.unpack_progress(src, dst) + return not self.dry_run and dst or None + + unpack_archive(egg_path, destination, pf) + self.byte_compile(to_compile) + if not self.dry_run: + for f in to_chmod: + mode = ((os.stat(f)[stat.ST_MODE]) | 0o555) & 0o7755 + chmod(f, mode) + + def byte_compile(self, to_compile): + if sys.dont_write_bytecode: + return + + from distutils.util import byte_compile + + try: + # try to make the byte compile messages quieter + log.set_verbosity(self.verbose - 1) + + byte_compile(to_compile, optimize=0, force=1, dry_run=self.dry_run) + if self.optimize: + byte_compile( + to_compile, optimize=self.optimize, force=1, + dry_run=self.dry_run, + ) + finally: + log.set_verbosity(self.verbose) # restore original verbosity + + __no_default_msg = textwrap.dedent(""" + bad install directory or PYTHONPATH + + You are attempting to install a package to a directory that is not + on PYTHONPATH and which Python does not read ".pth" files from. The + installation directory you specified (via --install-dir, --prefix, or + the distutils default setting) was: + + %s + + and your PYTHONPATH environment variable currently contains: + + %r + + Here are some of your options for correcting the problem: + + * You can choose a different installation directory, i.e., one that is + on PYTHONPATH or supports .pth files + + * You can add the installation directory to the PYTHONPATH environment + variable. (It must then also be on PYTHONPATH whenever you run + Python and want to use the package(s) you are installing.) + + * You can set up the installation directory to support ".pth" files by + using one of the approaches described here: + + https://setuptools.readthedocs.io/en/latest/easy_install.html#custom-installation-locations + + + Please make the appropriate changes for your system and try again.""").lstrip() + + def no_default_version_msg(self): + template = self.__no_default_msg + return template % (self.install_dir, os.environ.get('PYTHONPATH', '')) + + def install_site_py(self): + """Make sure there's a site.py in the target dir, if needed""" + + if self.sitepy_installed: + return # already did it, or don't need to + + sitepy = os.path.join(self.install_dir, "site.py") + source = resource_string("setuptools", "site-patch.py") + source = source.decode('utf-8') + current = "" + + if os.path.exists(sitepy): + log.debug("Checking existing site.py in %s", self.install_dir) + with io.open(sitepy) as strm: + current = strm.read() + + if not current.startswith('def __boot():'): + raise DistutilsError( + "%s is not a setuptools-generated site.py; please" + " remove it." % sitepy + ) + + if current != source: + log.info("Creating %s", sitepy) + if not self.dry_run: + ensure_directory(sitepy) + with io.open(sitepy, 'w', encoding='utf-8') as strm: + strm.write(source) + self.byte_compile([sitepy]) + + self.sitepy_installed = True + + def create_home_path(self): + """Create directories under ~.""" + if not self.user: + return + home = convert_path(os.path.expanduser("~")) + for name, path in six.iteritems(self.config_vars): + if path.startswith(home) and not os.path.isdir(path): + self.debug_print("os.makedirs('%s', 0o700)" % path) + os.makedirs(path, 0o700) + + INSTALL_SCHEMES = dict( + posix=dict( + install_dir='$base/lib/python$py_version_short/site-packages', + script_dir='$base/bin', + ), + ) + + DEFAULT_SCHEME = dict( + install_dir='$base/Lib/site-packages', + script_dir='$base/Scripts', + ) + + def _expand(self, *attrs): + config_vars = self.get_finalized_command('install').config_vars + + if self.prefix: + # Set default install_dir/scripts from --prefix + config_vars = config_vars.copy() + config_vars['base'] = self.prefix + scheme = self.INSTALL_SCHEMES.get(os.name, self.DEFAULT_SCHEME) + for attr, val in scheme.items(): + if getattr(self, attr, None) is None: + setattr(self, attr, val) + + from distutils.util import subst_vars + + for attr in attrs: + val = getattr(self, attr) + if val is not None: + val = subst_vars(val, config_vars) + if os.name == 'posix': + val = os.path.expanduser(val) + setattr(self, attr, val) + + +def _pythonpath(): + items = os.environ.get('PYTHONPATH', '').split(os.pathsep) + return filter(None, items) + + +def get_site_dirs(): + """ + Return a list of 'site' dirs + """ + + sitedirs = [] + + # start with PYTHONPATH + sitedirs.extend(_pythonpath()) + + prefixes = [sys.prefix] + if sys.exec_prefix != sys.prefix: + prefixes.append(sys.exec_prefix) + for prefix in prefixes: + if prefix: + if sys.platform in ('os2emx', 'riscos'): + sitedirs.append(os.path.join(prefix, "Lib", "site-packages")) + elif os.sep == '/': + sitedirs.extend([ + os.path.join( + prefix, + "lib", + "python" + sys.version[:3], + "site-packages", + ), + os.path.join(prefix, "lib", "site-python"), + ]) + else: + sitedirs.extend([ + prefix, + os.path.join(prefix, "lib", "site-packages"), + ]) + if sys.platform == 'darwin': + # for framework builds *only* we add the standard Apple + # locations. Currently only per-user, but /Library and + # /Network/Library could be added too + if 'Python.framework' in prefix: + home = os.environ.get('HOME') + if home: + home_sp = os.path.join( + home, + 'Library', + 'Python', + sys.version[:3], + 'site-packages', + ) + sitedirs.append(home_sp) + lib_paths = get_path('purelib'), get_path('platlib') + for site_lib in lib_paths: + if site_lib not in sitedirs: + sitedirs.append(site_lib) + + if site.ENABLE_USER_SITE: + sitedirs.append(site.USER_SITE) + + try: + sitedirs.extend(site.getsitepackages()) + except AttributeError: + pass + + sitedirs = list(map(normalize_path, sitedirs)) + + return sitedirs + + +def expand_paths(inputs): + """Yield sys.path directories that might contain "old-style" packages""" + + seen = {} + + for dirname in inputs: + dirname = normalize_path(dirname) + if dirname in seen: + continue + + seen[dirname] = 1 + if not os.path.isdir(dirname): + continue + + files = os.listdir(dirname) + yield dirname, files + + for name in files: + if not name.endswith('.pth'): + # We only care about the .pth files + continue + if name in ('easy-install.pth', 'setuptools.pth'): + # Ignore .pth files that we control + continue + + # Read the .pth file + f = open(os.path.join(dirname, name)) + lines = list(yield_lines(f)) + f.close() + + # Yield existing non-dupe, non-import directory lines from it + for line in lines: + if not line.startswith("import"): + line = normalize_path(line.rstrip()) + if line not in seen: + seen[line] = 1 + if not os.path.isdir(line): + continue + yield line, os.listdir(line) + + +def extract_wininst_cfg(dist_filename): + """Extract configuration data from a bdist_wininst .exe + + Returns a configparser.RawConfigParser, or None + """ + f = open(dist_filename, 'rb') + try: + endrec = zipfile._EndRecData(f) + if endrec is None: + return None + + prepended = (endrec[9] - endrec[5]) - endrec[6] + if prepended < 12: # no wininst data here + return None + f.seek(prepended - 12) + + tag, cfglen, bmlen = struct.unpack("egg path translations for a given .exe file""" + + prefixes = [ + ('PURELIB/', ''), + ('PLATLIB/pywin32_system32', ''), + ('PLATLIB/', ''), + ('SCRIPTS/', 'EGG-INFO/scripts/'), + ('DATA/lib/site-packages', ''), + ] + z = zipfile.ZipFile(exe_filename) + try: + for info in z.infolist(): + name = info.filename + parts = name.split('/') + if len(parts) == 3 and parts[2] == 'PKG-INFO': + if parts[1].endswith('.egg-info'): + prefixes.insert(0, ('/'.join(parts[:2]), 'EGG-INFO/')) + break + if len(parts) != 2 or not name.endswith('.pth'): + continue + if name.endswith('-nspkg.pth'): + continue + if parts[0].upper() in ('PURELIB', 'PLATLIB'): + contents = z.read(name) + if six.PY3: + contents = contents.decode() + for pth in yield_lines(contents): + pth = pth.strip().replace('\\', '/') + if not pth.startswith('import'): + prefixes.append((('%s/%s/' % (parts[0], pth)), '')) + finally: + z.close() + prefixes = [(x.lower(), y) for x, y in prefixes] + prefixes.sort() + prefixes.reverse() + return prefixes + + +class PthDistributions(Environment): + """A .pth file with Distribution paths in it""" + + dirty = False + + def __init__(self, filename, sitedirs=()): + self.filename = filename + self.sitedirs = list(map(normalize_path, sitedirs)) + self.basedir = normalize_path(os.path.dirname(self.filename)) + self._load() + Environment.__init__(self, [], None, None) + for path in yield_lines(self.paths): + list(map(self.add, find_distributions(path, True))) + + def _load(self): + self.paths = [] + saw_import = False + seen = dict.fromkeys(self.sitedirs) + if os.path.isfile(self.filename): + f = open(self.filename, 'rt') + for line in f: + if line.startswith('import'): + saw_import = True + continue + path = line.rstrip() + self.paths.append(path) + if not path.strip() or path.strip().startswith('#'): + continue + # skip non-existent paths, in case somebody deleted a package + # manually, and duplicate paths as well + path = self.paths[-1] = normalize_path( + os.path.join(self.basedir, path) + ) + if not os.path.exists(path) or path in seen: + self.paths.pop() # skip it + self.dirty = True # we cleaned up, so we're dirty now :) + continue + seen[path] = 1 + f.close() + + if self.paths and not saw_import: + self.dirty = True # ensure anything we touch has import wrappers + while self.paths and not self.paths[-1].strip(): + self.paths.pop() + + def save(self): + """Write changed .pth file back to disk""" + if not self.dirty: + return + + rel_paths = list(map(self.make_relative, self.paths)) + if rel_paths: + log.debug("Saving %s", self.filename) + lines = self._wrap_lines(rel_paths) + data = '\n'.join(lines) + '\n' + + if os.path.islink(self.filename): + os.unlink(self.filename) + with open(self.filename, 'wt') as f: + f.write(data) + + elif os.path.exists(self.filename): + log.debug("Deleting empty %s", self.filename) + os.unlink(self.filename) + + self.dirty = False + + @staticmethod + def _wrap_lines(lines): + return lines + + def add(self, dist): + """Add `dist` to the distribution map""" + new_path = ( + dist.location not in self.paths and ( + dist.location not in self.sitedirs or + # account for '.' being in PYTHONPATH + dist.location == os.getcwd() + ) + ) + if new_path: + self.paths.append(dist.location) + self.dirty = True + Environment.add(self, dist) + + def remove(self, dist): + """Remove `dist` from the distribution map""" + while dist.location in self.paths: + self.paths.remove(dist.location) + self.dirty = True + Environment.remove(self, dist) + + def make_relative(self, path): + npath, last = os.path.split(normalize_path(path)) + baselen = len(self.basedir) + parts = [last] + sep = os.altsep == '/' and '/' or os.sep + while len(npath) >= baselen: + if npath == self.basedir: + parts.append(os.curdir) + parts.reverse() + return sep.join(parts) + npath, last = os.path.split(npath) + parts.append(last) + else: + return path + + +class RewritePthDistributions(PthDistributions): + @classmethod + def _wrap_lines(cls, lines): + yield cls.prelude + for line in lines: + yield line + yield cls.postlude + + prelude = _one_liner(""" + import sys + sys.__plen = len(sys.path) + """) + postlude = _one_liner(""" + import sys + new = sys.path[sys.__plen:] + del sys.path[sys.__plen:] + p = getattr(sys, '__egginsert', 0) + sys.path[p:p] = new + sys.__egginsert = p + len(new) + """) + + +if os.environ.get('SETUPTOOLS_SYS_PATH_TECHNIQUE', 'raw') == 'rewrite': + PthDistributions = RewritePthDistributions + + +def _first_line_re(): + """ + Return a regular expression based on first_line_re suitable for matching + strings. + """ + if isinstance(first_line_re.pattern, str): + return first_line_re + + # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern. + return re.compile(first_line_re.pattern.decode()) + + +def auto_chmod(func, arg, exc): + if func in [os.unlink, os.remove] and os.name == 'nt': + chmod(arg, stat.S_IWRITE) + return func(arg) + et, ev, _ = sys.exc_info() + six.reraise(et, (ev[0], ev[1] + (" %s %s" % (func, arg)))) + + +def update_dist_caches(dist_path, fix_zipimporter_caches): + """ + Fix any globally cached `dist_path` related data + + `dist_path` should be a path of a newly installed egg distribution (zipped + or unzipped). + + sys.path_importer_cache contains finder objects that have been cached when + importing data from the original distribution. Any such finders need to be + cleared since the replacement distribution might be packaged differently, + e.g. a zipped egg distribution might get replaced with an unzipped egg + folder or vice versa. Having the old finders cached may then cause Python + to attempt loading modules from the replacement distribution using an + incorrect loader. + + zipimport.zipimporter objects are Python loaders charged with importing + data packaged inside zip archives. If stale loaders referencing the + original distribution, are left behind, they can fail to load modules from + the replacement distribution. E.g. if an old zipimport.zipimporter instance + is used to load data from a new zipped egg archive, it may cause the + operation to attempt to locate the requested data in the wrong location - + one indicated by the original distribution's zip archive directory + information. Such an operation may then fail outright, e.g. report having + read a 'bad local file header', or even worse, it may fail silently & + return invalid data. + + zipimport._zip_directory_cache contains cached zip archive directory + information for all existing zipimport.zipimporter instances and all such + instances connected to the same archive share the same cached directory + information. + + If asked, and the underlying Python implementation allows it, we can fix + all existing zipimport.zipimporter instances instead of having to track + them down and remove them one by one, by updating their shared cached zip + archive directory information. This, of course, assumes that the + replacement distribution is packaged as a zipped egg. + + If not asked to fix existing zipimport.zipimporter instances, we still do + our best to clear any remaining zipimport.zipimporter related cached data + that might somehow later get used when attempting to load data from the new + distribution and thus cause such load operations to fail. Note that when + tracking down such remaining stale data, we can not catch every conceivable + usage from here, and we clear only those that we know of and have found to + cause problems if left alive. Any remaining caches should be updated by + whomever is in charge of maintaining them, i.e. they should be ready to + handle us replacing their zip archives with new distributions at runtime. + + """ + # There are several other known sources of stale zipimport.zipimporter + # instances that we do not clear here, but might if ever given a reason to + # do so: + # * Global setuptools pkg_resources.working_set (a.k.a. 'master working + # set') may contain distributions which may in turn contain their + # zipimport.zipimporter loaders. + # * Several zipimport.zipimporter loaders held by local variables further + # up the function call stack when running the setuptools installation. + # * Already loaded modules may have their __loader__ attribute set to the + # exact loader instance used when importing them. Python 3.4 docs state + # that this information is intended mostly for introspection and so is + # not expected to cause us problems. + normalized_path = normalize_path(dist_path) + _uncache(normalized_path, sys.path_importer_cache) + if fix_zipimporter_caches: + _replace_zip_directory_cache_data(normalized_path) + else: + # Here, even though we do not want to fix existing and now stale + # zipimporter cache information, we still want to remove it. Related to + # Python's zip archive directory information cache, we clear each of + # its stale entries in two phases: + # 1. Clear the entry so attempting to access zip archive information + # via any existing stale zipimport.zipimporter instances fails. + # 2. Remove the entry from the cache so any newly constructed + # zipimport.zipimporter instances do not end up using old stale + # zip archive directory information. + # This whole stale data removal step does not seem strictly necessary, + # but has been left in because it was done before we started replacing + # the zip archive directory information cache content if possible, and + # there are no relevant unit tests that we can depend on to tell us if + # this is really needed. + _remove_and_clear_zip_directory_cache_data(normalized_path) + + +def _collect_zipimporter_cache_entries(normalized_path, cache): + """ + Return zipimporter cache entry keys related to a given normalized path. + + Alternative path spellings (e.g. those using different character case or + those using alternative path separators) related to the same path are + included. Any sub-path entries are included as well, i.e. those + corresponding to zip archives embedded in other zip archives. + + """ + result = [] + prefix_len = len(normalized_path) + for p in cache: + np = normalize_path(p) + if (np.startswith(normalized_path) and + np[prefix_len:prefix_len + 1] in (os.sep, '')): + result.append(p) + return result + + +def _update_zipimporter_cache(normalized_path, cache, updater=None): + """ + Update zipimporter cache data for a given normalized path. + + Any sub-path entries are processed as well, i.e. those corresponding to zip + archives embedded in other zip archives. + + Given updater is a callable taking a cache entry key and the original entry + (after already removing the entry from the cache), and expected to update + the entry and possibly return a new one to be inserted in its place. + Returning None indicates that the entry should not be replaced with a new + one. If no updater is given, the cache entries are simply removed without + any additional processing, the same as if the updater simply returned None. + + """ + for p in _collect_zipimporter_cache_entries(normalized_path, cache): + # N.B. pypy's custom zipimport._zip_directory_cache implementation does + # not support the complete dict interface: + # * Does not support item assignment, thus not allowing this function + # to be used only for removing existing cache entries. + # * Does not support the dict.pop() method, forcing us to use the + # get/del patterns instead. For more detailed information see the + # following links: + # https://github.com/pypa/setuptools/issues/202#issuecomment-202913420 + # http://bit.ly/2h9itJX + old_entry = cache[p] + del cache[p] + new_entry = updater and updater(p, old_entry) + if new_entry is not None: + cache[p] = new_entry + + +def _uncache(normalized_path, cache): + _update_zipimporter_cache(normalized_path, cache) + + +def _remove_and_clear_zip_directory_cache_data(normalized_path): + def clear_and_remove_cached_zip_archive_directory_data(path, old_entry): + old_entry.clear() + + _update_zipimporter_cache( + normalized_path, zipimport._zip_directory_cache, + updater=clear_and_remove_cached_zip_archive_directory_data) + + +# PyPy Python implementation does not allow directly writing to the +# zipimport._zip_directory_cache and so prevents us from attempting to correct +# its content. The best we can do there is clear the problematic cache content +# and have PyPy repopulate it as needed. The downside is that if there are any +# stale zipimport.zipimporter instances laying around, attempting to use them +# will fail due to not having its zip archive directory information available +# instead of being automatically corrected to use the new correct zip archive +# directory information. +if '__pypy__' in sys.builtin_module_names: + _replace_zip_directory_cache_data = \ + _remove_and_clear_zip_directory_cache_data +else: + + def _replace_zip_directory_cache_data(normalized_path): + def replace_cached_zip_archive_directory_data(path, old_entry): + # N.B. In theory, we could load the zip directory information just + # once for all updated path spellings, and then copy it locally and + # update its contained path strings to contain the correct + # spelling, but that seems like a way too invasive move (this cache + # structure is not officially documented anywhere and could in + # theory change with new Python releases) for no significant + # benefit. + old_entry.clear() + zipimport.zipimporter(path) + old_entry.update(zipimport._zip_directory_cache[path]) + return old_entry + + _update_zipimporter_cache( + normalized_path, zipimport._zip_directory_cache, + updater=replace_cached_zip_archive_directory_data) + + +def is_python(text, filename=''): + "Is this string a valid Python script?" + try: + compile(text, filename, 'exec') + except (SyntaxError, TypeError): + return False + else: + return True + + +def is_sh(executable): + """Determine if the specified executable is a .sh (contains a #! line)""" + try: + with io.open(executable, encoding='latin-1') as fp: + magic = fp.read(2) + except (OSError, IOError): + return executable + return magic == '#!' + + +def nt_quote_arg(arg): + """Quote a command line argument according to Windows parsing rules""" + return subprocess.list2cmdline([arg]) + + +def is_python_script(script_text, filename): + """Is this text, as a whole, a Python script? (as opposed to shell/bat/etc. + """ + if filename.endswith('.py') or filename.endswith('.pyw'): + return True # extension says it's Python + if is_python(script_text, filename): + return True # it's syntactically valid Python + if script_text.startswith('#!'): + # It begins with a '#!' line, so check if 'python' is in it somewhere + return 'python' in script_text.splitlines()[0].lower() + + return False # Not any Python I can recognize + + +try: + from os import chmod as _chmod +except ImportError: + # Jython compatibility + def _chmod(*args): + pass + + +def chmod(path, mode): + log.debug("changing mode of %s to %o", path, mode) + try: + _chmod(path, mode) + except os.error as e: + log.debug("chmod failed: %s", e) + + +class CommandSpec(list): + """ + A command spec for a #! header, specified as a list of arguments akin to + those passed to Popen. + """ + + options = [] + split_args = dict() + + @classmethod + def best(cls): + """ + Choose the best CommandSpec class based on environmental conditions. + """ + return cls + + @classmethod + def _sys_executable(cls): + _default = os.path.normpath(sys.executable) + return os.environ.get('__PYVENV_LAUNCHER__', _default) + + @classmethod + def from_param(cls, param): + """ + Construct a CommandSpec from a parameter to build_scripts, which may + be None. + """ + if isinstance(param, cls): + return param + if isinstance(param, list): + return cls(param) + if param is None: + return cls.from_environment() + # otherwise, assume it's a string. + return cls.from_string(param) + + @classmethod + def from_environment(cls): + return cls([cls._sys_executable()]) + + @classmethod + def from_string(cls, string): + """ + Construct a command spec from a simple string representing a command + line parseable by shlex.split. + """ + items = shlex.split(string, **cls.split_args) + return cls(items) + + def install_options(self, script_text): + self.options = shlex.split(self._extract_options(script_text)) + cmdline = subprocess.list2cmdline(self) + if not isascii(cmdline): + self.options[:0] = ['-x'] + + @staticmethod + def _extract_options(orig_script): + """ + Extract any options from the first line of the script. + """ + first = (orig_script + '\n').splitlines()[0] + match = _first_line_re().match(first) + options = match.group(1) or '' if match else '' + return options.strip() + + def as_header(self): + return self._render(self + list(self.options)) + + @staticmethod + def _strip_quotes(item): + _QUOTES = '"\'' + for q in _QUOTES: + if item.startswith(q) and item.endswith(q): + return item[1:-1] + return item + + @staticmethod + def _render(items): + cmdline = subprocess.list2cmdline( + CommandSpec._strip_quotes(item.strip()) for item in items) + return '#!' + cmdline + '\n' + + +# For pbr compat; will be removed in a future version. +sys_executable = CommandSpec._sys_executable() + + +class WindowsCommandSpec(CommandSpec): + split_args = dict(posix=False) + + +class ScriptWriter: + """ + Encapsulates behavior around writing entry point scripts for console and + gui apps. + """ + + template = textwrap.dedent(r""" + # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r + __requires__ = %(spec)r + import re + import sys + from pkg_resources import load_entry_point + + if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) + sys.exit( + load_entry_point(%(spec)r, %(group)r, %(name)r)() + ) + """).lstrip() + + command_spec_class = CommandSpec + + @classmethod + def get_script_args(cls, dist, executable=None, wininst=False): + # for backward compatibility + warnings.warn("Use get_args", EasyInstallDeprecationWarning) + writer = (WindowsScriptWriter if wininst else ScriptWriter).best() + header = cls.get_script_header("", executable, wininst) + return writer.get_args(dist, header) + + @classmethod + def get_script_header(cls, script_text, executable=None, wininst=False): + # for backward compatibility + warnings.warn("Use get_header", EasyInstallDeprecationWarning, stacklevel=2) + if wininst: + executable = "python.exe" + return cls.get_header(script_text, executable) + + @classmethod + def get_args(cls, dist, header=None): + """ + Yield write_script() argument tuples for a distribution's + console_scripts and gui_scripts entry points. + """ + if header is None: + header = cls.get_header() + spec = str(dist.as_requirement()) + for type_ in 'console', 'gui': + group = type_ + '_scripts' + for name, ep in dist.get_entry_map(group).items(): + cls._ensure_safe_name(name) + script_text = cls.template % locals() + args = cls._get_script_args(type_, name, header, script_text) + for res in args: + yield res + + @staticmethod + def _ensure_safe_name(name): + """ + Prevent paths in *_scripts entry point names. + """ + has_path_sep = re.search(r'[\\/]', name) + if has_path_sep: + raise ValueError("Path separators not allowed in script names") + + @classmethod + def get_writer(cls, force_windows): + # for backward compatibility + warnings.warn("Use best", EasyInstallDeprecationWarning) + return WindowsScriptWriter.best() if force_windows else cls.best() + + @classmethod + def best(cls): + """ + Select the best ScriptWriter for this environment. + """ + if sys.platform == 'win32' or (os.name == 'java' and os._name == 'nt'): + return WindowsScriptWriter.best() + else: + return cls + + @classmethod + def _get_script_args(cls, type_, name, header, script_text): + # Simply write the stub with no extension. + yield (name, header + script_text) + + @classmethod + def get_header(cls, script_text="", executable=None): + """Create a #! line, getting options (if any) from script_text""" + cmd = cls.command_spec_class.best().from_param(executable) + cmd.install_options(script_text) + return cmd.as_header() + + +class WindowsScriptWriter(ScriptWriter): + command_spec_class = WindowsCommandSpec + + @classmethod + def get_writer(cls): + # for backward compatibility + warnings.warn("Use best", EasyInstallDeprecationWarning) + return cls.best() + + @classmethod + def best(cls): + """ + Select the best ScriptWriter suitable for Windows + """ + writer_lookup = dict( + executable=WindowsExecutableLauncherWriter, + natural=cls, + ) + # for compatibility, use the executable launcher by default + launcher = os.environ.get('SETUPTOOLS_LAUNCHER', 'executable') + return writer_lookup[launcher] + + @classmethod + def _get_script_args(cls, type_, name, header, script_text): + "For Windows, add a .py extension" + ext = dict(console='.pya', gui='.pyw')[type_] + if ext not in os.environ['PATHEXT'].lower().split(';'): + msg = ( + "{ext} not listed in PATHEXT; scripts will not be " + "recognized as executables." + ).format(**locals()) + warnings.warn(msg, UserWarning) + old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', '.pyw', '.exe'] + old.remove(ext) + header = cls._adjust_header(type_, header) + blockers = [name + x for x in old] + yield name + ext, header + script_text, 't', blockers + + @classmethod + def _adjust_header(cls, type_, orig_header): + """ + Make sure 'pythonw' is used for gui and and 'python' is used for + console (regardless of what sys.executable is). + """ + pattern = 'pythonw.exe' + repl = 'python.exe' + if type_ == 'gui': + pattern, repl = repl, pattern + pattern_ob = re.compile(re.escape(pattern), re.IGNORECASE) + new_header = pattern_ob.sub(string=orig_header, repl=repl) + return new_header if cls._use_header(new_header) else orig_header + + @staticmethod + def _use_header(new_header): + """ + Should _adjust_header use the replaced header? + + On non-windows systems, always use. On + Windows systems, only use the replaced header if it resolves + to an executable on the system. + """ + clean_header = new_header[2:-1].strip('"') + return sys.platform != 'win32' or find_executable(clean_header) + + +class WindowsExecutableLauncherWriter(WindowsScriptWriter): + @classmethod + def _get_script_args(cls, type_, name, header, script_text): + """ + For Windows, add a .py extension and an .exe launcher + """ + if type_ == 'gui': + launcher_type = 'gui' + ext = '-script.pyw' + old = ['.pyw'] + else: + launcher_type = 'cli' + ext = '-script.py' + old = ['.py', '.pyc', '.pyo'] + hdr = cls._adjust_header(type_, header) + blockers = [name + x for x in old] + yield (name + ext, hdr + script_text, 't', blockers) + yield ( + name + '.exe', get_win_launcher(launcher_type), + 'b' # write in binary mode + ) + if not is_64bit(): + # install a manifest for the launcher to prevent Windows + # from detecting it as an installer (which it will for + # launchers like easy_install.exe). Consider only + # adding a manifest for launchers detected as installers. + # See Distribute #143 for details. + m_name = name + '.exe.manifest' + yield (m_name, load_launcher_manifest(name), 't') + + +# for backward-compatibility +get_script_args = ScriptWriter.get_script_args +get_script_header = ScriptWriter.get_script_header + + +def get_win_launcher(type): + """ + Load the Windows launcher (executable) suitable for launching a script. + + `type` should be either 'cli' or 'gui' + + Returns the executable as a byte string. + """ + launcher_fn = '%s.exe' % type + if is_64bit(): + launcher_fn = launcher_fn.replace(".", "-64.") + else: + launcher_fn = launcher_fn.replace(".", "-32.") + return resource_string('setuptools', launcher_fn) + + +def load_launcher_manifest(name): + manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml') + if six.PY2: + return manifest % vars() + else: + return manifest.decode('utf-8') % vars() + + +def rmtree(path, ignore_errors=False, onerror=auto_chmod): + return shutil.rmtree(path, ignore_errors, onerror) + + +def current_umask(): + tmp = os.umask(0o022) + os.umask(tmp) + return tmp + + +def bootstrap(): + # This function is called when setuptools*.egg is run using /bin/sh + import setuptools + + argv0 = os.path.dirname(setuptools.__path__[0]) + sys.argv[0] = argv0 + sys.argv.append(argv0) + main() + + +def main(argv=None, **kw): + from setuptools import setup + from setuptools.dist import Distribution + + class DistributionWithoutHelpCommands(Distribution): + common_usage = "" + + def _show_help(self, *args, **kw): + with _patch_usage(): + Distribution._show_help(self, *args, **kw) + + if argv is None: + argv = sys.argv[1:] + + with _patch_usage(): + setup( + script_args=['-q', 'easy_install', '-v'] + argv, + script_name=sys.argv[0] or 'easy_install', + distclass=DistributionWithoutHelpCommands, + **kw + ) + + +@contextlib.contextmanager +def _patch_usage(): + import distutils.core + USAGE = textwrap.dedent(""" + usage: %(script)s [options] requirement_or_url ... + or: %(script)s --help + """).lstrip() + + def gen_usage(script_name): + return USAGE % dict( + script=os.path.basename(script_name), + ) + + saved = distutils.core.gen_usage + distutils.core.gen_usage = gen_usage + try: + yield + finally: + distutils.core.gen_usage = saved + +class EasyInstallDeprecationWarning(SetuptoolsDeprecationWarning): + """Class for warning about deprecations in EasyInstall in SetupTools. Not ignored by default, unlike DeprecationWarning.""" + diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/egg_info.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/egg_info.py new file mode 100644 index 0000000000000000000000000000000000000000..5d8f451ee4555449177821ece5ad9807ffefed11 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/egg_info.py @@ -0,0 +1,717 @@ +"""setuptools.command.egg_info + +Create a distribution's .egg-info directory and contents""" + +from distutils.filelist import FileList as _FileList +from distutils.errors import DistutilsInternalError +from distutils.util import convert_path +from distutils import log +import distutils.errors +import distutils.filelist +import os +import re +import sys +import io +import warnings +import time +import collections + +from setuptools.extern import six +from setuptools.extern.six.moves import map + +from setuptools import Command +from setuptools.command.sdist import sdist +from setuptools.command.sdist import walk_revctrl +from setuptools.command.setopt import edit_config +from setuptools.command import bdist_egg +from pkg_resources import ( + parse_requirements, safe_name, parse_version, + safe_version, yield_lines, EntryPoint, iter_entry_points, to_filename) +import setuptools.unicode_utils as unicode_utils +from setuptools.glob import glob + +from setuptools.extern import packaging +from setuptools import SetuptoolsDeprecationWarning + +def translate_pattern(glob): + """ + Translate a file path glob like '*.txt' in to a regular expression. + This differs from fnmatch.translate which allows wildcards to match + directory separators. It also knows about '**/' which matches any number of + directories. + """ + pat = '' + + # This will split on '/' within [character classes]. This is deliberate. + chunks = glob.split(os.path.sep) + + sep = re.escape(os.sep) + valid_char = '[^%s]' % (sep,) + + for c, chunk in enumerate(chunks): + last_chunk = c == len(chunks) - 1 + + # Chunks that are a literal ** are globstars. They match anything. + if chunk == '**': + if last_chunk: + # Match anything if this is the last component + pat += '.*' + else: + # Match '(name/)*' + pat += '(?:%s+%s)*' % (valid_char, sep) + continue # Break here as the whole path component has been handled + + # Find any special characters in the remainder + i = 0 + chunk_len = len(chunk) + while i < chunk_len: + char = chunk[i] + if char == '*': + # Match any number of name characters + pat += valid_char + '*' + elif char == '?': + # Match a name character + pat += valid_char + elif char == '[': + # Character class + inner_i = i + 1 + # Skip initial !/] chars + if inner_i < chunk_len and chunk[inner_i] == '!': + inner_i = inner_i + 1 + if inner_i < chunk_len and chunk[inner_i] == ']': + inner_i = inner_i + 1 + + # Loop till the closing ] is found + while inner_i < chunk_len and chunk[inner_i] != ']': + inner_i = inner_i + 1 + + if inner_i >= chunk_len: + # Got to the end of the string without finding a closing ] + # Do not treat this as a matching group, but as a literal [ + pat += re.escape(char) + else: + # Grab the insides of the [brackets] + inner = chunk[i + 1:inner_i] + char_class = '' + + # Class negation + if inner[0] == '!': + char_class = '^' + inner = inner[1:] + + char_class += re.escape(inner) + pat += '[%s]' % (char_class,) + + # Skip to the end ] + i = inner_i + else: + pat += re.escape(char) + i += 1 + + # Join each chunk with the dir separator + if not last_chunk: + pat += sep + + pat += r'\Z' + return re.compile(pat, flags=re.MULTILINE|re.DOTALL) + + +class InfoCommon: + tag_build = None + tag_date = None + + @property + def name(self): + return safe_name(self.distribution.get_name()) + + def tagged_version(self): + version = self.distribution.get_version() + # egg_info may be called more than once for a distribution, + # in which case the version string already contains all tags. + if self.vtags and version.endswith(self.vtags): + return safe_version(version) + return safe_version(version + self.vtags) + + def tags(self): + version = '' + if self.tag_build: + version += self.tag_build + if self.tag_date: + version += time.strftime("-%Y%m%d") + return version + vtags = property(tags) + + +class egg_info(InfoCommon, Command): + description = "create a distribution's .egg-info directory" + + user_options = [ + ('egg-base=', 'e', "directory containing .egg-info directories" + " (default: top of the source tree)"), + ('tag-date', 'd', "Add date stamp (e.g. 20050528) to version number"), + ('tag-build=', 'b', "Specify explicit tag to add to version number"), + ('no-date', 'D', "Don't include date stamp [default]"), + ] + + boolean_options = ['tag-date'] + negative_opt = { + 'no-date': 'tag-date', + } + + def initialize_options(self): + self.egg_base = None + self.egg_name = None + self.egg_info = None + self.egg_version = None + self.broken_egg_info = False + + #################################### + # allow the 'tag_svn_revision' to be detected and + # set, supporting sdists built on older Setuptools. + @property + def tag_svn_revision(self): + pass + + @tag_svn_revision.setter + def tag_svn_revision(self, value): + pass + #################################### + + def save_version_info(self, filename): + """ + Materialize the value of date into the + build tag. Install build keys in a deterministic order + to avoid arbitrary reordering on subsequent builds. + """ + egg_info = collections.OrderedDict() + # follow the order these keys would have been added + # when PYTHONHASHSEED=0 + egg_info['tag_build'] = self.tags() + egg_info['tag_date'] = 0 + edit_config(filename, dict(egg_info=egg_info)) + + def finalize_options(self): + # Note: we need to capture the current value returned + # by `self.tagged_version()`, so we can later update + # `self.distribution.metadata.version` without + # repercussions. + self.egg_name = self.name + self.egg_version = self.tagged_version() + parsed_version = parse_version(self.egg_version) + + try: + is_version = isinstance(parsed_version, packaging.version.Version) + spec = ( + "%s==%s" if is_version else "%s===%s" + ) + list( + parse_requirements(spec % (self.egg_name, self.egg_version)) + ) + except ValueError: + raise distutils.errors.DistutilsOptionError( + "Invalid distribution name or version syntax: %s-%s" % + (self.egg_name, self.egg_version) + ) + + if self.egg_base is None: + dirs = self.distribution.package_dir + self.egg_base = (dirs or {}).get('', os.curdir) + + self.ensure_dirname('egg_base') + self.egg_info = to_filename(self.egg_name) + '.egg-info' + if self.egg_base != os.curdir: + self.egg_info = os.path.join(self.egg_base, self.egg_info) + if '-' in self.egg_name: + self.check_broken_egg_info() + + # Set package version for the benefit of dumber commands + # (e.g. sdist, bdist_wininst, etc.) + # + self.distribution.metadata.version = self.egg_version + + # If we bootstrapped around the lack of a PKG-INFO, as might be the + # case in a fresh checkout, make sure that any special tags get added + # to the version info + # + pd = self.distribution._patched_dist + if pd is not None and pd.key == self.egg_name.lower(): + pd._version = self.egg_version + pd._parsed_version = parse_version(self.egg_version) + self.distribution._patched_dist = None + + def write_or_delete_file(self, what, filename, data, force=False): + """Write `data` to `filename` or delete if empty + + If `data` is non-empty, this routine is the same as ``write_file()``. + If `data` is empty but not ``None``, this is the same as calling + ``delete_file(filename)`. If `data` is ``None``, then this is a no-op + unless `filename` exists, in which case a warning is issued about the + orphaned file (if `force` is false), or deleted (if `force` is true). + """ + if data: + self.write_file(what, filename, data) + elif os.path.exists(filename): + if data is None and not force: + log.warn( + "%s not set in setup(), but %s exists", what, filename + ) + return + else: + self.delete_file(filename) + + def write_file(self, what, filename, data): + """Write `data` to `filename` (if not a dry run) after announcing it + + `what` is used in a log message to identify what is being written + to the file. + """ + log.info("writing %s to %s", what, filename) + if six.PY3: + data = data.encode("utf-8") + if not self.dry_run: + f = open(filename, 'wb') + f.write(data) + f.close() + + def delete_file(self, filename): + """Delete `filename` (if not a dry run) after announcing it""" + log.info("deleting %s", filename) + if not self.dry_run: + os.unlink(filename) + + def run(self): + self.mkpath(self.egg_info) + os.utime(self.egg_info, None) + installer = self.distribution.fetch_build_egg + for ep in iter_entry_points('egg_info.writers'): + ep.require(installer=installer) + writer = ep.resolve() + writer(self, ep.name, os.path.join(self.egg_info, ep.name)) + + # Get rid of native_libs.txt if it was put there by older bdist_egg + nl = os.path.join(self.egg_info, "native_libs.txt") + if os.path.exists(nl): + self.delete_file(nl) + + self.find_sources() + + def find_sources(self): + """Generate SOURCES.txt manifest file""" + manifest_filename = os.path.join(self.egg_info, "SOURCES.txt") + mm = manifest_maker(self.distribution) + mm.manifest = manifest_filename + mm.run() + self.filelist = mm.filelist + + def check_broken_egg_info(self): + bei = self.egg_name + '.egg-info' + if self.egg_base != os.curdir: + bei = os.path.join(self.egg_base, bei) + if os.path.exists(bei): + log.warn( + "-" * 78 + '\n' + "Note: Your current .egg-info directory has a '-' in its name;" + '\nthis will not work correctly with "setup.py develop".\n\n' + 'Please rename %s to %s to correct this problem.\n' + '-' * 78, + bei, self.egg_info + ) + self.broken_egg_info = self.egg_info + self.egg_info = bei # make it work for now + + +class FileList(_FileList): + # Implementations of the various MANIFEST.in commands + + def process_template_line(self, line): + # Parse the line: split it up, make sure the right number of words + # is there, and return the relevant words. 'action' is always + # defined: it's the first word of the line. Which of the other + # three are defined depends on the action; it'll be either + # patterns, (dir and patterns), or (dir_pattern). + (action, patterns, dir, dir_pattern) = self._parse_template_line(line) + + # OK, now we know that the action is valid and we have the + # right number of words on the line for that action -- so we + # can proceed with minimal error-checking. + if action == 'include': + self.debug_print("include " + ' '.join(patterns)) + for pattern in patterns: + if not self.include(pattern): + log.warn("warning: no files found matching '%s'", pattern) + + elif action == 'exclude': + self.debug_print("exclude " + ' '.join(patterns)) + for pattern in patterns: + if not self.exclude(pattern): + log.warn(("warning: no previously-included files " + "found matching '%s'"), pattern) + + elif action == 'global-include': + self.debug_print("global-include " + ' '.join(patterns)) + for pattern in patterns: + if not self.global_include(pattern): + log.warn(("warning: no files found matching '%s' " + "anywhere in distribution"), pattern) + + elif action == 'global-exclude': + self.debug_print("global-exclude " + ' '.join(patterns)) + for pattern in patterns: + if not self.global_exclude(pattern): + log.warn(("warning: no previously-included files matching " + "'%s' found anywhere in distribution"), + pattern) + + elif action == 'recursive-include': + self.debug_print("recursive-include %s %s" % + (dir, ' '.join(patterns))) + for pattern in patterns: + if not self.recursive_include(dir, pattern): + log.warn(("warning: no files found matching '%s' " + "under directory '%s'"), + pattern, dir) + + elif action == 'recursive-exclude': + self.debug_print("recursive-exclude %s %s" % + (dir, ' '.join(patterns))) + for pattern in patterns: + if not self.recursive_exclude(dir, pattern): + log.warn(("warning: no previously-included files matching " + "'%s' found under directory '%s'"), + pattern, dir) + + elif action == 'graft': + self.debug_print("graft " + dir_pattern) + if not self.graft(dir_pattern): + log.warn("warning: no directories found matching '%s'", + dir_pattern) + + elif action == 'prune': + self.debug_print("prune " + dir_pattern) + if not self.prune(dir_pattern): + log.warn(("no previously-included directories found " + "matching '%s'"), dir_pattern) + + else: + raise DistutilsInternalError( + "this cannot happen: invalid action '%s'" % action) + + def _remove_files(self, predicate): + """ + Remove all files from the file list that match the predicate. + Return True if any matching files were removed + """ + found = False + for i in range(len(self.files) - 1, -1, -1): + if predicate(self.files[i]): + self.debug_print(" removing " + self.files[i]) + del self.files[i] + found = True + return found + + def include(self, pattern): + """Include files that match 'pattern'.""" + found = [f for f in glob(pattern) if not os.path.isdir(f)] + self.extend(found) + return bool(found) + + def exclude(self, pattern): + """Exclude files that match 'pattern'.""" + match = translate_pattern(pattern) + return self._remove_files(match.match) + + def recursive_include(self, dir, pattern): + """ + Include all files anywhere in 'dir/' that match the pattern. + """ + full_pattern = os.path.join(dir, '**', pattern) + found = [f for f in glob(full_pattern, recursive=True) + if not os.path.isdir(f)] + self.extend(found) + return bool(found) + + def recursive_exclude(self, dir, pattern): + """ + Exclude any file anywhere in 'dir/' that match the pattern. + """ + match = translate_pattern(os.path.join(dir, '**', pattern)) + return self._remove_files(match.match) + + def graft(self, dir): + """Include all files from 'dir/'.""" + found = [ + item + for match_dir in glob(dir) + for item in distutils.filelist.findall(match_dir) + ] + self.extend(found) + return bool(found) + + def prune(self, dir): + """Filter out files from 'dir/'.""" + match = translate_pattern(os.path.join(dir, '**')) + return self._remove_files(match.match) + + def global_include(self, pattern): + """ + Include all files anywhere in the current directory that match the + pattern. This is very inefficient on large file trees. + """ + if self.allfiles is None: + self.findall() + match = translate_pattern(os.path.join('**', pattern)) + found = [f for f in self.allfiles if match.match(f)] + self.extend(found) + return bool(found) + + def global_exclude(self, pattern): + """ + Exclude all files anywhere that match the pattern. + """ + match = translate_pattern(os.path.join('**', pattern)) + return self._remove_files(match.match) + + def append(self, item): + if item.endswith('\r'): # Fix older sdists built on Windows + item = item[:-1] + path = convert_path(item) + + if self._safe_path(path): + self.files.append(path) + + def extend(self, paths): + self.files.extend(filter(self._safe_path, paths)) + + def _repair(self): + """ + Replace self.files with only safe paths + + Because some owners of FileList manipulate the underlying + ``files`` attribute directly, this method must be called to + repair those paths. + """ + self.files = list(filter(self._safe_path, self.files)) + + def _safe_path(self, path): + enc_warn = "'%s' not %s encodable -- skipping" + + # To avoid accidental trans-codings errors, first to unicode + u_path = unicode_utils.filesys_decode(path) + if u_path is None: + log.warn("'%s' in unexpected encoding -- skipping" % path) + return False + + # Must ensure utf-8 encodability + utf8_path = unicode_utils.try_encode(u_path, "utf-8") + if utf8_path is None: + log.warn(enc_warn, path, 'utf-8') + return False + + try: + # accept is either way checks out + if os.path.exists(u_path) or os.path.exists(utf8_path): + return True + # this will catch any encode errors decoding u_path + except UnicodeEncodeError: + log.warn(enc_warn, path, sys.getfilesystemencoding()) + + +class manifest_maker(sdist): + template = "MANIFEST.in" + + def initialize_options(self): + self.use_defaults = 1 + self.prune = 1 + self.manifest_only = 1 + self.force_manifest = 1 + + def finalize_options(self): + pass + + def run(self): + self.filelist = FileList() + if not os.path.exists(self.manifest): + self.write_manifest() # it must exist so it'll get in the list + self.add_defaults() + if os.path.exists(self.template): + self.read_template() + self.prune_file_list() + self.filelist.sort() + self.filelist.remove_duplicates() + self.write_manifest() + + def _manifest_normalize(self, path): + path = unicode_utils.filesys_decode(path) + return path.replace(os.sep, '/') + + def write_manifest(self): + """ + Write the file list in 'self.filelist' to the manifest file + named by 'self.manifest'. + """ + self.filelist._repair() + + # Now _repairs should encodability, but not unicode + files = [self._manifest_normalize(f) for f in self.filelist.files] + msg = "writing manifest file '%s'" % self.manifest + self.execute(write_file, (self.manifest, files), msg) + + def warn(self, msg): + if not self._should_suppress_warning(msg): + sdist.warn(self, msg) + + @staticmethod + def _should_suppress_warning(msg): + """ + suppress missing-file warnings from sdist + """ + return re.match(r"standard file .*not found", msg) + + def add_defaults(self): + sdist.add_defaults(self) + self.check_license() + self.filelist.append(self.template) + self.filelist.append(self.manifest) + rcfiles = list(walk_revctrl()) + if rcfiles: + self.filelist.extend(rcfiles) + elif os.path.exists(self.manifest): + self.read_manifest() + + if os.path.exists("setup.py"): + # setup.py should be included by default, even if it's not + # the script called to create the sdist + self.filelist.append("setup.py") + + ei_cmd = self.get_finalized_command('egg_info') + self.filelist.graft(ei_cmd.egg_info) + + def prune_file_list(self): + build = self.get_finalized_command('build') + base_dir = self.distribution.get_fullname() + self.filelist.prune(build.build_base) + self.filelist.prune(base_dir) + sep = re.escape(os.sep) + self.filelist.exclude_pattern(r'(^|' + sep + r')(RCS|CVS|\.svn)' + sep, + is_regex=1) + + +def write_file(filename, contents): + """Create a file with the specified name and write 'contents' (a + sequence of strings without line terminators) to it. + """ + contents = "\n".join(contents) + + # assuming the contents has been vetted for utf-8 encoding + contents = contents.encode("utf-8") + + with open(filename, "wb") as f: # always write POSIX-style manifest + f.write(contents) + + +def write_pkg_info(cmd, basename, filename): + log.info("writing %s", filename) + if not cmd.dry_run: + metadata = cmd.distribution.metadata + metadata.version, oldver = cmd.egg_version, metadata.version + metadata.name, oldname = cmd.egg_name, metadata.name + + try: + # write unescaped data to PKG-INFO, so older pkg_resources + # can still parse it + metadata.write_pkg_info(cmd.egg_info) + finally: + metadata.name, metadata.version = oldname, oldver + + safe = getattr(cmd.distribution, 'zip_safe', None) + + bdist_egg.write_safety_flag(cmd.egg_info, safe) + + +def warn_depends_obsolete(cmd, basename, filename): + if os.path.exists(filename): + log.warn( + "WARNING: 'depends.txt' is not used by setuptools 0.6!\n" + "Use the install_requires/extras_require setup() args instead." + ) + + +def _write_requirements(stream, reqs): + lines = yield_lines(reqs or ()) + append_cr = lambda line: line + '\n' + lines = map(append_cr, lines) + stream.writelines(lines) + + +def write_requirements(cmd, basename, filename): + dist = cmd.distribution + data = six.StringIO() + _write_requirements(data, dist.install_requires) + extras_require = dist.extras_require or {} + for extra in sorted(extras_require): + data.write('\n[{extra}]\n'.format(**vars())) + _write_requirements(data, extras_require[extra]) + cmd.write_or_delete_file("requirements", filename, data.getvalue()) + + +def write_setup_requirements(cmd, basename, filename): + data = io.StringIO() + _write_requirements(data, cmd.distribution.setup_requires) + cmd.write_or_delete_file("setup-requirements", filename, data.getvalue()) + + +def write_toplevel_names(cmd, basename, filename): + pkgs = dict.fromkeys( + [ + k.split('.', 1)[0] + for k in cmd.distribution.iter_distribution_names() + ] + ) + cmd.write_file("top-level names", filename, '\n'.join(sorted(pkgs)) + '\n') + + +def overwrite_arg(cmd, basename, filename): + write_arg(cmd, basename, filename, True) + + +def write_arg(cmd, basename, filename, force=False): + argname = os.path.splitext(basename)[0] + value = getattr(cmd.distribution, argname, None) + if value is not None: + value = '\n'.join(value) + '\n' + cmd.write_or_delete_file(argname, filename, value, force) + + +def write_entries(cmd, basename, filename): + ep = cmd.distribution.entry_points + + if isinstance(ep, six.string_types) or ep is None: + data = ep + elif ep is not None: + data = [] + for section, contents in sorted(ep.items()): + if not isinstance(contents, six.string_types): + contents = EntryPoint.parse_group(section, contents) + contents = '\n'.join(sorted(map(str, contents.values()))) + data.append('[%s]\n%s\n\n' % (section, contents)) + data = ''.join(data) + + cmd.write_or_delete_file('entry points', filename, data, True) + + +def get_pkg_info_revision(): + """ + Get a -r### off of PKG-INFO Version in case this is an sdist of + a subversion revision. + """ + warnings.warn("get_pkg_info_revision is deprecated.", EggInfoDeprecationWarning) + if os.path.exists('PKG-INFO'): + with io.open('PKG-INFO') as f: + for line in f: + match = re.match(r"Version:.*-r(\d+)\s*$", line) + if match: + return int(match.group(1)) + return 0 + + +class EggInfoDeprecationWarning(SetuptoolsDeprecationWarning): + """Class for warning about deprecations in eggInfo in setupTools. Not ignored by default, unlike DeprecationWarning.""" diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/install.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/install.py new file mode 100644 index 0000000000000000000000000000000000000000..31a5ddb57739f8dc132cef1b9f5d252befb67ca7 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/install.py @@ -0,0 +1,125 @@ +from distutils.errors import DistutilsArgError +import inspect +import glob +import warnings +import platform +import distutils.command.install as orig + +import setuptools + +# Prior to numpy 1.9, NumPy relies on the '_install' name, so provide it for +# now. See https://github.com/pypa/setuptools/issues/199/ +_install = orig.install + + +class install(orig.install): + """Use easy_install to install the package, w/dependencies""" + + user_options = orig.install.user_options + [ + ('old-and-unmanageable', None, "Try not to use this!"), + ('single-version-externally-managed', None, + "used by system package builders to create 'flat' eggs"), + ] + boolean_options = orig.install.boolean_options + [ + 'old-and-unmanageable', 'single-version-externally-managed', + ] + new_commands = [ + ('install_egg_info', lambda self: True), + ('install_scripts', lambda self: True), + ] + _nc = dict(new_commands) + + def initialize_options(self): + orig.install.initialize_options(self) + self.old_and_unmanageable = None + self.single_version_externally_managed = None + + def finalize_options(self): + orig.install.finalize_options(self) + if self.root: + self.single_version_externally_managed = True + elif self.single_version_externally_managed: + if not self.root and not self.record: + raise DistutilsArgError( + "You must specify --record or --root when building system" + " packages" + ) + + def handle_extra_path(self): + if self.root or self.single_version_externally_managed: + # explicit backward-compatibility mode, allow extra_path to work + return orig.install.handle_extra_path(self) + + # Ignore extra_path when installing an egg (or being run by another + # command without --root or --single-version-externally-managed + self.path_file = None + self.extra_dirs = '' + + def run(self): + # Explicit request for old-style install? Just do it + if self.old_and_unmanageable or self.single_version_externally_managed: + return orig.install.run(self) + + if not self._called_from_setup(inspect.currentframe()): + # Run in backward-compatibility mode to support bdist_* commands. + orig.install.run(self) + else: + self.do_egg_install() + + @staticmethod + def _called_from_setup(run_frame): + """ + Attempt to detect whether run() was called from setup() or by another + command. If called by setup(), the parent caller will be the + 'run_command' method in 'distutils.dist', and *its* caller will be + the 'run_commands' method. If called any other way, the + immediate caller *might* be 'run_command', but it won't have been + called by 'run_commands'. Return True in that case or if a call stack + is unavailable. Return False otherwise. + """ + if run_frame is None: + msg = "Call stack not available. bdist_* commands may fail." + warnings.warn(msg) + if platform.python_implementation() == 'IronPython': + msg = "For best results, pass -X:Frames to enable call stack." + warnings.warn(msg) + return True + res = inspect.getouterframes(run_frame)[2] + caller, = res[:1] + info = inspect.getframeinfo(caller) + caller_module = caller.f_globals.get('__name__', '') + return ( + caller_module == 'distutils.dist' + and info.function == 'run_commands' + ) + + def do_egg_install(self): + + easy_install = self.distribution.get_command_class('easy_install') + + cmd = easy_install( + self.distribution, args="x", root=self.root, record=self.record, + ) + cmd.ensure_finalized() # finalize before bdist_egg munges install cmd + cmd.always_copy_from = '.' # make sure local-dir eggs get installed + + # pick up setup-dir .egg files only: no .egg-info + cmd.package_index.scan(glob.glob('*.egg')) + + self.run_command('bdist_egg') + args = [self.distribution.get_command_obj('bdist_egg').egg_output] + + if setuptools.bootstrap_install_from: + # Bootstrap self-installation of setuptools + args.insert(0, setuptools.bootstrap_install_from) + + cmd.args = args + cmd.run() + setuptools.bootstrap_install_from = None + + +# XXX Python 3.1 doesn't see _nc if this is inside the class +install.sub_commands = ( + [cmd for cmd in orig.install.sub_commands if cmd[0] not in install._nc] + + install.new_commands +) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/install_egg_info.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/install_egg_info.py new file mode 100644 index 0000000000000000000000000000000000000000..edc4718b686203312cea4487a30d8f7801f49b08 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/install_egg_info.py @@ -0,0 +1,62 @@ +from distutils import log, dir_util +import os + +from setuptools import Command +from setuptools import namespaces +from setuptools.archive_util import unpack_archive +import pkg_resources + + +class install_egg_info(namespaces.Installer, Command): + """Install an .egg-info directory for the package""" + + description = "Install an .egg-info directory for the package" + + user_options = [ + ('install-dir=', 'd', "directory to install to"), + ] + + def initialize_options(self): + self.install_dir = None + + def finalize_options(self): + self.set_undefined_options('install_lib', + ('install_dir', 'install_dir')) + ei_cmd = self.get_finalized_command("egg_info") + basename = pkg_resources.Distribution( + None, None, ei_cmd.egg_name, ei_cmd.egg_version + ).egg_name() + '.egg-info' + self.source = ei_cmd.egg_info + self.target = os.path.join(self.install_dir, basename) + self.outputs = [] + + def run(self): + self.run_command('egg_info') + if os.path.isdir(self.target) and not os.path.islink(self.target): + dir_util.remove_tree(self.target, dry_run=self.dry_run) + elif os.path.exists(self.target): + self.execute(os.unlink, (self.target,), "Removing " + self.target) + if not self.dry_run: + pkg_resources.ensure_directory(self.target) + self.execute( + self.copytree, (), "Copying %s to %s" % (self.source, self.target) + ) + self.install_namespaces() + + def get_outputs(self): + return self.outputs + + def copytree(self): + # Copy the .egg-info tree to site-packages + def skimmer(src, dst): + # filter out source-control directories; note that 'src' is always + # a '/'-separated path, regardless of platform. 'dst' is a + # platform-specific path. + for skip in '.svn/', 'CVS/': + if src.startswith(skip) or '/' + skip in src: + return None + self.outputs.append(dst) + log.debug("Copying %s to %s", src, dst) + return dst + + unpack_archive(self.source, self.target, skimmer) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/install_lib.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/install_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..07d659330930c66cf33615fcb72fe4f6df54326b --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/install_lib.py @@ -0,0 +1,121 @@ +import os +import sys +from itertools import product, starmap +import distutils.command.install_lib as orig + + +class install_lib(orig.install_lib): + """Don't add compiled flags to filenames of non-Python files""" + + def run(self): + self.build() + outfiles = self.install() + if outfiles is not None: + # always compile, in case we have any extension stubs to deal with + self.byte_compile(outfiles) + + def get_exclusions(self): + """ + Return a collections.Sized collections.Container of paths to be + excluded for single_version_externally_managed installations. + """ + all_packages = ( + pkg + for ns_pkg in self._get_SVEM_NSPs() + for pkg in self._all_packages(ns_pkg) + ) + + excl_specs = product(all_packages, self._gen_exclusion_paths()) + return set(starmap(self._exclude_pkg_path, excl_specs)) + + def _exclude_pkg_path(self, pkg, exclusion_path): + """ + Given a package name and exclusion path within that package, + compute the full exclusion path. + """ + parts = pkg.split('.') + [exclusion_path] + return os.path.join(self.install_dir, *parts) + + @staticmethod + def _all_packages(pkg_name): + """ + >>> list(install_lib._all_packages('foo.bar.baz')) + ['foo.bar.baz', 'foo.bar', 'foo'] + """ + while pkg_name: + yield pkg_name + pkg_name, sep, child = pkg_name.rpartition('.') + + def _get_SVEM_NSPs(self): + """ + Get namespace packages (list) but only for + single_version_externally_managed installations and empty otherwise. + """ + # TODO: is it necessary to short-circuit here? i.e. what's the cost + # if get_finalized_command is called even when namespace_packages is + # False? + if not self.distribution.namespace_packages: + return [] + + install_cmd = self.get_finalized_command('install') + svem = install_cmd.single_version_externally_managed + + return self.distribution.namespace_packages if svem else [] + + @staticmethod + def _gen_exclusion_paths(): + """ + Generate file paths to be excluded for namespace packages (bytecode + cache files). + """ + # always exclude the package module itself + yield '__init__.py' + + yield '__init__.pyc' + yield '__init__.pyo' + + if not hasattr(sys, 'implementation'): + return + + base = os.path.join('__pycache__', '__init__.' + sys.implementation.cache_tag) + yield base + '.pyc' + yield base + '.pyo' + yield base + '.opt-1.pyc' + yield base + '.opt-2.pyc' + + def copy_tree( + self, infile, outfile, + preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1 + ): + assert preserve_mode and preserve_times and not preserve_symlinks + exclude = self.get_exclusions() + + if not exclude: + return orig.install_lib.copy_tree(self, infile, outfile) + + # Exclude namespace package __init__.py* files from the output + + from setuptools.archive_util import unpack_directory + from distutils import log + + outfiles = [] + + def pf(src, dst): + if dst in exclude: + log.warn("Skipping installation of %s (namespace package)", + dst) + return False + + log.info("copying %s -> %s", src, os.path.dirname(dst)) + outfiles.append(dst) + return dst + + unpack_directory(infile, outfile, pf) + return outfiles + + def get_outputs(self): + outputs = orig.install_lib.get_outputs(self) + exclude = self.get_exclusions() + if exclude: + return [f for f in outputs if f not in exclude] + return outputs diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/install_scripts.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/install_scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..16234273a2d36b0b3d821a7a97bf8f03cf3f2948 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/install_scripts.py @@ -0,0 +1,65 @@ +from distutils import log +import distutils.command.install_scripts as orig +import os +import sys + +from pkg_resources import Distribution, PathMetadata, ensure_directory + + +class install_scripts(orig.install_scripts): + """Do normal script install, plus any egg_info wrapper scripts""" + + def initialize_options(self): + orig.install_scripts.initialize_options(self) + self.no_ep = False + + def run(self): + import setuptools.command.easy_install as ei + + self.run_command("egg_info") + if self.distribution.scripts: + orig.install_scripts.run(self) # run first to set up self.outfiles + else: + self.outfiles = [] + if self.no_ep: + # don't install entry point scripts into .egg file! + return + + ei_cmd = self.get_finalized_command("egg_info") + dist = Distribution( + ei_cmd.egg_base, PathMetadata(ei_cmd.egg_base, ei_cmd.egg_info), + ei_cmd.egg_name, ei_cmd.egg_version, + ) + bs_cmd = self.get_finalized_command('build_scripts') + exec_param = getattr(bs_cmd, 'executable', None) + bw_cmd = self.get_finalized_command("bdist_wininst") + is_wininst = getattr(bw_cmd, '_is_running', False) + writer = ei.ScriptWriter + if is_wininst: + exec_param = "python.exe" + writer = ei.WindowsScriptWriter + if exec_param == sys.executable: + # In case the path to the Python executable contains a space, wrap + # it so it's not split up. + exec_param = [exec_param] + # resolve the writer to the environment + writer = writer.best() + cmd = writer.command_spec_class.best().from_param(exec_param) + for args in writer.get_args(dist, cmd.as_header()): + self.write_script(*args) + + def write_script(self, script_name, contents, mode="t", *ignored): + """Write an executable file to the scripts directory""" + from setuptools.command.easy_install import chmod, current_umask + + log.info("Installing %s script to %s", script_name, self.install_dir) + target = os.path.join(self.install_dir, script_name) + self.outfiles.append(target) + + mask = current_umask() + if not self.dry_run: + ensure_directory(target) + f = open(target, "w" + mode) + f.write(contents) + f.close() + chmod(target, 0o777 - mask) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/launcher manifest.xml b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/launcher manifest.xml new file mode 100644 index 0000000000000000000000000000000000000000..5972a96d8ded85cc14147ffc1400ec67c3b5a578 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/launcher manifest.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/py36compat.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/py36compat.py new file mode 100644 index 0000000000000000000000000000000000000000..61063e7542586c05c3af21d31cd917ebd1118272 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/py36compat.py @@ -0,0 +1,136 @@ +import os +from glob import glob +from distutils.util import convert_path +from distutils.command import sdist + +from setuptools.extern.six.moves import filter + + +class sdist_add_defaults: + """ + Mix-in providing forward-compatibility for functionality as found in + distutils on Python 3.7. + + Do not edit the code in this class except to update functionality + as implemented in distutils. Instead, override in the subclass. + """ + + def add_defaults(self): + """Add all the default files to self.filelist: + - README or README.txt + - setup.py + - test/test*.py + - all pure Python modules mentioned in setup script + - all files pointed by package_data (build_py) + - all files defined in data_files. + - all files defined as scripts. + - all C sources listed as part of extensions or C libraries + in the setup script (doesn't catch C headers!) + Warns if (README or README.txt) or setup.py are missing; everything + else is optional. + """ + self._add_defaults_standards() + self._add_defaults_optional() + self._add_defaults_python() + self._add_defaults_data_files() + self._add_defaults_ext() + self._add_defaults_c_libs() + self._add_defaults_scripts() + + @staticmethod + def _cs_path_exists(fspath): + """ + Case-sensitive path existence check + + >>> sdist_add_defaults._cs_path_exists(__file__) + True + >>> sdist_add_defaults._cs_path_exists(__file__.upper()) + False + """ + if not os.path.exists(fspath): + return False + # make absolute so we always have a directory + abspath = os.path.abspath(fspath) + directory, filename = os.path.split(abspath) + return filename in os.listdir(directory) + + def _add_defaults_standards(self): + standards = [self.READMES, self.distribution.script_name] + for fn in standards: + if isinstance(fn, tuple): + alts = fn + got_it = False + for fn in alts: + if self._cs_path_exists(fn): + got_it = True + self.filelist.append(fn) + break + + if not got_it: + self.warn("standard file not found: should have one of " + + ', '.join(alts)) + else: + if self._cs_path_exists(fn): + self.filelist.append(fn) + else: + self.warn("standard file '%s' not found" % fn) + + def _add_defaults_optional(self): + optional = ['test/test*.py', 'setup.cfg'] + for pattern in optional: + files = filter(os.path.isfile, glob(pattern)) + self.filelist.extend(files) + + def _add_defaults_python(self): + # build_py is used to get: + # - python modules + # - files defined in package_data + build_py = self.get_finalized_command('build_py') + + # getting python files + if self.distribution.has_pure_modules(): + self.filelist.extend(build_py.get_source_files()) + + # getting package_data files + # (computed in build_py.data_files by build_py.finalize_options) + for pkg, src_dir, build_dir, filenames in build_py.data_files: + for filename in filenames: + self.filelist.append(os.path.join(src_dir, filename)) + + def _add_defaults_data_files(self): + # getting distribution.data_files + if self.distribution.has_data_files(): + for item in self.distribution.data_files: + if isinstance(item, str): + # plain file + item = convert_path(item) + if os.path.isfile(item): + self.filelist.append(item) + else: + # a (dirname, filenames) tuple + dirname, filenames = item + for f in filenames: + f = convert_path(f) + if os.path.isfile(f): + self.filelist.append(f) + + def _add_defaults_ext(self): + if self.distribution.has_ext_modules(): + build_ext = self.get_finalized_command('build_ext') + self.filelist.extend(build_ext.get_source_files()) + + def _add_defaults_c_libs(self): + if self.distribution.has_c_libraries(): + build_clib = self.get_finalized_command('build_clib') + self.filelist.extend(build_clib.get_source_files()) + + def _add_defaults_scripts(self): + if self.distribution.has_scripts(): + build_scripts = self.get_finalized_command('build_scripts') + self.filelist.extend(build_scripts.get_source_files()) + + +if hasattr(sdist.sdist, '_add_defaults_standards'): + # disable the functionality already available upstream + class sdist_add_defaults: + pass diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/register.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/register.py new file mode 100644 index 0000000000000000000000000000000000000000..98bc01566f42b289e08cc180fb6e00cc5f4824a3 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/register.py @@ -0,0 +1,18 @@ +from distutils import log +import distutils.command.register as orig + + +class register(orig.register): + __doc__ = orig.register.__doc__ + + def run(self): + try: + # Make sure that we are using valid current name/version info + self.run_command('egg_info') + orig.register.run(self) + finally: + self.announce( + "WARNING: Registering is deprecated, use twine to " + "upload instead (https://pypi.org/p/twine/)", + log.WARN + ) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/rotate.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/rotate.py new file mode 100644 index 0000000000000000000000000000000000000000..b89353f529b3d08e768dea69a9dc8b5e7403003d --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/rotate.py @@ -0,0 +1,66 @@ +from distutils.util import convert_path +from distutils import log +from distutils.errors import DistutilsOptionError +import os +import shutil + +from setuptools.extern import six + +from setuptools import Command + + +class rotate(Command): + """Delete older distributions""" + + description = "delete older distributions, keeping N newest files" + user_options = [ + ('match=', 'm', "patterns to match (required)"), + ('dist-dir=', 'd', "directory where the distributions are"), + ('keep=', 'k', "number of matching distributions to keep"), + ] + + boolean_options = [] + + def initialize_options(self): + self.match = None + self.dist_dir = None + self.keep = None + + def finalize_options(self): + if self.match is None: + raise DistutilsOptionError( + "Must specify one or more (comma-separated) match patterns " + "(e.g. '.zip' or '.egg')" + ) + if self.keep is None: + raise DistutilsOptionError("Must specify number of files to keep") + try: + self.keep = int(self.keep) + except ValueError: + raise DistutilsOptionError("--keep must be an integer") + if isinstance(self.match, six.string_types): + self.match = [ + convert_path(p.strip()) for p in self.match.split(',') + ] + self.set_undefined_options('bdist', ('dist_dir', 'dist_dir')) + + def run(self): + self.run_command("egg_info") + from glob import glob + + for pattern in self.match: + pattern = self.distribution.get_name() + '*' + pattern + files = glob(os.path.join(self.dist_dir, pattern)) + files = [(os.path.getmtime(f), f) for f in files] + files.sort() + files.reverse() + + log.info("%d file(s) matching %s", len(files), pattern) + files = files[self.keep:] + for (t, f) in files: + log.info("Deleting %s", f) + if not self.dry_run: + if os.path.isdir(f): + shutil.rmtree(f) + else: + os.unlink(f) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/saveopts.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/saveopts.py new file mode 100644 index 0000000000000000000000000000000000000000..611cec552867a6d50b7edd700c86c7396d906ea2 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/saveopts.py @@ -0,0 +1,22 @@ +from setuptools.command.setopt import edit_config, option_base + + +class saveopts(option_base): + """Save command-line options to a file""" + + description = "save supplied options to setup.cfg or other config file" + + def run(self): + dist = self.distribution + settings = {} + + for cmd in dist.command_options: + + if cmd == 'saveopts': + continue # don't save our own options! + + for opt, (src, val) in dist.get_option_dict(cmd).items(): + if src == "command line": + settings.setdefault(cmd, {})[opt] = val + + edit_config(self.filename, settings, self.dry_run) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/sdist.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/sdist.py new file mode 100644 index 0000000000000000000000000000000000000000..dc25398147cfedcbc01be33ee25b693361a685cf --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/sdist.py @@ -0,0 +1,221 @@ +from distutils import log +import distutils.command.sdist as orig +import os +import sys +import io +import contextlib + +from setuptools.extern import six + +from .py36compat import sdist_add_defaults + +import pkg_resources + +_default_revctrl = list + + +def walk_revctrl(dirname=''): + """Find all files under revision control""" + for ep in pkg_resources.iter_entry_points('setuptools.file_finders'): + for item in ep.load()(dirname): + yield item + + +class sdist(sdist_add_defaults, orig.sdist): + """Smart sdist that finds anything supported by revision control""" + + user_options = [ + ('formats=', None, + "formats for source distribution (comma-separated list)"), + ('keep-temp', 'k', + "keep the distribution tree around after creating " + + "archive file(s)"), + ('dist-dir=', 'd', + "directory to put the source distribution archive(s) in " + "[default: dist]"), + ] + + negative_opt = {} + + README_EXTENSIONS = ['', '.rst', '.txt', '.md'] + READMES = tuple('README{0}'.format(ext) for ext in README_EXTENSIONS) + + def run(self): + self.run_command('egg_info') + ei_cmd = self.get_finalized_command('egg_info') + self.filelist = ei_cmd.filelist + self.filelist.append(os.path.join(ei_cmd.egg_info, 'SOURCES.txt')) + self.check_readme() + + # Run sub commands + for cmd_name in self.get_sub_commands(): + self.run_command(cmd_name) + + self.make_distribution() + + dist_files = getattr(self.distribution, 'dist_files', []) + for file in self.archive_files: + data = ('sdist', '', file) + if data not in dist_files: + dist_files.append(data) + + def initialize_options(self): + orig.sdist.initialize_options(self) + + self._default_to_gztar() + + def _default_to_gztar(self): + # only needed on Python prior to 3.6. + if sys.version_info >= (3, 6, 0, 'beta', 1): + return + self.formats = ['gztar'] + + def make_distribution(self): + """ + Workaround for #516 + """ + with self._remove_os_link(): + orig.sdist.make_distribution(self) + + @staticmethod + @contextlib.contextmanager + def _remove_os_link(): + """ + In a context, remove and restore os.link if it exists + """ + + class NoValue: + pass + + orig_val = getattr(os, 'link', NoValue) + try: + del os.link + except Exception: + pass + try: + yield + finally: + if orig_val is not NoValue: + setattr(os, 'link', orig_val) + + def __read_template_hack(self): + # This grody hack closes the template file (MANIFEST.in) if an + # exception occurs during read_template. + # Doing so prevents an error when easy_install attempts to delete the + # file. + try: + orig.sdist.read_template(self) + except Exception: + _, _, tb = sys.exc_info() + tb.tb_next.tb_frame.f_locals['template'].close() + raise + + # Beginning with Python 2.7.2, 3.1.4, and 3.2.1, this leaky file handle + # has been fixed, so only override the method if we're using an earlier + # Python. + has_leaky_handle = ( + sys.version_info < (2, 7, 2) + or (3, 0) <= sys.version_info < (3, 1, 4) + or (3, 2) <= sys.version_info < (3, 2, 1) + ) + if has_leaky_handle: + read_template = __read_template_hack + + def _add_defaults_python(self): + """getting python files""" + if self.distribution.has_pure_modules(): + build_py = self.get_finalized_command('build_py') + self.filelist.extend(build_py.get_source_files()) + # This functionality is incompatible with include_package_data, and + # will in fact create an infinite recursion if include_package_data + # is True. Use of include_package_data will imply that + # distutils-style automatic handling of package_data is disabled + if not self.distribution.include_package_data: + for _, src_dir, _, filenames in build_py.data_files: + self.filelist.extend([os.path.join(src_dir, filename) + for filename in filenames]) + + def _add_defaults_data_files(self): + try: + if six.PY2: + sdist_add_defaults._add_defaults_data_files(self) + else: + super()._add_defaults_data_files() + except TypeError: + log.warn("data_files contains unexpected objects") + + def check_readme(self): + for f in self.READMES: + if os.path.exists(f): + return + else: + self.warn( + "standard file not found: should have one of " + + ', '.join(self.READMES) + ) + + def make_release_tree(self, base_dir, files): + orig.sdist.make_release_tree(self, base_dir, files) + + # Save any egg_info command line options used to create this sdist + dest = os.path.join(base_dir, 'setup.cfg') + if hasattr(os, 'link') and os.path.exists(dest): + # unlink and re-copy, since it might be hard-linked, and + # we don't want to change the source version + os.unlink(dest) + self.copy_file('setup.cfg', dest) + + self.get_finalized_command('egg_info').save_version_info(dest) + + def _manifest_is_not_generated(self): + # check for special comment used in 2.7.1 and higher + if not os.path.isfile(self.manifest): + return False + + with io.open(self.manifest, 'rb') as fp: + first_line = fp.readline() + return (first_line != + '# file GENERATED by distutils, do NOT edit\n'.encode()) + + def read_manifest(self): + """Read the manifest file (named by 'self.manifest') and use it to + fill in 'self.filelist', the list of files to include in the source + distribution. + """ + log.info("reading manifest file '%s'", self.manifest) + manifest = open(self.manifest, 'rb') + for line in manifest: + # The manifest must contain UTF-8. See #303. + if six.PY3: + try: + line = line.decode('UTF-8') + except UnicodeDecodeError: + log.warn("%r not UTF-8 decodable -- skipping" % line) + continue + # ignore comments and blank lines + line = line.strip() + if line.startswith('#') or not line: + continue + self.filelist.append(line) + manifest.close() + + def check_license(self): + """Checks if license_file' is configured and adds it to + 'self.filelist' if the value contains a valid path. + """ + + opts = self.distribution.get_option_dict('metadata') + + # ignore the source of the value + _, license_file = opts.get('license_file', (None, None)) + + if license_file is None: + log.debug("'license_file' option was not specified") + return + + if not os.path.exists(license_file): + log.warn("warning: Failed to find the configured license file '%s'", + license_file) + return + + self.filelist.append(license_file) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/setopt.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/setopt.py new file mode 100644 index 0000000000000000000000000000000000000000..7e57cc02627fc3c3bb49613731a51c72452f96ba --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/setopt.py @@ -0,0 +1,149 @@ +from distutils.util import convert_path +from distutils import log +from distutils.errors import DistutilsOptionError +import distutils +import os + +from setuptools.extern.six.moves import configparser + +from setuptools import Command + +__all__ = ['config_file', 'edit_config', 'option_base', 'setopt'] + + +def config_file(kind="local"): + """Get the filename of the distutils, local, global, or per-user config + + `kind` must be one of "local", "global", or "user" + """ + if kind == 'local': + return 'setup.cfg' + if kind == 'global': + return os.path.join( + os.path.dirname(distutils.__file__), 'distutils.cfg' + ) + if kind == 'user': + dot = os.name == 'posix' and '.' or '' + return os.path.expanduser(convert_path("~/%spydistutils.cfg" % dot)) + raise ValueError( + "config_file() type must be 'local', 'global', or 'user'", kind + ) + + +def edit_config(filename, settings, dry_run=False): + """Edit a configuration file to include `settings` + + `settings` is a dictionary of dictionaries or ``None`` values, keyed by + command/section name. A ``None`` value means to delete the entire section, + while a dictionary lists settings to be changed or deleted in that section. + A setting of ``None`` means to delete that setting. + """ + log.debug("Reading configuration from %s", filename) + opts = configparser.RawConfigParser() + opts.read([filename]) + for section, options in settings.items(): + if options is None: + log.info("Deleting section [%s] from %s", section, filename) + opts.remove_section(section) + else: + if not opts.has_section(section): + log.debug("Adding new section [%s] to %s", section, filename) + opts.add_section(section) + for option, value in options.items(): + if value is None: + log.debug( + "Deleting %s.%s from %s", + section, option, filename + ) + opts.remove_option(section, option) + if not opts.options(section): + log.info("Deleting empty [%s] section from %s", + section, filename) + opts.remove_section(section) + else: + log.debug( + "Setting %s.%s to %r in %s", + section, option, value, filename + ) + opts.set(section, option, value) + + log.info("Writing %s", filename) + if not dry_run: + with open(filename, 'w') as f: + opts.write(f) + + +class option_base(Command): + """Abstract base class for commands that mess with config files""" + + user_options = [ + ('global-config', 'g', + "save options to the site-wide distutils.cfg file"), + ('user-config', 'u', + "save options to the current user's pydistutils.cfg file"), + ('filename=', 'f', + "configuration file to use (default=setup.cfg)"), + ] + + boolean_options = [ + 'global-config', 'user-config', + ] + + def initialize_options(self): + self.global_config = None + self.user_config = None + self.filename = None + + def finalize_options(self): + filenames = [] + if self.global_config: + filenames.append(config_file('global')) + if self.user_config: + filenames.append(config_file('user')) + if self.filename is not None: + filenames.append(self.filename) + if not filenames: + filenames.append(config_file('local')) + if len(filenames) > 1: + raise DistutilsOptionError( + "Must specify only one configuration file option", + filenames + ) + self.filename, = filenames + + +class setopt(option_base): + """Save command-line options to a file""" + + description = "set an option in setup.cfg or another config file" + + user_options = [ + ('command=', 'c', 'command to set an option for'), + ('option=', 'o', 'option to set'), + ('set-value=', 's', 'value of the option'), + ('remove', 'r', 'remove (unset) the value'), + ] + option_base.user_options + + boolean_options = option_base.boolean_options + ['remove'] + + def initialize_options(self): + option_base.initialize_options(self) + self.command = None + self.option = None + self.set_value = None + self.remove = None + + def finalize_options(self): + option_base.finalize_options(self) + if self.command is None or self.option is None: + raise DistutilsOptionError("Must specify --command *and* --option") + if self.set_value is None and not self.remove: + raise DistutilsOptionError("Must specify --set-value or --remove") + + def run(self): + edit_config( + self.filename, { + self.command: {self.option.replace('-', '_'): self.set_value} + }, + self.dry_run + ) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/test.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/test.py new file mode 100644 index 0000000000000000000000000000000000000000..973e4eb214b1305aadf771617b2b4ec162feea1f --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/test.py @@ -0,0 +1,271 @@ +import os +import operator +import sys +import contextlib +import itertools +import unittest +from distutils.errors import DistutilsError, DistutilsOptionError +from distutils import log +from unittest import TestLoader + +from setuptools.extern import six +from setuptools.extern.six.moves import map, filter + +from pkg_resources import (resource_listdir, resource_exists, normalize_path, + working_set, _namespace_packages, evaluate_marker, + add_activation_listener, require, EntryPoint) +from setuptools import Command +from .build_py import _unique_everseen + +__metaclass__ = type + + +class ScanningLoader(TestLoader): + + def __init__(self): + TestLoader.__init__(self) + self._visited = set() + + def loadTestsFromModule(self, module, pattern=None): + """Return a suite of all tests cases contained in the given module + + If the module is a package, load tests from all the modules in it. + If the module has an ``additional_tests`` function, call it and add + the return value to the tests. + """ + if module in self._visited: + return None + self._visited.add(module) + + tests = [] + tests.append(TestLoader.loadTestsFromModule(self, module)) + + if hasattr(module, "additional_tests"): + tests.append(module.additional_tests()) + + if hasattr(module, '__path__'): + for file in resource_listdir(module.__name__, ''): + if file.endswith('.py') and file != '__init__.py': + submodule = module.__name__ + '.' + file[:-3] + else: + if resource_exists(module.__name__, file + '/__init__.py'): + submodule = module.__name__ + '.' + file + else: + continue + tests.append(self.loadTestsFromName(submodule)) + + if len(tests) != 1: + return self.suiteClass(tests) + else: + return tests[0] # don't create a nested suite for only one return + + +# adapted from jaraco.classes.properties:NonDataProperty +class NonDataProperty: + def __init__(self, fget): + self.fget = fget + + def __get__(self, obj, objtype=None): + if obj is None: + return self + return self.fget(obj) + + +class test(Command): + """Command to run unit tests after in-place build""" + + description = "run unit tests after in-place build" + + user_options = [ + ('test-module=', 'm', "Run 'test_suite' in specified module"), + ('test-suite=', 's', + "Run single test, case or suite (e.g. 'module.test_suite')"), + ('test-runner=', 'r', "Test runner to use"), + ] + + def initialize_options(self): + self.test_suite = None + self.test_module = None + self.test_loader = None + self.test_runner = None + + def finalize_options(self): + + if self.test_suite and self.test_module: + msg = "You may specify a module or a suite, but not both" + raise DistutilsOptionError(msg) + + if self.test_suite is None: + if self.test_module is None: + self.test_suite = self.distribution.test_suite + else: + self.test_suite = self.test_module + ".test_suite" + + if self.test_loader is None: + self.test_loader = getattr(self.distribution, 'test_loader', None) + if self.test_loader is None: + self.test_loader = "setuptools.command.test:ScanningLoader" + if self.test_runner is None: + self.test_runner = getattr(self.distribution, 'test_runner', None) + + @NonDataProperty + def test_args(self): + return list(self._test_args()) + + def _test_args(self): + if not self.test_suite and sys.version_info >= (2, 7): + yield 'discover' + if self.verbose: + yield '--verbose' + if self.test_suite: + yield self.test_suite + + def with_project_on_sys_path(self, func): + """ + Backward compatibility for project_on_sys_path context. + """ + with self.project_on_sys_path(): + func() + + @contextlib.contextmanager + def project_on_sys_path(self, include_dists=[]): + with_2to3 = six.PY3 and getattr(self.distribution, 'use_2to3', False) + + if with_2to3: + # If we run 2to3 we can not do this inplace: + + # Ensure metadata is up-to-date + self.reinitialize_command('build_py', inplace=0) + self.run_command('build_py') + bpy_cmd = self.get_finalized_command("build_py") + build_path = normalize_path(bpy_cmd.build_lib) + + # Build extensions + self.reinitialize_command('egg_info', egg_base=build_path) + self.run_command('egg_info') + + self.reinitialize_command('build_ext', inplace=0) + self.run_command('build_ext') + else: + # Without 2to3 inplace works fine: + self.run_command('egg_info') + + # Build extensions in-place + self.reinitialize_command('build_ext', inplace=1) + self.run_command('build_ext') + + ei_cmd = self.get_finalized_command("egg_info") + + old_path = sys.path[:] + old_modules = sys.modules.copy() + + try: + project_path = normalize_path(ei_cmd.egg_base) + sys.path.insert(0, project_path) + working_set.__init__() + add_activation_listener(lambda dist: dist.activate()) + require('%s==%s' % (ei_cmd.egg_name, ei_cmd.egg_version)) + with self.paths_on_pythonpath([project_path]): + yield + finally: + sys.path[:] = old_path + sys.modules.clear() + sys.modules.update(old_modules) + working_set.__init__() + + @staticmethod + @contextlib.contextmanager + def paths_on_pythonpath(paths): + """ + Add the indicated paths to the head of the PYTHONPATH environment + variable so that subprocesses will also see the packages at + these paths. + + Do this in a context that restores the value on exit. + """ + nothing = object() + orig_pythonpath = os.environ.get('PYTHONPATH', nothing) + current_pythonpath = os.environ.get('PYTHONPATH', '') + try: + prefix = os.pathsep.join(_unique_everseen(paths)) + to_join = filter(None, [prefix, current_pythonpath]) + new_path = os.pathsep.join(to_join) + if new_path: + os.environ['PYTHONPATH'] = new_path + yield + finally: + if orig_pythonpath is nothing: + os.environ.pop('PYTHONPATH', None) + else: + os.environ['PYTHONPATH'] = orig_pythonpath + + @staticmethod + def install_dists(dist): + """ + Install the requirements indicated by self.distribution and + return an iterable of the dists that were built. + """ + ir_d = dist.fetch_build_eggs(dist.install_requires) + tr_d = dist.fetch_build_eggs(dist.tests_require or []) + er_d = dist.fetch_build_eggs( + v for k, v in dist.extras_require.items() + if k.startswith(':') and evaluate_marker(k[1:]) + ) + return itertools.chain(ir_d, tr_d, er_d) + + def run(self): + installed_dists = self.install_dists(self.distribution) + + cmd = ' '.join(self._argv) + if self.dry_run: + self.announce('skipping "%s" (dry run)' % cmd) + return + + self.announce('running "%s"' % cmd) + + paths = map(operator.attrgetter('location'), installed_dists) + with self.paths_on_pythonpath(paths): + with self.project_on_sys_path(): + self.run_tests() + + def run_tests(self): + # Purge modules under test from sys.modules. The test loader will + # re-import them from the build location. Required when 2to3 is used + # with namespace packages. + if six.PY3 and getattr(self.distribution, 'use_2to3', False): + module = self.test_suite.split('.')[0] + if module in _namespace_packages: + del_modules = [] + if module in sys.modules: + del_modules.append(module) + module += '.' + for name in sys.modules: + if name.startswith(module): + del_modules.append(name) + list(map(sys.modules.__delitem__, del_modules)) + + test = unittest.main( + None, None, self._argv, + testLoader=self._resolve_as_ep(self.test_loader), + testRunner=self._resolve_as_ep(self.test_runner), + exit=False, + ) + if not test.result.wasSuccessful(): + msg = 'Test failed: %s' % test.result + self.announce(msg, log.ERROR) + raise DistutilsError(msg) + + @property + def _argv(self): + return ['unittest'] + self.test_args + + @staticmethod + def _resolve_as_ep(val): + """ + Load the indicated attribute value, called, as a as if it were + specified as an entry point. + """ + if val is None: + return + parsed = EntryPoint.parse("x=" + val) + return parsed.resolve()() diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/upload.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/upload.py new file mode 100644 index 0000000000000000000000000000000000000000..6db8888bb29cc59ef23e42a4b3335c311a6ef0ad --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/upload.py @@ -0,0 +1,196 @@ +import io +import os +import hashlib +import getpass + +from base64 import standard_b64encode + +from distutils import log +from distutils.command import upload as orig +from distutils.spawn import spawn + +from distutils.errors import DistutilsError + +from setuptools.extern.six.moves.urllib.request import urlopen, Request +from setuptools.extern.six.moves.urllib.error import HTTPError +from setuptools.extern.six.moves.urllib.parse import urlparse + + +class upload(orig.upload): + """ + Override default upload behavior to obtain password + in a variety of different ways. + """ + def run(self): + try: + orig.upload.run(self) + finally: + self.announce( + "WARNING: Uploading via this command is deprecated, use twine " + "to upload instead (https://pypi.org/p/twine/)", + log.WARN + ) + + def finalize_options(self): + orig.upload.finalize_options(self) + self.username = ( + self.username or + getpass.getuser() + ) + # Attempt to obtain password. Short circuit evaluation at the first + # sign of success. + self.password = ( + self.password or + self._load_password_from_keyring() or + self._prompt_for_password() + ) + + def upload_file(self, command, pyversion, filename): + # Makes sure the repository URL is compliant + schema, netloc, url, params, query, fragments = \ + urlparse(self.repository) + if params or query or fragments: + raise AssertionError("Incompatible url %s" % self.repository) + + if schema not in ('http', 'https'): + raise AssertionError("unsupported schema " + schema) + + # Sign if requested + if self.sign: + gpg_args = ["gpg", "--detach-sign", "-a", filename] + if self.identity: + gpg_args[2:2] = ["--local-user", self.identity] + spawn(gpg_args, + dry_run=self.dry_run) + + # Fill in the data - send all the meta-data in case we need to + # register a new release + with open(filename, 'rb') as f: + content = f.read() + + meta = self.distribution.metadata + + data = { + # action + ':action': 'file_upload', + 'protocol_version': '1', + + # identify release + 'name': meta.get_name(), + 'version': meta.get_version(), + + # file content + 'content': (os.path.basename(filename), content), + 'filetype': command, + 'pyversion': pyversion, + 'md5_digest': hashlib.md5(content).hexdigest(), + + # additional meta-data + 'metadata_version': str(meta.get_metadata_version()), + 'summary': meta.get_description(), + 'home_page': meta.get_url(), + 'author': meta.get_contact(), + 'author_email': meta.get_contact_email(), + 'license': meta.get_licence(), + 'description': meta.get_long_description(), + 'keywords': meta.get_keywords(), + 'platform': meta.get_platforms(), + 'classifiers': meta.get_classifiers(), + 'download_url': meta.get_download_url(), + # PEP 314 + 'provides': meta.get_provides(), + 'requires': meta.get_requires(), + 'obsoletes': meta.get_obsoletes(), + } + + data['comment'] = '' + + if self.sign: + data['gpg_signature'] = (os.path.basename(filename) + ".asc", + open(filename+".asc", "rb").read()) + + # set up the authentication + user_pass = (self.username + ":" + self.password).encode('ascii') + # The exact encoding of the authentication string is debated. + # Anyway PyPI only accepts ascii for both username or password. + auth = "Basic " + standard_b64encode(user_pass).decode('ascii') + + # Build up the MIME payload for the POST data + boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254' + sep_boundary = b'\r\n--' + boundary.encode('ascii') + end_boundary = sep_boundary + b'--\r\n' + body = io.BytesIO() + for key, value in data.items(): + title = '\r\nContent-Disposition: form-data; name="%s"' % key + # handle multiple entries for the same name + if not isinstance(value, list): + value = [value] + for value in value: + if type(value) is tuple: + title += '; filename="%s"' % value[0] + value = value[1] + else: + value = str(value).encode('utf-8') + body.write(sep_boundary) + body.write(title.encode('utf-8')) + body.write(b"\r\n\r\n") + body.write(value) + body.write(end_boundary) + body = body.getvalue() + + msg = "Submitting %s to %s" % (filename, self.repository) + self.announce(msg, log.INFO) + + # build the Request + headers = { + 'Content-type': 'multipart/form-data; boundary=%s' % boundary, + 'Content-length': str(len(body)), + 'Authorization': auth, + } + + request = Request(self.repository, data=body, + headers=headers) + # send the data + try: + result = urlopen(request) + status = result.getcode() + reason = result.msg + except HTTPError as e: + status = e.code + reason = e.msg + except OSError as e: + self.announce(str(e), log.ERROR) + raise + + if status == 200: + self.announce('Server response (%s): %s' % (status, reason), + log.INFO) + if self.show_response: + text = getattr(self, '_read_pypi_response', + lambda x: None)(result) + if text is not None: + msg = '\n'.join(('-' * 75, text, '-' * 75)) + self.announce(msg, log.INFO) + else: + msg = 'Upload failed (%s): %s' % (status, reason) + self.announce(msg, log.ERROR) + raise DistutilsError(msg) + + def _load_password_from_keyring(self): + """ + Attempt to load password from keyring. Suppress Exceptions. + """ + try: + keyring = __import__('keyring') + return keyring.get_password(self.repository, self.username) + except Exception: + pass + + def _prompt_for_password(self): + """ + Prompt for a password on the tty. Suppress Exceptions. + """ + try: + return getpass.getpass() + except (Exception, KeyboardInterrupt): + pass diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/upload_docs.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/upload_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..07aa564af451ce41d818d72f8ee93cb46887cecf --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/command/upload_docs.py @@ -0,0 +1,206 @@ +# -*- coding: utf-8 -*- +"""upload_docs + +Implements a Distutils 'upload_docs' subcommand (upload documentation to +PyPI's pythonhosted.org). +""" + +from base64 import standard_b64encode +from distutils import log +from distutils.errors import DistutilsOptionError +import os +import socket +import zipfile +import tempfile +import shutil +import itertools +import functools + +from setuptools.extern import six +from setuptools.extern.six.moves import http_client, urllib + +from pkg_resources import iter_entry_points +from .upload import upload + + +def _encode(s): + errors = 'surrogateescape' if six.PY3 else 'strict' + return s.encode('utf-8', errors) + + +class upload_docs(upload): + # override the default repository as upload_docs isn't + # supported by Warehouse (and won't be). + DEFAULT_REPOSITORY = 'https://pypi.python.org/pypi/' + + description = 'Upload documentation to PyPI' + + user_options = [ + ('repository=', 'r', + "url of repository [default: %s]" % upload.DEFAULT_REPOSITORY), + ('show-response', None, + 'display full response text from server'), + ('upload-dir=', None, 'directory to upload'), + ] + boolean_options = upload.boolean_options + + def has_sphinx(self): + if self.upload_dir is None: + for ep in iter_entry_points('distutils.commands', 'build_sphinx'): + return True + + sub_commands = [('build_sphinx', has_sphinx)] + + def initialize_options(self): + upload.initialize_options(self) + self.upload_dir = None + self.target_dir = None + + def finalize_options(self): + upload.finalize_options(self) + if self.upload_dir is None: + if self.has_sphinx(): + build_sphinx = self.get_finalized_command('build_sphinx') + self.target_dir = build_sphinx.builder_target_dir + else: + build = self.get_finalized_command('build') + self.target_dir = os.path.join(build.build_base, 'docs') + else: + self.ensure_dirname('upload_dir') + self.target_dir = self.upload_dir + if 'pypi.python.org' in self.repository: + log.warn("Upload_docs command is deprecated. Use RTD instead.") + self.announce('Using upload directory %s' % self.target_dir) + + def create_zipfile(self, filename): + zip_file = zipfile.ZipFile(filename, "w") + try: + self.mkpath(self.target_dir) # just in case + for root, dirs, files in os.walk(self.target_dir): + if root == self.target_dir and not files: + tmpl = "no files found in upload directory '%s'" + raise DistutilsOptionError(tmpl % self.target_dir) + for name in files: + full = os.path.join(root, name) + relative = root[len(self.target_dir):].lstrip(os.path.sep) + dest = os.path.join(relative, name) + zip_file.write(full, dest) + finally: + zip_file.close() + + def run(self): + # Run sub commands + for cmd_name in self.get_sub_commands(): + self.run_command(cmd_name) + + tmp_dir = tempfile.mkdtemp() + name = self.distribution.metadata.get_name() + zip_file = os.path.join(tmp_dir, "%s.zip" % name) + try: + self.create_zipfile(zip_file) + self.upload_file(zip_file) + finally: + shutil.rmtree(tmp_dir) + + @staticmethod + def _build_part(item, sep_boundary): + key, values = item + title = '\nContent-Disposition: form-data; name="%s"' % key + # handle multiple entries for the same name + if not isinstance(values, list): + values = [values] + for value in values: + if isinstance(value, tuple): + title += '; filename="%s"' % value[0] + value = value[1] + else: + value = _encode(value) + yield sep_boundary + yield _encode(title) + yield b"\n\n" + yield value + if value and value[-1:] == b'\r': + yield b'\n' # write an extra newline (lurve Macs) + + @classmethod + def _build_multipart(cls, data): + """ + Build up the MIME payload for the POST data + """ + boundary = b'--------------GHSKFJDLGDS7543FJKLFHRE75642756743254' + sep_boundary = b'\n--' + boundary + end_boundary = sep_boundary + b'--' + end_items = end_boundary, b"\n", + builder = functools.partial( + cls._build_part, + sep_boundary=sep_boundary, + ) + part_groups = map(builder, data.items()) + parts = itertools.chain.from_iterable(part_groups) + body_items = itertools.chain(parts, end_items) + content_type = 'multipart/form-data; boundary=%s' % boundary.decode('ascii') + return b''.join(body_items), content_type + + def upload_file(self, filename): + with open(filename, 'rb') as f: + content = f.read() + meta = self.distribution.metadata + data = { + ':action': 'doc_upload', + 'name': meta.get_name(), + 'content': (os.path.basename(filename), content), + } + # set up the authentication + credentials = _encode(self.username + ':' + self.password) + credentials = standard_b64encode(credentials) + if six.PY3: + credentials = credentials.decode('ascii') + auth = "Basic " + credentials + + body, ct = self._build_multipart(data) + + msg = "Submitting documentation to %s" % (self.repository) + self.announce(msg, log.INFO) + + # build the Request + # We can't use urllib2 since we need to send the Basic + # auth right with the first request + schema, netloc, url, params, query, fragments = \ + urllib.parse.urlparse(self.repository) + assert not params and not query and not fragments + if schema == 'http': + conn = http_client.HTTPConnection(netloc) + elif schema == 'https': + conn = http_client.HTTPSConnection(netloc) + else: + raise AssertionError("unsupported schema " + schema) + + data = '' + try: + conn.connect() + conn.putrequest("POST", url) + content_type = ct + conn.putheader('Content-type', content_type) + conn.putheader('Content-length', str(len(body))) + conn.putheader('Authorization', auth) + conn.endheaders() + conn.send(body) + except socket.error as e: + self.announce(str(e), log.ERROR) + return + + r = conn.getresponse() + if r.status == 200: + msg = 'Server response (%s): %s' % (r.status, r.reason) + self.announce(msg, log.INFO) + elif r.status == 301: + location = r.getheader('Location') + if location is None: + location = 'https://pythonhosted.org/%s/' % meta.get_name() + msg = 'Upload successful. Visit %s' % location + self.announce(msg, log.INFO) + else: + msg = 'Upload failed (%s): %s' % (r.status, r.reason) + self.announce(msg, log.ERROR) + if self.show_response: + print('-' * 75, r.read(), '-' * 75) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/extern/__init__.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/extern/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cb2fa329272be7eb62a4a1eaf01e0e4288a7287c --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/extern/__init__.py @@ -0,0 +1,73 @@ +import sys + + +class VendorImporter: + """ + A PEP 302 meta path importer for finding optionally-vendored + or otherwise naturally-installed packages from root_name. + """ + + def __init__(self, root_name, vendored_names=(), vendor_pkg=None): + self.root_name = root_name + self.vendored_names = set(vendored_names) + self.vendor_pkg = vendor_pkg or root_name.replace('extern', '_vendor') + + @property + def search_path(self): + """ + Search first the vendor package then as a natural package. + """ + yield self.vendor_pkg + '.' + yield '' + + def find_module(self, fullname, path=None): + """ + Return self when fullname starts with root_name and the + target module is one vendored through this importer. + """ + root, base, target = fullname.partition(self.root_name + '.') + if root: + return + if not any(map(target.startswith, self.vendored_names)): + return + return self + + def load_module(self, fullname): + """ + Iterate over the search path to locate and load fullname. + """ + root, base, target = fullname.partition(self.root_name + '.') + for prefix in self.search_path: + try: + extant = prefix + target + __import__(extant) + mod = sys.modules[extant] + sys.modules[fullname] = mod + # mysterious hack: + # Remove the reference to the extant package/module + # on later Python versions to cause relative imports + # in the vendor package to resolve the same modules + # as those going through this importer. + if sys.version_info >= (3, ): + del sys.modules[extant] + return mod + except ImportError: + pass + else: + raise ImportError( + "The '{target}' package is required; " + "normally this is bundled with this package so if you get " + "this warning, consult the packager of your " + "distribution.".format(**locals()) + ) + + def install(self): + """ + Install this importer into sys.meta_path if not already present. + """ + if self not in sys.meta_path: + sys.meta_path.append(self) + + +names = 'six', 'packaging', 'pyparsing', +VendorImporter(__name__, names, 'setuptools._vendor').install() diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/package_index.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/package_index.py new file mode 100644 index 0000000000000000000000000000000000000000..6b06f2ca281296c989fa55c6c77c9d8b7356b552 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/package_index.py @@ -0,0 +1,1136 @@ +"""PyPI and direct package downloading""" +import sys +import os +import re +import shutil +import socket +import base64 +import hashlib +import itertools +import warnings +from functools import wraps + +from setuptools.extern import six +from setuptools.extern.six.moves import urllib, http_client, configparser, map + +import setuptools +from pkg_resources import ( + CHECKOUT_DIST, Distribution, BINARY_DIST, normalize_path, SOURCE_DIST, + Environment, find_distributions, safe_name, safe_version, + to_filename, Requirement, DEVELOP_DIST, EGG_DIST, +) +from setuptools import ssl_support +from distutils import log +from distutils.errors import DistutilsError +from fnmatch import translate +from setuptools.py27compat import get_all_headers +from setuptools.py33compat import unescape +from setuptools.wheel import Wheel + +__metaclass__ = type + +EGG_FRAGMENT = re.compile(r'^egg=([-A-Za-z0-9_.+!]+)$') +HREF = re.compile(r"""href\s*=\s*['"]?([^'"> ]+)""", re.I) +PYPI_MD5 = re.compile( + r'([^<]+)\n\s+\(md5\)' +) +URL_SCHEME = re.compile('([-+.a-z0-9]{2,}):', re.I).match +EXTENSIONS = ".tar.gz .tar.bz2 .tar .zip .tgz".split() + +__all__ = [ + 'PackageIndex', 'distros_for_url', 'parse_bdist_wininst', + 'interpret_distro_name', +] + +_SOCKET_TIMEOUT = 15 + +_tmpl = "setuptools/{setuptools.__version__} Python-urllib/{py_major}" +user_agent = _tmpl.format(py_major=sys.version[:3], setuptools=setuptools) + + +def parse_requirement_arg(spec): + try: + return Requirement.parse(spec) + except ValueError: + raise DistutilsError( + "Not a URL, existing file, or requirement spec: %r" % (spec,) + ) + + +def parse_bdist_wininst(name): + """Return (base,pyversion) or (None,None) for possible .exe name""" + + lower = name.lower() + base, py_ver, plat = None, None, None + + if lower.endswith('.exe'): + if lower.endswith('.win32.exe'): + base = name[:-10] + plat = 'win32' + elif lower.startswith('.win32-py', -16): + py_ver = name[-7:-4] + base = name[:-16] + plat = 'win32' + elif lower.endswith('.win-amd64.exe'): + base = name[:-14] + plat = 'win-amd64' + elif lower.startswith('.win-amd64-py', -20): + py_ver = name[-7:-4] + base = name[:-20] + plat = 'win-amd64' + return base, py_ver, plat + + +def egg_info_for_url(url): + parts = urllib.parse.urlparse(url) + scheme, server, path, parameters, query, fragment = parts + base = urllib.parse.unquote(path.split('/')[-1]) + if server == 'sourceforge.net' and base == 'download': # XXX Yuck + base = urllib.parse.unquote(path.split('/')[-2]) + if '#' in base: + base, fragment = base.split('#', 1) + return base, fragment + + +def distros_for_url(url, metadata=None): + """Yield egg or source distribution objects that might be found at a URL""" + base, fragment = egg_info_for_url(url) + for dist in distros_for_location(url, base, metadata): + yield dist + if fragment: + match = EGG_FRAGMENT.match(fragment) + if match: + for dist in interpret_distro_name( + url, match.group(1), metadata, precedence=CHECKOUT_DIST + ): + yield dist + + +def distros_for_location(location, basename, metadata=None): + """Yield egg or source distribution objects based on basename""" + if basename.endswith('.egg.zip'): + basename = basename[:-4] # strip the .zip + if basename.endswith('.egg') and '-' in basename: + # only one, unambiguous interpretation + return [Distribution.from_location(location, basename, metadata)] + if basename.endswith('.whl') and '-' in basename: + wheel = Wheel(basename) + if not wheel.is_compatible(): + return [] + return [Distribution( + location=location, + project_name=wheel.project_name, + version=wheel.version, + # Increase priority over eggs. + precedence=EGG_DIST + 1, + )] + if basename.endswith('.exe'): + win_base, py_ver, platform = parse_bdist_wininst(basename) + if win_base is not None: + return interpret_distro_name( + location, win_base, metadata, py_ver, BINARY_DIST, platform + ) + # Try source distro extensions (.zip, .tgz, etc.) + # + for ext in EXTENSIONS: + if basename.endswith(ext): + basename = basename[:-len(ext)] + return interpret_distro_name(location, basename, metadata) + return [] # no extension matched + + +def distros_for_filename(filename, metadata=None): + """Yield possible egg or source distribution objects based on a filename""" + return distros_for_location( + normalize_path(filename), os.path.basename(filename), metadata + ) + + +def interpret_distro_name( + location, basename, metadata, py_version=None, precedence=SOURCE_DIST, + platform=None +): + """Generate alternative interpretations of a source distro name + + Note: if `location` is a filesystem filename, you should call + ``pkg_resources.normalize_path()`` on it before passing it to this + routine! + """ + # Generate alternative interpretations of a source distro name + # Because some packages are ambiguous as to name/versions split + # e.g. "adns-python-1.1.0", "egenix-mx-commercial", etc. + # So, we generate each possible interepretation (e.g. "adns, python-1.1.0" + # "adns-python, 1.1.0", and "adns-python-1.1.0, no version"). In practice, + # the spurious interpretations should be ignored, because in the event + # there's also an "adns" package, the spurious "python-1.1.0" version will + # compare lower than any numeric version number, and is therefore unlikely + # to match a request for it. It's still a potential problem, though, and + # in the long run PyPI and the distutils should go for "safe" names and + # versions in distribution archive names (sdist and bdist). + + parts = basename.split('-') + if not py_version and any(re.match(r'py\d\.\d$', p) for p in parts[2:]): + # it is a bdist_dumb, not an sdist -- bail out + return + + for p in range(1, len(parts) + 1): + yield Distribution( + location, metadata, '-'.join(parts[:p]), '-'.join(parts[p:]), + py_version=py_version, precedence=precedence, + platform=platform + ) + + +# From Python 2.7 docs +def unique_everseen(iterable, key=None): + "List unique elements, preserving order. Remember all elements ever seen." + # unique_everseen('AAAABBBCCDAABBB') --> A B C D + # unique_everseen('ABBCcAD', str.lower) --> A B C D + seen = set() + seen_add = seen.add + if key is None: + for element in six.moves.filterfalse(seen.__contains__, iterable): + seen_add(element) + yield element + else: + for element in iterable: + k = key(element) + if k not in seen: + seen_add(k) + yield element + + +def unique_values(func): + """ + Wrap a function returning an iterable such that the resulting iterable + only ever yields unique items. + """ + + @wraps(func) + def wrapper(*args, **kwargs): + return unique_everseen(func(*args, **kwargs)) + + return wrapper + + +REL = re.compile(r"""<([^>]*\srel\s*=\s*['"]?([^'">]+)[^>]*)>""", re.I) +# this line is here to fix emacs' cruddy broken syntax highlighting + + +@unique_values +def find_external_links(url, page): + """Find rel="homepage" and rel="download" links in `page`, yielding URLs""" + + for match in REL.finditer(page): + tag, rel = match.groups() + rels = set(map(str.strip, rel.lower().split(','))) + if 'homepage' in rels or 'download' in rels: + for match in HREF.finditer(tag): + yield urllib.parse.urljoin(url, htmldecode(match.group(1))) + + for tag in ("Home Page", "Download URL"): + pos = page.find(tag) + if pos != -1: + match = HREF.search(page, pos) + if match: + yield urllib.parse.urljoin(url, htmldecode(match.group(1))) + + +class ContentChecker: + """ + A null content checker that defines the interface for checking content + """ + + def feed(self, block): + """ + Feed a block of data to the hash. + """ + return + + def is_valid(self): + """ + Check the hash. Return False if validation fails. + """ + return True + + def report(self, reporter, template): + """ + Call reporter with information about the checker (hash name) + substituted into the template. + """ + return + + +class HashChecker(ContentChecker): + pattern = re.compile( + r'(?Psha1|sha224|sha384|sha256|sha512|md5)=' + r'(?P[a-f0-9]+)' + ) + + def __init__(self, hash_name, expected): + self.hash_name = hash_name + self.hash = hashlib.new(hash_name) + self.expected = expected + + @classmethod + def from_url(cls, url): + "Construct a (possibly null) ContentChecker from a URL" + fragment = urllib.parse.urlparse(url)[-1] + if not fragment: + return ContentChecker() + match = cls.pattern.search(fragment) + if not match: + return ContentChecker() + return cls(**match.groupdict()) + + def feed(self, block): + self.hash.update(block) + + def is_valid(self): + return self.hash.hexdigest() == self.expected + + def report(self, reporter, template): + msg = template % self.hash_name + return reporter(msg) + + +class PackageIndex(Environment): + """A distribution index that scans web pages for download URLs""" + + def __init__( + self, index_url="https://pypi.org/simple/", hosts=('*',), + ca_bundle=None, verify_ssl=True, *args, **kw + ): + Environment.__init__(self, *args, **kw) + self.index_url = index_url + "/" [:not index_url.endswith('/')] + self.scanned_urls = {} + self.fetched_urls = {} + self.package_pages = {} + self.allows = re.compile('|'.join(map(translate, hosts))).match + self.to_scan = [] + use_ssl = ( + verify_ssl + and ssl_support.is_available + and (ca_bundle or ssl_support.find_ca_bundle()) + ) + if use_ssl: + self.opener = ssl_support.opener_for(ca_bundle) + else: + self.opener = urllib.request.urlopen + + def process_url(self, url, retrieve=False): + """Evaluate a URL as a possible download, and maybe retrieve it""" + if url in self.scanned_urls and not retrieve: + return + self.scanned_urls[url] = True + if not URL_SCHEME(url): + self.process_filename(url) + return + else: + dists = list(distros_for_url(url)) + if dists: + if not self.url_ok(url): + return + self.debug("Found link: %s", url) + + if dists or not retrieve or url in self.fetched_urls: + list(map(self.add, dists)) + return # don't need the actual page + + if not self.url_ok(url): + self.fetched_urls[url] = True + return + + self.info("Reading %s", url) + self.fetched_urls[url] = True # prevent multiple fetch attempts + tmpl = "Download error on %s: %%s -- Some packages may not be found!" + f = self.open_url(url, tmpl % url) + if f is None: + return + self.fetched_urls[f.url] = True + if 'html' not in f.headers.get('content-type', '').lower(): + f.close() # not html, we can't process it + return + + base = f.url # handle redirects + page = f.read() + if not isinstance(page, str): + # In Python 3 and got bytes but want str. + if isinstance(f, urllib.error.HTTPError): + # Errors have no charset, assume latin1: + charset = 'latin-1' + else: + charset = f.headers.get_param('charset') or 'latin-1' + page = page.decode(charset, "ignore") + f.close() + for match in HREF.finditer(page): + link = urllib.parse.urljoin(base, htmldecode(match.group(1))) + self.process_url(link) + if url.startswith(self.index_url) and getattr(f, 'code', None) != 404: + page = self.process_index(url, page) + + def process_filename(self, fn, nested=False): + # process filenames or directories + if not os.path.exists(fn): + self.warn("Not found: %s", fn) + return + + if os.path.isdir(fn) and not nested: + path = os.path.realpath(fn) + for item in os.listdir(path): + self.process_filename(os.path.join(path, item), True) + + dists = distros_for_filename(fn) + if dists: + self.debug("Found: %s", fn) + list(map(self.add, dists)) + + def url_ok(self, url, fatal=False): + s = URL_SCHEME(url) + is_file = s and s.group(1).lower() == 'file' + if is_file or self.allows(urllib.parse.urlparse(url)[1]): + return True + msg = ( + "\nNote: Bypassing %s (disallowed host; see " + "http://bit.ly/2hrImnY for details).\n") + if fatal: + raise DistutilsError(msg % url) + else: + self.warn(msg, url) + + def scan_egg_links(self, search_path): + dirs = filter(os.path.isdir, search_path) + egg_links = ( + (path, entry) + for path in dirs + for entry in os.listdir(path) + if entry.endswith('.egg-link') + ) + list(itertools.starmap(self.scan_egg_link, egg_links)) + + def scan_egg_link(self, path, entry): + with open(os.path.join(path, entry)) as raw_lines: + # filter non-empty lines + lines = list(filter(None, map(str.strip, raw_lines))) + + if len(lines) != 2: + # format is not recognized; punt + return + + egg_path, setup_path = lines + + for dist in find_distributions(os.path.join(path, egg_path)): + dist.location = os.path.join(path, *lines) + dist.precedence = SOURCE_DIST + self.add(dist) + + def process_index(self, url, page): + """Process the contents of a PyPI page""" + + def scan(link): + # Process a URL to see if it's for a package page + if link.startswith(self.index_url): + parts = list(map( + urllib.parse.unquote, link[len(self.index_url):].split('/') + )) + if len(parts) == 2 and '#' not in parts[1]: + # it's a package page, sanitize and index it + pkg = safe_name(parts[0]) + ver = safe_version(parts[1]) + self.package_pages.setdefault(pkg.lower(), {})[link] = True + return to_filename(pkg), to_filename(ver) + return None, None + + # process an index page into the package-page index + for match in HREF.finditer(page): + try: + scan(urllib.parse.urljoin(url, htmldecode(match.group(1)))) + except ValueError: + pass + + pkg, ver = scan(url) # ensure this page is in the page index + if pkg: + # process individual package page + for new_url in find_external_links(url, page): + # Process the found URL + base, frag = egg_info_for_url(new_url) + if base.endswith('.py') and not frag: + if ver: + new_url += '#egg=%s-%s' % (pkg, ver) + else: + self.need_version_info(url) + self.scan_url(new_url) + + return PYPI_MD5.sub( + lambda m: '%s' % m.group(1, 3, 2), page + ) + else: + return "" # no sense double-scanning non-package pages + + def need_version_info(self, url): + self.scan_all( + "Page at %s links to .py file(s) without version info; an index " + "scan is required.", url + ) + + def scan_all(self, msg=None, *args): + if self.index_url not in self.fetched_urls: + if msg: + self.warn(msg, *args) + self.info( + "Scanning index of all packages (this may take a while)" + ) + self.scan_url(self.index_url) + + def find_packages(self, requirement): + self.scan_url(self.index_url + requirement.unsafe_name + '/') + + if not self.package_pages.get(requirement.key): + # Fall back to safe version of the name + self.scan_url(self.index_url + requirement.project_name + '/') + + if not self.package_pages.get(requirement.key): + # We couldn't find the target package, so search the index page too + self.not_found_in_index(requirement) + + for url in list(self.package_pages.get(requirement.key, ())): + # scan each page that might be related to the desired package + self.scan_url(url) + + def obtain(self, requirement, installer=None): + self.prescan() + self.find_packages(requirement) + for dist in self[requirement.key]: + if dist in requirement: + return dist + self.debug("%s does not match %s", requirement, dist) + return super(PackageIndex, self).obtain(requirement, installer) + + def check_hash(self, checker, filename, tfp): + """ + checker is a ContentChecker + """ + checker.report( + self.debug, + "Validating %%s checksum for %s" % filename) + if not checker.is_valid(): + tfp.close() + os.unlink(filename) + raise DistutilsError( + "%s validation failed for %s; " + "possible download problem?" + % (checker.hash.name, os.path.basename(filename)) + ) + + def add_find_links(self, urls): + """Add `urls` to the list that will be prescanned for searches""" + for url in urls: + if ( + self.to_scan is None # if we have already "gone online" + or not URL_SCHEME(url) # or it's a local file/directory + or url.startswith('file:') + or list(distros_for_url(url)) # or a direct package link + ): + # then go ahead and process it now + self.scan_url(url) + else: + # otherwise, defer retrieval till later + self.to_scan.append(url) + + def prescan(self): + """Scan urls scheduled for prescanning (e.g. --find-links)""" + if self.to_scan: + list(map(self.scan_url, self.to_scan)) + self.to_scan = None # from now on, go ahead and process immediately + + def not_found_in_index(self, requirement): + if self[requirement.key]: # we've seen at least one distro + meth, msg = self.info, "Couldn't retrieve index page for %r" + else: # no distros seen for this name, might be misspelled + meth, msg = ( + self.warn, + "Couldn't find index page for %r (maybe misspelled?)") + meth(msg, requirement.unsafe_name) + self.scan_all() + + def download(self, spec, tmpdir): + """Locate and/or download `spec` to `tmpdir`, returning a local path + + `spec` may be a ``Requirement`` object, or a string containing a URL, + an existing local filename, or a project/version requirement spec + (i.e. the string form of a ``Requirement`` object). If it is the URL + of a .py file with an unambiguous ``#egg=name-version`` tag (i.e., one + that escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` is + automatically created alongside the downloaded file. + + If `spec` is a ``Requirement`` object or a string containing a + project/version requirement spec, this method returns the location of + a matching distribution (possibly after downloading it to `tmpdir`). + If `spec` is a locally existing file or directory name, it is simply + returned unchanged. If `spec` is a URL, it is downloaded to a subpath + of `tmpdir`, and the local filename is returned. Various errors may be + raised if a problem occurs during downloading. + """ + if not isinstance(spec, Requirement): + scheme = URL_SCHEME(spec) + if scheme: + # It's a url, download it to tmpdir + found = self._download_url(scheme.group(1), spec, tmpdir) + base, fragment = egg_info_for_url(spec) + if base.endswith('.py'): + found = self.gen_setup(found, fragment, tmpdir) + return found + elif os.path.exists(spec): + # Existing file or directory, just return it + return spec + else: + spec = parse_requirement_arg(spec) + return getattr(self.fetch_distribution(spec, tmpdir), 'location', None) + + def fetch_distribution( + self, requirement, tmpdir, force_scan=False, source=False, + develop_ok=False, local_index=None): + """Obtain a distribution suitable for fulfilling `requirement` + + `requirement` must be a ``pkg_resources.Requirement`` instance. + If necessary, or if the `force_scan` flag is set, the requirement is + searched for in the (online) package index as well as the locally + installed packages. If a distribution matching `requirement` is found, + the returned distribution's ``location`` is the value you would have + gotten from calling the ``download()`` method with the matching + distribution's URL or filename. If no matching distribution is found, + ``None`` is returned. + + If the `source` flag is set, only source distributions and source + checkout links will be considered. Unless the `develop_ok` flag is + set, development and system eggs (i.e., those using the ``.egg-info`` + format) will be ignored. + """ + # process a Requirement + self.info("Searching for %s", requirement) + skipped = {} + dist = None + + def find(req, env=None): + if env is None: + env = self + # Find a matching distribution; may be called more than once + + for dist in env[req.key]: + + if dist.precedence == DEVELOP_DIST and not develop_ok: + if dist not in skipped: + self.warn( + "Skipping development or system egg: %s", dist, + ) + skipped[dist] = 1 + continue + + test = ( + dist in req + and (dist.precedence <= SOURCE_DIST or not source) + ) + if test: + loc = self.download(dist.location, tmpdir) + dist.download_location = loc + if os.path.exists(dist.download_location): + return dist + + if force_scan: + self.prescan() + self.find_packages(requirement) + dist = find(requirement) + + if not dist and local_index is not None: + dist = find(requirement, local_index) + + if dist is None: + if self.to_scan is not None: + self.prescan() + dist = find(requirement) + + if dist is None and not force_scan: + self.find_packages(requirement) + dist = find(requirement) + + if dist is None: + self.warn( + "No local packages or working download links found for %s%s", + (source and "a source distribution of " or ""), + requirement, + ) + else: + self.info("Best match: %s", dist) + return dist.clone(location=dist.download_location) + + def fetch(self, requirement, tmpdir, force_scan=False, source=False): + """Obtain a file suitable for fulfilling `requirement` + + DEPRECATED; use the ``fetch_distribution()`` method now instead. For + backward compatibility, this routine is identical but returns the + ``location`` of the downloaded distribution instead of a distribution + object. + """ + dist = self.fetch_distribution(requirement, tmpdir, force_scan, source) + if dist is not None: + return dist.location + return None + + def gen_setup(self, filename, fragment, tmpdir): + match = EGG_FRAGMENT.match(fragment) + dists = match and [ + d for d in + interpret_distro_name(filename, match.group(1), None) if d.version + ] or [] + + if len(dists) == 1: # unambiguous ``#egg`` fragment + basename = os.path.basename(filename) + + # Make sure the file has been downloaded to the temp dir. + if os.path.dirname(filename) != tmpdir: + dst = os.path.join(tmpdir, basename) + from setuptools.command.easy_install import samefile + if not samefile(filename, dst): + shutil.copy2(filename, dst) + filename = dst + + with open(os.path.join(tmpdir, 'setup.py'), 'w') as file: + file.write( + "from setuptools import setup\n" + "setup(name=%r, version=%r, py_modules=[%r])\n" + % ( + dists[0].project_name, dists[0].version, + os.path.splitext(basename)[0] + ) + ) + return filename + + elif match: + raise DistutilsError( + "Can't unambiguously interpret project/version identifier %r; " + "any dashes in the name or version should be escaped using " + "underscores. %r" % (fragment, dists) + ) + else: + raise DistutilsError( + "Can't process plain .py files without an '#egg=name-version'" + " suffix to enable automatic setup script generation." + ) + + dl_blocksize = 8192 + + def _download_to(self, url, filename): + self.info("Downloading %s", url) + # Download the file + fp = None + try: + checker = HashChecker.from_url(url) + fp = self.open_url(url) + if isinstance(fp, urllib.error.HTTPError): + raise DistutilsError( + "Can't download %s: %s %s" % (url, fp.code, fp.msg) + ) + headers = fp.info() + blocknum = 0 + bs = self.dl_blocksize + size = -1 + if "content-length" in headers: + # Some servers return multiple Content-Length headers :( + sizes = get_all_headers(headers, 'Content-Length') + size = max(map(int, sizes)) + self.reporthook(url, filename, blocknum, bs, size) + with open(filename, 'wb') as tfp: + while True: + block = fp.read(bs) + if block: + checker.feed(block) + tfp.write(block) + blocknum += 1 + self.reporthook(url, filename, blocknum, bs, size) + else: + break + self.check_hash(checker, filename, tfp) + return headers + finally: + if fp: + fp.close() + + def reporthook(self, url, filename, blocknum, blksize, size): + pass # no-op + + def open_url(self, url, warning=None): + if url.startswith('file:'): + return local_open(url) + try: + return open_with_auth(url, self.opener) + except (ValueError, http_client.InvalidURL) as v: + msg = ' '.join([str(arg) for arg in v.args]) + if warning: + self.warn(warning, msg) + else: + raise DistutilsError('%s %s' % (url, msg)) + except urllib.error.HTTPError as v: + return v + except urllib.error.URLError as v: + if warning: + self.warn(warning, v.reason) + else: + raise DistutilsError("Download error for %s: %s" + % (url, v.reason)) + except http_client.BadStatusLine as v: + if warning: + self.warn(warning, v.line) + else: + raise DistutilsError( + '%s returned a bad status line. The server might be ' + 'down, %s' % + (url, v.line) + ) + except (http_client.HTTPException, socket.error) as v: + if warning: + self.warn(warning, v) + else: + raise DistutilsError("Download error for %s: %s" + % (url, v)) + + def _download_url(self, scheme, url, tmpdir): + # Determine download filename + # + name, fragment = egg_info_for_url(url) + if name: + while '..' in name: + name = name.replace('..', '.').replace('\\', '_') + else: + name = "__downloaded__" # default if URL has no path contents + + if name.endswith('.egg.zip'): + name = name[:-4] # strip the extra .zip before download + + filename = os.path.join(tmpdir, name) + + # Download the file + # + if scheme == 'svn' or scheme.startswith('svn+'): + return self._download_svn(url, filename) + elif scheme == 'git' or scheme.startswith('git+'): + return self._download_git(url, filename) + elif scheme.startswith('hg+'): + return self._download_hg(url, filename) + elif scheme == 'file': + return urllib.request.url2pathname(urllib.parse.urlparse(url)[2]) + else: + self.url_ok(url, True) # raises error if not allowed + return self._attempt_download(url, filename) + + def scan_url(self, url): + self.process_url(url, True) + + def _attempt_download(self, url, filename): + headers = self._download_to(url, filename) + if 'html' in headers.get('content-type', '').lower(): + return self._download_html(url, headers, filename) + else: + return filename + + def _download_html(self, url, headers, filename): + file = open(filename) + for line in file: + if line.strip(): + # Check for a subversion index page + if re.search(r'([^- ]+ - )?Revision \d+:', line): + # it's a subversion index page: + file.close() + os.unlink(filename) + return self._download_svn(url, filename) + break # not an index page + file.close() + os.unlink(filename) + raise DistutilsError("Unexpected HTML page found at " + url) + + def _download_svn(self, url, filename): + warnings.warn("SVN download support is deprecated", UserWarning) + url = url.split('#', 1)[0] # remove any fragment for svn's sake + creds = '' + if url.lower().startswith('svn:') and '@' in url: + scheme, netloc, path, p, q, f = urllib.parse.urlparse(url) + if not netloc and path.startswith('//') and '/' in path[2:]: + netloc, path = path[2:].split('/', 1) + auth, host = _splituser(netloc) + if auth: + if ':' in auth: + user, pw = auth.split(':', 1) + creds = " --username=%s --password=%s" % (user, pw) + else: + creds = " --username=" + auth + netloc = host + parts = scheme, netloc, url, p, q, f + url = urllib.parse.urlunparse(parts) + self.info("Doing subversion checkout from %s to %s", url, filename) + os.system("svn checkout%s -q %s %s" % (creds, url, filename)) + return filename + + @staticmethod + def _vcs_split_rev_from_url(url, pop_prefix=False): + scheme, netloc, path, query, frag = urllib.parse.urlsplit(url) + + scheme = scheme.split('+', 1)[-1] + + # Some fragment identification fails + path = path.split('#', 1)[0] + + rev = None + if '@' in path: + path, rev = path.rsplit('@', 1) + + # Also, discard fragment + url = urllib.parse.urlunsplit((scheme, netloc, path, query, '')) + + return url, rev + + def _download_git(self, url, filename): + filename = filename.split('#', 1)[0] + url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True) + + self.info("Doing git clone from %s to %s", url, filename) + os.system("git clone --quiet %s %s" % (url, filename)) + + if rev is not None: + self.info("Checking out %s", rev) + os.system("git -C %s checkout --quiet %s" % ( + filename, + rev, + )) + + return filename + + def _download_hg(self, url, filename): + filename = filename.split('#', 1)[0] + url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True) + + self.info("Doing hg clone from %s to %s", url, filename) + os.system("hg clone --quiet %s %s" % (url, filename)) + + if rev is not None: + self.info("Updating to %s", rev) + os.system("hg --cwd %s up -C -r %s -q" % ( + filename, + rev, + )) + + return filename + + def debug(self, msg, *args): + log.debug(msg, *args) + + def info(self, msg, *args): + log.info(msg, *args) + + def warn(self, msg, *args): + log.warn(msg, *args) + + +# This pattern matches a character entity reference (a decimal numeric +# references, a hexadecimal numeric reference, or a named reference). +entity_sub = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?').sub + + +def decode_entity(match): + what = match.group(0) + return unescape(what) + + +def htmldecode(text): + """ + Decode HTML entities in the given text. + + >>> htmldecode( + ... 'https://../package_name-0.1.2.tar.gz' + ... '?tokena=A&tokenb=B">package_name-0.1.2.tar.gz') + 'https://../package_name-0.1.2.tar.gz?tokena=A&tokenb=B">package_name-0.1.2.tar.gz' + """ + return entity_sub(decode_entity, text) + + +def socket_timeout(timeout=15): + def _socket_timeout(func): + def _socket_timeout(*args, **kwargs): + old_timeout = socket.getdefaulttimeout() + socket.setdefaulttimeout(timeout) + try: + return func(*args, **kwargs) + finally: + socket.setdefaulttimeout(old_timeout) + + return _socket_timeout + + return _socket_timeout + + +def _encode_auth(auth): + """ + A function compatible with Python 2.3-3.3 that will encode + auth from a URL suitable for an HTTP header. + >>> str(_encode_auth('username%3Apassword')) + 'dXNlcm5hbWU6cGFzc3dvcmQ=' + + Long auth strings should not cause a newline to be inserted. + >>> long_auth = 'username:' + 'password'*10 + >>> chr(10) in str(_encode_auth(long_auth)) + False + """ + auth_s = urllib.parse.unquote(auth) + # convert to bytes + auth_bytes = auth_s.encode() + encoded_bytes = base64.b64encode(auth_bytes) + # convert back to a string + encoded = encoded_bytes.decode() + # strip the trailing carriage return + return encoded.replace('\n', '') + + +class Credential: + """ + A username/password pair. Use like a namedtuple. + """ + + def __init__(self, username, password): + self.username = username + self.password = password + + def __iter__(self): + yield self.username + yield self.password + + def __str__(self): + return '%(username)s:%(password)s' % vars(self) + + +class PyPIConfig(configparser.RawConfigParser): + def __init__(self): + """ + Load from ~/.pypirc + """ + defaults = dict.fromkeys(['username', 'password', 'repository'], '') + configparser.RawConfigParser.__init__(self, defaults) + + rc = os.path.join(os.path.expanduser('~'), '.pypirc') + if os.path.exists(rc): + self.read(rc) + + @property + def creds_by_repository(self): + sections_with_repositories = [ + section for section in self.sections() + if self.get(section, 'repository').strip() + ] + + return dict(map(self._get_repo_cred, sections_with_repositories)) + + def _get_repo_cred(self, section): + repo = self.get(section, 'repository').strip() + return repo, Credential( + self.get(section, 'username').strip(), + self.get(section, 'password').strip(), + ) + + def find_credential(self, url): + """ + If the URL indicated appears to be a repository defined in this + config, return the credential for that repository. + """ + for repository, cred in self.creds_by_repository.items(): + if url.startswith(repository): + return cred + + +def open_with_auth(url, opener=urllib.request.urlopen): + """Open a urllib2 request, handling HTTP authentication""" + + parsed = urllib.parse.urlparse(url) + scheme, netloc, path, params, query, frag = parsed + + # Double scheme does not raise on Mac OS X as revealed by a + # failing test. We would expect "nonnumeric port". Refs #20. + if netloc.endswith(':'): + raise http_client.InvalidURL("nonnumeric port: ''") + + if scheme in ('http', 'https'): + auth, address = _splituser(netloc) + else: + auth = None + + if not auth: + cred = PyPIConfig().find_credential(url) + if cred: + auth = str(cred) + info = cred.username, url + log.info('Authenticating as %s for %s (from .pypirc)', *info) + + if auth: + auth = "Basic " + _encode_auth(auth) + parts = scheme, address, path, params, query, frag + new_url = urllib.parse.urlunparse(parts) + request = urllib.request.Request(new_url) + request.add_header("Authorization", auth) + else: + request = urllib.request.Request(url) + + request.add_header('User-Agent', user_agent) + fp = opener(request) + + if auth: + # Put authentication info back into request URL if same host, + # so that links found on the page will work + s2, h2, path2, param2, query2, frag2 = urllib.parse.urlparse(fp.url) + if s2 == scheme and h2 == address: + parts = s2, netloc, path2, param2, query2, frag2 + fp.url = urllib.parse.urlunparse(parts) + + return fp + + +# copy of urllib.parse._splituser from Python 3.8 +def _splituser(host): + """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.""" + user, delim, host = host.rpartition('@') + return (user if delim else None), host + + +# adding a timeout to avoid freezing package_index +open_with_auth = socket_timeout(_SOCKET_TIMEOUT)(open_with_auth) + + +def fix_sf_url(url): + return url # backward compatibility + + +def local_open(url): + """Read a local path, with special support for directories""" + scheme, server, path, param, query, frag = urllib.parse.urlparse(url) + filename = urllib.request.url2pathname(path) + if os.path.isfile(filename): + return urllib.request.urlopen(url) + elif path.endswith('/') and os.path.isdir(filename): + files = [] + for f in os.listdir(filename): + filepath = os.path.join(filename, f) + if f == 'index.html': + with open(filepath, 'r') as fp: + body = fp.read() + break + elif os.path.isdir(filepath): + f += '/' + files.append('<a href="{name}">{name}</a>'.format(name=f)) + else: + tmpl = ( + "<html><head><title>{url}" + "{files}") + body = tmpl.format(url=url, files='\n'.join(files)) + status, message = 200, "OK" + else: + status, message, body = 404, "Path not found", "Not found" + + headers = {'content-type': 'text/html'} + body_stream = six.StringIO(body) + return urllib.error.HTTPError(url, status, message, headers, body_stream) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/pep425tags.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/pep425tags.py new file mode 100644 index 0000000000000000000000000000000000000000..48745a29027400f1c921b52b7d492a26d4e5d5a2 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/pep425tags.py @@ -0,0 +1,319 @@ +# This file originally from pip: +# https://github.com/pypa/pip/blob/8f4f15a5a95d7d5b511ceaee9ed261176c181970/src/pip/_internal/pep425tags.py +"""Generate and work with PEP 425 Compatibility Tags.""" +from __future__ import absolute_import + +import distutils.util +from distutils import log +import platform +import re +import sys +import sysconfig +import warnings +from collections import OrderedDict + +from .extern import six + +from . import glibc + +_osx_arch_pat = re.compile(r'(.+)_(\d+)_(\d+)_(.+)') + + +def get_config_var(var): + try: + return sysconfig.get_config_var(var) + except IOError as e: # Issue #1074 + warnings.warn("{}".format(e), RuntimeWarning) + return None + + +def get_abbr_impl(): + """Return abbreviated implementation name.""" + if hasattr(sys, 'pypy_version_info'): + pyimpl = 'pp' + elif sys.platform.startswith('java'): + pyimpl = 'jy' + elif sys.platform == 'cli': + pyimpl = 'ip' + else: + pyimpl = 'cp' + return pyimpl + + +def get_impl_ver(): + """Return implementation version.""" + impl_ver = get_config_var("py_version_nodot") + if not impl_ver or get_abbr_impl() == 'pp': + impl_ver = ''.join(map(str, get_impl_version_info())) + return impl_ver + + +def get_impl_version_info(): + """Return sys.version_info-like tuple for use in decrementing the minor + version.""" + if get_abbr_impl() == 'pp': + # as per https://github.com/pypa/pip/issues/2882 + return (sys.version_info[0], sys.pypy_version_info.major, + sys.pypy_version_info.minor) + else: + return sys.version_info[0], sys.version_info[1] + + +def get_impl_tag(): + """ + Returns the Tag for this specific implementation. + """ + return "{}{}".format(get_abbr_impl(), get_impl_ver()) + + +def get_flag(var, fallback, expected=True, warn=True): + """Use a fallback method for determining SOABI flags if the needed config + var is unset or unavailable.""" + val = get_config_var(var) + if val is None: + if warn: + log.debug("Config variable '%s' is unset, Python ABI tag may " + "be incorrect", var) + return fallback() + return val == expected + + +def get_abi_tag(): + """Return the ABI tag based on SOABI (if available) or emulate SOABI + (CPython 2, PyPy).""" + soabi = get_config_var('SOABI') + impl = get_abbr_impl() + if not soabi and impl in {'cp', 'pp'} and hasattr(sys, 'maxunicode'): + d = '' + m = '' + u = '' + if get_flag('Py_DEBUG', + lambda: hasattr(sys, 'gettotalrefcount'), + warn=(impl == 'cp')): + d = 'd' + if get_flag('WITH_PYMALLOC', + lambda: impl == 'cp', + warn=(impl == 'cp')): + m = 'm' + if get_flag('Py_UNICODE_SIZE', + lambda: sys.maxunicode == 0x10ffff, + expected=4, + warn=(impl == 'cp' and + six.PY2)) \ + and six.PY2: + u = 'u' + abi = '%s%s%s%s%s' % (impl, get_impl_ver(), d, m, u) + elif soabi and soabi.startswith('cpython-'): + abi = 'cp' + soabi.split('-')[1] + elif soabi: + abi = soabi.replace('.', '_').replace('-', '_') + else: + abi = None + return abi + + +def _is_running_32bit(): + return sys.maxsize == 2147483647 + + +def get_platform(): + """Return our platform name 'win32', 'linux_x86_64'""" + if sys.platform == 'darwin': + # distutils.util.get_platform() returns the release based on the value + # of MACOSX_DEPLOYMENT_TARGET on which Python was built, which may + # be significantly older than the user's current machine. + release, _, machine = platform.mac_ver() + split_ver = release.split('.') + + if machine == "x86_64" and _is_running_32bit(): + machine = "i386" + elif machine == "ppc64" and _is_running_32bit(): + machine = "ppc" + + return 'macosx_{}_{}_{}'.format(split_ver[0], split_ver[1], machine) + + # XXX remove distutils dependency + result = distutils.util.get_platform().replace('.', '_').replace('-', '_') + if result == "linux_x86_64" and _is_running_32bit(): + # 32 bit Python program (running on a 64 bit Linux): pip should only + # install and run 32 bit compiled extensions in that case. + result = "linux_i686" + + return result + + +def is_manylinux1_compatible(): + # Only Linux, and only x86-64 / i686 + if get_platform() not in {"linux_x86_64", "linux_i686"}: + return False + + # Check for presence of _manylinux module + try: + import _manylinux + return bool(_manylinux.manylinux1_compatible) + except (ImportError, AttributeError): + # Fall through to heuristic check below + pass + + # Check glibc version. CentOS 5 uses glibc 2.5. + return glibc.have_compatible_glibc(2, 5) + + +def get_darwin_arches(major, minor, machine): + """Return a list of supported arches (including group arches) for + the given major, minor and machine architecture of a macOS machine. + """ + arches = [] + + def _supports_arch(major, minor, arch): + # Looking at the application support for macOS versions in the chart + # provided by https://en.wikipedia.org/wiki/OS_X#Versions it appears + # our timeline looks roughly like: + # + # 10.0 - Introduces ppc support. + # 10.4 - Introduces ppc64, i386, and x86_64 support, however the ppc64 + # and x86_64 support is CLI only, and cannot be used for GUI + # applications. + # 10.5 - Extends ppc64 and x86_64 support to cover GUI applications. + # 10.6 - Drops support for ppc64 + # 10.7 - Drops support for ppc + # + # Given that we do not know if we're installing a CLI or a GUI + # application, we must be conservative and assume it might be a GUI + # application and behave as if ppc64 and x86_64 support did not occur + # until 10.5. + # + # Note: The above information is taken from the "Application support" + # column in the chart not the "Processor support" since I believe + # that we care about what instruction sets an application can use + # not which processors the OS supports. + if arch == 'ppc': + return (major, minor) <= (10, 5) + if arch == 'ppc64': + return (major, minor) == (10, 5) + if arch == 'i386': + return (major, minor) >= (10, 4) + if arch == 'x86_64': + return (major, minor) >= (10, 5) + if arch in groups: + for garch in groups[arch]: + if _supports_arch(major, minor, garch): + return True + return False + + groups = OrderedDict([ + ("fat", ("i386", "ppc")), + ("intel", ("x86_64", "i386")), + ("fat64", ("x86_64", "ppc64")), + ("fat32", ("x86_64", "i386", "ppc")), + ]) + + if _supports_arch(major, minor, machine): + arches.append(machine) + + for garch in groups: + if machine in groups[garch] and _supports_arch(major, minor, garch): + arches.append(garch) + + arches.append('universal') + + return arches + + +def get_supported(versions=None, noarch=False, platform=None, + impl=None, abi=None): + """Return a list of supported tags for each version specified in + `versions`. + + :param versions: a list of string versions, of the form ["33", "32"], + or None. The first version will be assumed to support our ABI. + :param platform: specify the exact platform you want valid + tags for, or None. If None, use the local system platform. + :param impl: specify the exact implementation you want valid + tags for, or None. If None, use the local interpreter impl. + :param abi: specify the exact abi you want valid + tags for, or None. If None, use the local interpreter abi. + """ + supported = [] + + # Versions must be given with respect to the preference + if versions is None: + versions = [] + version_info = get_impl_version_info() + major = version_info[:-1] + # Support all previous minor Python versions. + for minor in range(version_info[-1], -1, -1): + versions.append(''.join(map(str, major + (minor,)))) + + impl = impl or get_abbr_impl() + + abis = [] + + abi = abi or get_abi_tag() + if abi: + abis[0:0] = [abi] + + abi3s = set() + import imp + for suffix in imp.get_suffixes(): + if suffix[0].startswith('.abi'): + abi3s.add(suffix[0].split('.', 2)[1]) + + abis.extend(sorted(list(abi3s))) + + abis.append('none') + + if not noarch: + arch = platform or get_platform() + if arch.startswith('macosx'): + # support macosx-10.6-intel on macosx-10.9-x86_64 + match = _osx_arch_pat.match(arch) + if match: + name, major, minor, actual_arch = match.groups() + tpl = '{}_{}_%i_%s'.format(name, major) + arches = [] + for m in reversed(range(int(minor) + 1)): + for a in get_darwin_arches(int(major), m, actual_arch): + arches.append(tpl % (m, a)) + else: + # arch pattern didn't match (?!) + arches = [arch] + elif platform is None and is_manylinux1_compatible(): + arches = [arch.replace('linux', 'manylinux1'), arch] + else: + arches = [arch] + + # Current version, current API (built specifically for our Python): + for abi in abis: + for arch in arches: + supported.append(('%s%s' % (impl, versions[0]), abi, arch)) + + # abi3 modules compatible with older version of Python + for version in versions[1:]: + # abi3 was introduced in Python 3.2 + if version in {'31', '30'}: + break + for abi in abi3s: # empty set if not Python 3 + for arch in arches: + supported.append(("%s%s" % (impl, version), abi, arch)) + + # Has binaries, does not use the Python API: + for arch in arches: + supported.append(('py%s' % (versions[0][0]), 'none', arch)) + + # No abi / arch, but requires our implementation: + supported.append(('%s%s' % (impl, versions[0]), 'none', 'any')) + # Tagged specifically as being cross-version compatible + # (with just the major version specified) + supported.append(('%s%s' % (impl, versions[0][0]), 'none', 'any')) + + # No abi / arch, generic Python + for i, version in enumerate(versions): + supported.append(('py%s' % (version,), 'none', 'any')) + if i == 0: + supported.append(('py%s' % (version[0]), 'none', 'any')) + + return supported + + +implementation_tag = get_impl_tag() diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/py27compat.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/py27compat.py new file mode 100644 index 0000000000000000000000000000000000000000..2985011b92f7449e784f5f056dd24ffd991d24bd --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/py27compat.py @@ -0,0 +1,28 @@ +""" +Compatibility Support for Python 2.7 and earlier +""" + +import platform + +from setuptools.extern import six + + +def get_all_headers(message, key): + """ + Given an HTTPMessage, return all headers matching a given key. + """ + return message.get_all(key) + + +if six.PY2: + def get_all_headers(message, key): + return message.getheaders(key) + + +linux_py2_ascii = ( + platform.system() == 'Linux' and + six.PY2 +) + +rmtree_safe = str if linux_py2_ascii else lambda x: x +"""Workaround for http://bugs.python.org/issue24672""" diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/py31compat.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/py31compat.py new file mode 100644 index 0000000000000000000000000000000000000000..e1da7ee2a2c56e46e09665d98ba1bc5bfedd2c3e --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/py31compat.py @@ -0,0 +1,32 @@ +__all__ = [] + +__metaclass__ = type + + +try: + # Python >=3.2 + from tempfile import TemporaryDirectory +except ImportError: + import shutil + import tempfile + + class TemporaryDirectory: + """ + Very simple temporary directory context manager. + Will try to delete afterward, but will also ignore OS and similar + errors on deletion. + """ + + def __init__(self, **kwargs): + self.name = None # Handle mkdtemp raising an exception + self.name = tempfile.mkdtemp(**kwargs) + + def __enter__(self): + return self.name + + def __exit__(self, exctype, excvalue, exctrace): + try: + shutil.rmtree(self.name, True) + except OSError: # removal errors are not the only possible + pass + self.name = None diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/py33compat.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/py33compat.py new file mode 100644 index 0000000000000000000000000000000000000000..cb69443638354b46b43da5bbf187b4f7cba301f1 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/py33compat.py @@ -0,0 +1,59 @@ +import dis +import array +import collections + +try: + import html +except ImportError: + html = None + +from setuptools.extern import six +from setuptools.extern.six.moves import html_parser + +__metaclass__ = type + +OpArg = collections.namedtuple('OpArg', 'opcode arg') + + +class Bytecode_compat: + def __init__(self, code): + self.code = code + + def __iter__(self): + """Yield '(op,arg)' pair for each operation in code object 'code'""" + + bytes = array.array('b', self.code.co_code) + eof = len(self.code.co_code) + + ptr = 0 + extended_arg = 0 + + while ptr < eof: + + op = bytes[ptr] + + if op >= dis.HAVE_ARGUMENT: + + arg = bytes[ptr + 1] + bytes[ptr + 2] * 256 + extended_arg + ptr += 3 + + if op == dis.EXTENDED_ARG: + long_type = six.integer_types[-1] + extended_arg = arg * long_type(65536) + continue + + else: + arg = None + ptr += 1 + + yield OpArg(op, arg) + + +Bytecode = getattr(dis, 'Bytecode', Bytecode_compat) + + +unescape = getattr(html, 'unescape', None) +if unescape is None: + # HTMLParser.unescape is deprecated since Python 3.4, and will be removed + # from 3.9. + unescape = html_parser.HTMLParser().unescape diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/sandbox.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/sandbox.py new file mode 100644 index 0000000000000000000000000000000000000000..685f3f72e3611a5fa99c999e233ffd179c431a6d --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/sandbox.py @@ -0,0 +1,491 @@ +import os +import sys +import tempfile +import operator +import functools +import itertools +import re +import contextlib +import pickle +import textwrap + +from setuptools.extern import six +from setuptools.extern.six.moves import builtins, map + +import pkg_resources.py31compat + +if sys.platform.startswith('java'): + import org.python.modules.posix.PosixModule as _os +else: + _os = sys.modules[os.name] +try: + _file = file +except NameError: + _file = None +_open = open +from distutils.errors import DistutilsError +from pkg_resources import working_set + + +__all__ = [ + "AbstractSandbox", "DirectorySandbox", "SandboxViolation", "run_setup", +] + + +def _execfile(filename, globals, locals=None): + """ + Python 3 implementation of execfile. + """ + mode = 'rb' + with open(filename, mode) as stream: + script = stream.read() + if locals is None: + locals = globals + code = compile(script, filename, 'exec') + exec(code, globals, locals) + + +@contextlib.contextmanager +def save_argv(repl=None): + saved = sys.argv[:] + if repl is not None: + sys.argv[:] = repl + try: + yield saved + finally: + sys.argv[:] = saved + + +@contextlib.contextmanager +def save_path(): + saved = sys.path[:] + try: + yield saved + finally: + sys.path[:] = saved + + +@contextlib.contextmanager +def override_temp(replacement): + """ + Monkey-patch tempfile.tempdir with replacement, ensuring it exists + """ + pkg_resources.py31compat.makedirs(replacement, exist_ok=True) + + saved = tempfile.tempdir + + tempfile.tempdir = replacement + + try: + yield + finally: + tempfile.tempdir = saved + + +@contextlib.contextmanager +def pushd(target): + saved = os.getcwd() + os.chdir(target) + try: + yield saved + finally: + os.chdir(saved) + + +class UnpickleableException(Exception): + """ + An exception representing another Exception that could not be pickled. + """ + + @staticmethod + def dump(type, exc): + """ + Always return a dumped (pickled) type and exc. If exc can't be pickled, + wrap it in UnpickleableException first. + """ + try: + return pickle.dumps(type), pickle.dumps(exc) + except Exception: + # get UnpickleableException inside the sandbox + from setuptools.sandbox import UnpickleableException as cls + return cls.dump(cls, cls(repr(exc))) + + +class ExceptionSaver: + """ + A Context Manager that will save an exception, serialized, and restore it + later. + """ + + def __enter__(self): + return self + + def __exit__(self, type, exc, tb): + if not exc: + return + + # dump the exception + self._saved = UnpickleableException.dump(type, exc) + self._tb = tb + + # suppress the exception + return True + + def resume(self): + "restore and re-raise any exception" + + if '_saved' not in vars(self): + return + + type, exc = map(pickle.loads, self._saved) + six.reraise(type, exc, self._tb) + + +@contextlib.contextmanager +def save_modules(): + """ + Context in which imported modules are saved. + + Translates exceptions internal to the context into the equivalent exception + outside the context. + """ + saved = sys.modules.copy() + with ExceptionSaver() as saved_exc: + yield saved + + sys.modules.update(saved) + # remove any modules imported since + del_modules = ( + mod_name for mod_name in sys.modules + if mod_name not in saved + # exclude any encodings modules. See #285 + and not mod_name.startswith('encodings.') + ) + _clear_modules(del_modules) + + saved_exc.resume() + + +def _clear_modules(module_names): + for mod_name in list(module_names): + del sys.modules[mod_name] + + +@contextlib.contextmanager +def save_pkg_resources_state(): + saved = pkg_resources.__getstate__() + try: + yield saved + finally: + pkg_resources.__setstate__(saved) + + +@contextlib.contextmanager +def setup_context(setup_dir): + temp_dir = os.path.join(setup_dir, 'temp') + with save_pkg_resources_state(): + with save_modules(): + hide_setuptools() + with save_path(): + with save_argv(): + with override_temp(temp_dir): + with pushd(setup_dir): + # ensure setuptools commands are available + __import__('setuptools') + yield + + +def _needs_hiding(mod_name): + """ + >>> _needs_hiding('setuptools') + True + >>> _needs_hiding('pkg_resources') + True + >>> _needs_hiding('setuptools_plugin') + False + >>> _needs_hiding('setuptools.__init__') + True + >>> _needs_hiding('distutils') + True + >>> _needs_hiding('os') + False + >>> _needs_hiding('Cython') + True + """ + pattern = re.compile(r'(setuptools|pkg_resources|distutils|Cython)(\.|$)') + return bool(pattern.match(mod_name)) + + +def hide_setuptools(): + """ + Remove references to setuptools' modules from sys.modules to allow the + invocation to import the most appropriate setuptools. This technique is + necessary to avoid issues such as #315 where setuptools upgrading itself + would fail to find a function declared in the metadata. + """ + modules = filter(_needs_hiding, sys.modules) + _clear_modules(modules) + + +def run_setup(setup_script, args): + """Run a distutils setup script, sandboxed in its directory""" + setup_dir = os.path.abspath(os.path.dirname(setup_script)) + with setup_context(setup_dir): + try: + sys.argv[:] = [setup_script] + list(args) + sys.path.insert(0, setup_dir) + # reset to include setup dir, w/clean callback list + working_set.__init__() + working_set.callbacks.append(lambda dist: dist.activate()) + + # __file__ should be a byte string on Python 2 (#712) + dunder_file = ( + setup_script + if isinstance(setup_script, str) else + setup_script.encode(sys.getfilesystemencoding()) + ) + + with DirectorySandbox(setup_dir): + ns = dict(__file__=dunder_file, __name__='__main__') + _execfile(setup_script, ns) + except SystemExit as v: + if v.args and v.args[0]: + raise + # Normal exit, just return + + +class AbstractSandbox: + """Wrap 'os' module and 'open()' builtin for virtualizing setup scripts""" + + _active = False + + def __init__(self): + self._attrs = [ + name for name in dir(_os) + if not name.startswith('_') and hasattr(self, name) + ] + + def _copy(self, source): + for name in self._attrs: + setattr(os, name, getattr(source, name)) + + def __enter__(self): + self._copy(self) + if _file: + builtins.file = self._file + builtins.open = self._open + self._active = True + + def __exit__(self, exc_type, exc_value, traceback): + self._active = False + if _file: + builtins.file = _file + builtins.open = _open + self._copy(_os) + + def run(self, func): + """Run 'func' under os sandboxing""" + with self: + return func() + + def _mk_dual_path_wrapper(name): + original = getattr(_os, name) + + def wrap(self, src, dst, *args, **kw): + if self._active: + src, dst = self._remap_pair(name, src, dst, *args, **kw) + return original(src, dst, *args, **kw) + + return wrap + + for name in ["rename", "link", "symlink"]: + if hasattr(_os, name): + locals()[name] = _mk_dual_path_wrapper(name) + + def _mk_single_path_wrapper(name, original=None): + original = original or getattr(_os, name) + + def wrap(self, path, *args, **kw): + if self._active: + path = self._remap_input(name, path, *args, **kw) + return original(path, *args, **kw) + + return wrap + + if _file: + _file = _mk_single_path_wrapper('file', _file) + _open = _mk_single_path_wrapper('open', _open) + for name in [ + "stat", "listdir", "chdir", "open", "chmod", "chown", "mkdir", + "remove", "unlink", "rmdir", "utime", "lchown", "chroot", "lstat", + "startfile", "mkfifo", "mknod", "pathconf", "access" + ]: + if hasattr(_os, name): + locals()[name] = _mk_single_path_wrapper(name) + + def _mk_single_with_return(name): + original = getattr(_os, name) + + def wrap(self, path, *args, **kw): + if self._active: + path = self._remap_input(name, path, *args, **kw) + return self._remap_output(name, original(path, *args, **kw)) + return original(path, *args, **kw) + + return wrap + + for name in ['readlink', 'tempnam']: + if hasattr(_os, name): + locals()[name] = _mk_single_with_return(name) + + def _mk_query(name): + original = getattr(_os, name) + + def wrap(self, *args, **kw): + retval = original(*args, **kw) + if self._active: + return self._remap_output(name, retval) + return retval + + return wrap + + for name in ['getcwd', 'tmpnam']: + if hasattr(_os, name): + locals()[name] = _mk_query(name) + + def _validate_path(self, path): + """Called to remap or validate any path, whether input or output""" + return path + + def _remap_input(self, operation, path, *args, **kw): + """Called for path inputs""" + return self._validate_path(path) + + def _remap_output(self, operation, path): + """Called for path outputs""" + return self._validate_path(path) + + def _remap_pair(self, operation, src, dst, *args, **kw): + """Called for path pairs like rename, link, and symlink operations""" + return ( + self._remap_input(operation + '-from', src, *args, **kw), + self._remap_input(operation + '-to', dst, *args, **kw) + ) + + +if hasattr(os, 'devnull'): + _EXCEPTIONS = [os.devnull,] +else: + _EXCEPTIONS = [] + + +class DirectorySandbox(AbstractSandbox): + """Restrict operations to a single subdirectory - pseudo-chroot""" + + write_ops = dict.fromkeys([ + "open", "chmod", "chown", "mkdir", "remove", "unlink", "rmdir", + "utime", "lchown", "chroot", "mkfifo", "mknod", "tempnam", + ]) + + _exception_patterns = [ + # Allow lib2to3 to attempt to save a pickled grammar object (#121) + r'.*lib2to3.*\.pickle$', + ] + "exempt writing to paths that match the pattern" + + def __init__(self, sandbox, exceptions=_EXCEPTIONS): + self._sandbox = os.path.normcase(os.path.realpath(sandbox)) + self._prefix = os.path.join(self._sandbox, '') + self._exceptions = [ + os.path.normcase(os.path.realpath(path)) + for path in exceptions + ] + AbstractSandbox.__init__(self) + + def _violation(self, operation, *args, **kw): + from setuptools.sandbox import SandboxViolation + raise SandboxViolation(operation, args, kw) + + if _file: + + def _file(self, path, mode='r', *args, **kw): + if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path): + self._violation("file", path, mode, *args, **kw) + return _file(path, mode, *args, **kw) + + def _open(self, path, mode='r', *args, **kw): + if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path): + self._violation("open", path, mode, *args, **kw) + return _open(path, mode, *args, **kw) + + def tmpnam(self): + self._violation("tmpnam") + + def _ok(self, path): + active = self._active + try: + self._active = False + realpath = os.path.normcase(os.path.realpath(path)) + return ( + self._exempted(realpath) + or realpath == self._sandbox + or realpath.startswith(self._prefix) + ) + finally: + self._active = active + + def _exempted(self, filepath): + start_matches = ( + filepath.startswith(exception) + for exception in self._exceptions + ) + pattern_matches = ( + re.match(pattern, filepath) + for pattern in self._exception_patterns + ) + candidates = itertools.chain(start_matches, pattern_matches) + return any(candidates) + + def _remap_input(self, operation, path, *args, **kw): + """Called for path inputs""" + if operation in self.write_ops and not self._ok(path): + self._violation(operation, os.path.realpath(path), *args, **kw) + return path + + def _remap_pair(self, operation, src, dst, *args, **kw): + """Called for path pairs like rename, link, and symlink operations""" + if not self._ok(src) or not self._ok(dst): + self._violation(operation, src, dst, *args, **kw) + return (src, dst) + + def open(self, file, flags, mode=0o777, *args, **kw): + """Called for low-level os.open()""" + if flags & WRITE_FLAGS and not self._ok(file): + self._violation("os.open", file, flags, mode, *args, **kw) + return _os.open(file, flags, mode, *args, **kw) + + +WRITE_FLAGS = functools.reduce( + operator.or_, [getattr(_os, a, 0) for a in + "O_WRONLY O_RDWR O_APPEND O_CREAT O_TRUNC O_TEMPORARY".split()] +) + + +class SandboxViolation(DistutilsError): + """A setup script attempted to modify the filesystem outside the sandbox""" + + tmpl = textwrap.dedent(""" + SandboxViolation: {cmd}{args!r} {kwargs} + + The package setup script has attempted to modify files on your system + that are not within the EasyInstall build area, and has been aborted. + + This package cannot be safely installed by EasyInstall, and may not + support alternate installation locations even if you run its setup + script by hand. Please inform the package's author and the EasyInstall + maintainers to find out if a fix or workaround is available. + """).lstrip() + + def __str__(self): + cmd, args, kwargs = self.args + return self.tmpl.format(**locals()) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/wheel.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..e11f0a1d912860b0da241dee65f6f76d9c8d45e9 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/wheel.py @@ -0,0 +1,211 @@ +"""Wheels support.""" + +from distutils.util import get_platform +import email +import itertools +import os +import posixpath +import re +import zipfile + +import pkg_resources +import setuptools +from pkg_resources import parse_version +from setuptools.extern.packaging.utils import canonicalize_name +from setuptools.extern.six import PY3 +from setuptools import pep425tags +from setuptools.command.egg_info import write_requirements + + +__metaclass__ = type + + +WHEEL_NAME = re.compile( + r"""^(?P.+?)-(?P\d.*?) + ((-(?P\d.*?))?-(?P.+?)-(?P.+?)-(?P.+?) + )\.whl$""", + re.VERBOSE).match + +NAMESPACE_PACKAGE_INIT = '''\ +try: + __import__('pkg_resources').declare_namespace(__name__) +except ImportError: + __path__ = __import__('pkgutil').extend_path(__path__, __name__) +''' + + +def unpack(src_dir, dst_dir): + '''Move everything under `src_dir` to `dst_dir`, and delete the former.''' + for dirpath, dirnames, filenames in os.walk(src_dir): + subdir = os.path.relpath(dirpath, src_dir) + for f in filenames: + src = os.path.join(dirpath, f) + dst = os.path.join(dst_dir, subdir, f) + os.renames(src, dst) + for n, d in reversed(list(enumerate(dirnames))): + src = os.path.join(dirpath, d) + dst = os.path.join(dst_dir, subdir, d) + if not os.path.exists(dst): + # Directory does not exist in destination, + # rename it and prune it from os.walk list. + os.renames(src, dst) + del dirnames[n] + # Cleanup. + for dirpath, dirnames, filenames in os.walk(src_dir, topdown=True): + assert not filenames + os.rmdir(dirpath) + + +class Wheel: + + def __init__(self, filename): + match = WHEEL_NAME(os.path.basename(filename)) + if match is None: + raise ValueError('invalid wheel name: %r' % filename) + self.filename = filename + for k, v in match.groupdict().items(): + setattr(self, k, v) + + def tags(self): + '''List tags (py_version, abi, platform) supported by this wheel.''' + return itertools.product( + self.py_version.split('.'), + self.abi.split('.'), + self.platform.split('.'), + ) + + def is_compatible(self): + '''Is the wheel is compatible with the current platform?''' + supported_tags = pep425tags.get_supported() + return next((True for t in self.tags() if t in supported_tags), False) + + def egg_name(self): + return pkg_resources.Distribution( + project_name=self.project_name, version=self.version, + platform=(None if self.platform == 'any' else get_platform()), + ).egg_name() + '.egg' + + def get_dist_info(self, zf): + # find the correct name of the .dist-info dir in the wheel file + for member in zf.namelist(): + dirname = posixpath.dirname(member) + if (dirname.endswith('.dist-info') and + canonicalize_name(dirname).startswith( + canonicalize_name(self.project_name))): + return dirname + raise ValueError("unsupported wheel format. .dist-info not found") + + def install_as_egg(self, destination_eggdir): + '''Install wheel as an egg directory.''' + with zipfile.ZipFile(self.filename) as zf: + self._install_as_egg(destination_eggdir, zf) + + def _install_as_egg(self, destination_eggdir, zf): + dist_basename = '%s-%s' % (self.project_name, self.version) + dist_info = self.get_dist_info(zf) + dist_data = '%s.data' % dist_basename + egg_info = os.path.join(destination_eggdir, 'EGG-INFO') + + self._convert_metadata(zf, destination_eggdir, dist_info, egg_info) + self._move_data_entries(destination_eggdir, dist_data) + self._fix_namespace_packages(egg_info, destination_eggdir) + + @staticmethod + def _convert_metadata(zf, destination_eggdir, dist_info, egg_info): + def get_metadata(name): + with zf.open(posixpath.join(dist_info, name)) as fp: + value = fp.read().decode('utf-8') if PY3 else fp.read() + return email.parser.Parser().parsestr(value) + + wheel_metadata = get_metadata('WHEEL') + # Check wheel format version is supported. + wheel_version = parse_version(wheel_metadata.get('Wheel-Version')) + wheel_v1 = ( + parse_version('1.0') <= wheel_version < parse_version('2.0dev0') + ) + if not wheel_v1: + raise ValueError( + 'unsupported wheel format version: %s' % wheel_version) + # Extract to target directory. + os.mkdir(destination_eggdir) + zf.extractall(destination_eggdir) + # Convert metadata. + dist_info = os.path.join(destination_eggdir, dist_info) + dist = pkg_resources.Distribution.from_location( + destination_eggdir, dist_info, + metadata=pkg_resources.PathMetadata(destination_eggdir, dist_info), + ) + + # Note: Evaluate and strip markers now, + # as it's difficult to convert back from the syntax: + # foobar; "linux" in sys_platform and extra == 'test' + def raw_req(req): + req.marker = None + return str(req) + install_requires = list(sorted(map(raw_req, dist.requires()))) + extras_require = { + extra: sorted( + req + for req in map(raw_req, dist.requires((extra,))) + if req not in install_requires + ) + for extra in dist.extras + } + os.rename(dist_info, egg_info) + os.rename( + os.path.join(egg_info, 'METADATA'), + os.path.join(egg_info, 'PKG-INFO'), + ) + setup_dist = setuptools.Distribution( + attrs=dict( + install_requires=install_requires, + extras_require=extras_require, + ), + ) + write_requirements( + setup_dist.get_command_obj('egg_info'), + None, + os.path.join(egg_info, 'requires.txt'), + ) + + @staticmethod + def _move_data_entries(destination_eggdir, dist_data): + """Move data entries to their correct location.""" + dist_data = os.path.join(destination_eggdir, dist_data) + dist_data_scripts = os.path.join(dist_data, 'scripts') + if os.path.exists(dist_data_scripts): + egg_info_scripts = os.path.join( + destination_eggdir, 'EGG-INFO', 'scripts') + os.mkdir(egg_info_scripts) + for entry in os.listdir(dist_data_scripts): + # Remove bytecode, as it's not properly handled + # during easy_install scripts install phase. + if entry.endswith('.pyc'): + os.unlink(os.path.join(dist_data_scripts, entry)) + else: + os.rename( + os.path.join(dist_data_scripts, entry), + os.path.join(egg_info_scripts, entry), + ) + os.rmdir(dist_data_scripts) + for subdir in filter(os.path.exists, ( + os.path.join(dist_data, d) + for d in ('data', 'headers', 'purelib', 'platlib') + )): + unpack(subdir, destination_eggdir) + if os.path.exists(dist_data): + os.rmdir(dist_data) + + @staticmethod + def _fix_namespace_packages(egg_info, destination_eggdir): + namespace_packages = os.path.join( + egg_info, 'namespace_packages.txt') + if os.path.exists(namespace_packages): + with open(namespace_packages) as fp: + namespace_packages = fp.read().split() + for mod in namespace_packages: + mod_dir = os.path.join(destination_eggdir, *mod.split('.')) + mod_init = os.path.join(mod_dir, '__init__.py') + if os.path.exists(mod_dir) and not os.path.exists(mod_init): + with open(mod_init, 'w') as fp: + fp.write(NAMESPACE_PACKAGE_INIT) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/windows_support.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/windows_support.py new file mode 100644 index 0000000000000000000000000000000000000000..cb977cff9545ef5d48ad7cf13f2cbe1ebc3e7cd0 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/setuptools/windows_support.py @@ -0,0 +1,29 @@ +import platform +import ctypes + + +def windows_only(func): + if platform.system() != 'Windows': + return lambda *args, **kwargs: None + return func + + +@windows_only +def hide_file(path): + """ + Set the hidden attribute on a file or directory. + + From http://stackoverflow.com/questions/19622133/ + + `path` must be text. + """ + __import__('ctypes.wintypes') + SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW + SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD + SetFileAttributes.restype = ctypes.wintypes.BOOL + + FILE_ATTRIBUTE_HIDDEN = 0x02 + + ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN) + if not ret: + raise ctypes.WinError() diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/six-1.12.0.dist-info/WHEEL b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/six-1.12.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..c4bde30377756381c5d37d2ed1a082566a715c9b --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/six-1.12.0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.32.3) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/six-1.12.0.dist-info/top_level.txt b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/six-1.12.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..ffe2fce498955b628014618b28c6bcf152466a4a --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/six-1.12.0.dist-info/top_level.txt @@ -0,0 +1 @@ +six diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/socketserver/__init__.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/socketserver/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c5b8c9c28bebea986972e9eb591e0f829381ebdb --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/socketserver/__init__.py @@ -0,0 +1,9 @@ +from __future__ import absolute_import +import sys + +if sys.version_info[0] < 3: + from SocketServer import * +else: + raise ImportError('This package should not be accessible on Python 3. ' + 'Either you are trying to run from the python-future src folder ' + 'or your installation of python-future is corrupted.') diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/colorchooser.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/colorchooser.py new file mode 100644 index 0000000000000000000000000000000000000000..6dde6e8d300184857b92eb94a7e83ac1fe14d904 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/colorchooser.py @@ -0,0 +1,12 @@ +from __future__ import absolute_import + +from future.utils import PY3 + +if PY3: + from tkinter.colorchooser import * +else: + try: + from tkColorChooser import * + except ImportError: + raise ImportError('The tkColorChooser module is missing. Does your Py2 ' + 'installation include tkinter?') diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/commondialog.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/commondialog.py new file mode 100644 index 0000000000000000000000000000000000000000..eb7ae8d6076170bd3a72ca5c37a3a3d80c03afa2 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/commondialog.py @@ -0,0 +1,12 @@ +from __future__ import absolute_import + +from future.utils import PY3 + +if PY3: + from tkinter.commondialog import * +else: + try: + from tkCommonDialog import * + except ImportError: + raise ImportError('The tkCommonDialog module is missing. Does your Py2 ' + 'installation include tkinter?') diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/constants.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..ffe098152f11fb8310f96754d260154dcf7ab41c --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/constants.py @@ -0,0 +1,12 @@ +from __future__ import absolute_import + +from future.utils import PY3 + +if PY3: + from tkinter.constants import * +else: + try: + from Tkconstants import * + except ImportError: + raise ImportError('The Tkconstants module is missing. Does your Py2 ' + 'installation include tkinter?') diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/dialog.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/dialog.py new file mode 100644 index 0000000000000000000000000000000000000000..113370ca2cbf7dd5beff1f510951c95bbe142a91 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/dialog.py @@ -0,0 +1,12 @@ +from __future__ import absolute_import + +from future.utils import PY3 + +if PY3: + from tkinter.dialog import * +else: + try: + from Dialog import * + except ImportError: + raise ImportError('The Dialog module is missing. Does your Py2 ' + 'installation include tkinter?') diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/dnd.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/dnd.py new file mode 100644 index 0000000000000000000000000000000000000000..1ab437917d9e2cb0253846f6023031fea821adcd --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/dnd.py @@ -0,0 +1,12 @@ +from __future__ import absolute_import + +from future.utils import PY3 + +if PY3: + from tkinter.dnd import * +else: + try: + from Tkdnd import * + except ImportError: + raise ImportError('The Tkdnd module is missing. Does your Py2 ' + 'installation include tkinter?') diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/filedialog.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/filedialog.py new file mode 100644 index 0000000000000000000000000000000000000000..93a15388f1722e3da00af3985fae40f65be615e6 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/filedialog.py @@ -0,0 +1,17 @@ +from __future__ import absolute_import + +from future.utils import PY3 + +if PY3: + from tkinter.filedialog import * +else: + try: + from FileDialog import * + except ImportError: + raise ImportError('The FileDialog module is missing. Does your Py2 ' + 'installation include tkinter?') + try: + from tkFileDialog import * + except ImportError: + raise ImportError('The tkFileDialog module is missing. Does your Py2 ' + 'installation include tkinter?') diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/font.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/font.py new file mode 100644 index 0000000000000000000000000000000000000000..628f399a35b9d201c40ece3430890ad01b513265 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/font.py @@ -0,0 +1,12 @@ +from __future__ import absolute_import + +from future.utils import PY3 + +if PY3: + from tkinter.font import * +else: + try: + from tkFont import * + except ImportError: + raise ImportError('The tkFont module is missing. Does your Py2 ' + 'installation include tkinter?') diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/messagebox.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/messagebox.py new file mode 100644 index 0000000000000000000000000000000000000000..b43d8702f59d714817786c82262357598102c6f8 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/tkinter/messagebox.py @@ -0,0 +1,12 @@ +from __future__ import absolute_import + +from future.utils import PY3 + +if PY3: + from tkinter.messagebox import * +else: + try: + from tkMessageBox import * + except ImportError: + raise ImportError('The tkMessageBox module is missing. Does your Py2 ' + 'installation include tkinter?') diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/backports/__init__.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/backports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/backports/makefile.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/backports/makefile.py new file mode 100644 index 0000000000000000000000000000000000000000..740db377d99a963dafa6789e8aed6c2effa5e97d --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/backports/makefile.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +""" +backports.makefile +~~~~~~~~~~~~~~~~~~ + +Backports the Python 3 ``socket.makefile`` method for use with anything that +wants to create a "fake" socket object. +""" +import io + +from socket import SocketIO + + +def backport_makefile(self, mode="r", buffering=None, encoding=None, + errors=None, newline=None): + """ + Backport of ``socket.makefile`` from Python 3.5. + """ + if not set(mode) <= {"r", "w", "b"}: + raise ValueError( + "invalid mode %r (only r, w, b allowed)" % (mode,) + ) + writing = "w" in mode + reading = "r" in mode or not writing + assert reading or writing + binary = "b" in mode + rawmode = "" + if reading: + rawmode += "r" + if writing: + rawmode += "w" + raw = SocketIO(self, rawmode) + self._makefile_refs += 1 + if buffering is None: + buffering = -1 + if buffering < 0: + buffering = io.DEFAULT_BUFFER_SIZE + if buffering == 0: + if not binary: + raise ValueError("unbuffered streams must be binary") + return raw + if reading and writing: + buffer = io.BufferedRWPair(raw, raw, buffering) + elif reading: + buffer = io.BufferedReader(raw, buffering) + else: + assert writing + buffer = io.BufferedWriter(raw, buffering) + if binary: + return buffer + text = io.TextIOWrapper(buffer, encoding, errors, newline) + text.mode = mode + return text diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/abnf_regexp.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/abnf_regexp.py new file mode 100644 index 0000000000000000000000000000000000000000..24c9c3d00ad025662be75f6eb7e90469ab4edd45 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/abnf_regexp.py @@ -0,0 +1,267 @@ +# -*- coding: utf-8 -*- +# 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. +"""Module for the regular expressions crafted from ABNF.""" + +import sys + +# https://tools.ietf.org/html/rfc3986#page-13 +GEN_DELIMS = GENERIC_DELIMITERS = ":/?#[]@" +GENERIC_DELIMITERS_SET = set(GENERIC_DELIMITERS) +# https://tools.ietf.org/html/rfc3986#page-13 +SUB_DELIMS = SUB_DELIMITERS = "!$&'()*+,;=" +SUB_DELIMITERS_SET = set(SUB_DELIMITERS) +# Escape the '*' for use in regular expressions +SUB_DELIMITERS_RE = r"!$&'()\*+,;=" +RESERVED_CHARS_SET = GENERIC_DELIMITERS_SET.union(SUB_DELIMITERS_SET) +ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' +DIGIT = '0123456789' +# https://tools.ietf.org/html/rfc3986#section-2.3 +UNRESERVED = UNRESERVED_CHARS = ALPHA + DIGIT + r'._!-' +UNRESERVED_CHARS_SET = set(UNRESERVED_CHARS) +NON_PCT_ENCODED_SET = RESERVED_CHARS_SET.union(UNRESERVED_CHARS_SET) +# We need to escape the '-' in this case: +UNRESERVED_RE = r'A-Za-z0-9._~\-' + +# Percent encoded character values +PERCENT_ENCODED = PCT_ENCODED = '%[A-Fa-f0-9]{2}' +PCHAR = '([' + UNRESERVED_RE + SUB_DELIMITERS_RE + ':@]|%s)' % PCT_ENCODED + +# NOTE(sigmavirus24): We're going to use more strict regular expressions +# than appear in Appendix B for scheme. This will prevent over-eager +# consuming of items that aren't schemes. +SCHEME_RE = '[a-zA-Z][a-zA-Z0-9+.-]*' +_AUTHORITY_RE = '[^/?#]*' +_PATH_RE = '[^?#]*' +_QUERY_RE = '[^#]*' +_FRAGMENT_RE = '.*' + +# Extracted from http://tools.ietf.org/html/rfc3986#appendix-B +COMPONENT_PATTERN_DICT = { + 'scheme': SCHEME_RE, + 'authority': _AUTHORITY_RE, + 'path': _PATH_RE, + 'query': _QUERY_RE, + 'fragment': _FRAGMENT_RE, +} + +# See http://tools.ietf.org/html/rfc3986#appendix-B +# In this case, we name each of the important matches so we can use +# SRE_Match#groupdict to parse the values out if we so choose. This is also +# modified to ignore other matches that are not important to the parsing of +# the reference so we can also simply use SRE_Match#groups. +URL_PARSING_RE = ( + r'(?:(?P{scheme}):)?(?://(?P{authority}))?' + r'(?P{path})(?:\?(?P{query}))?' + r'(?:#(?P{fragment}))?' +).format(**COMPONENT_PATTERN_DICT) + + +# ######################### +# Authority Matcher Section +# ######################### + +# Host patterns, see: http://tools.ietf.org/html/rfc3986#section-3.2.2 +# The pattern for a regular name, e.g., www.google.com, api.github.com +REGULAR_NAME_RE = REG_NAME = '((?:{0}|[{1}])*)'.format( + '%[0-9A-Fa-f]{2}', SUB_DELIMITERS_RE + UNRESERVED_RE +) +# The pattern for an IPv4 address, e.g., 192.168.255.255, 127.0.0.1, +IPv4_RE = r'([0-9]{1,3}\.){3}[0-9]{1,3}' +# Hexadecimal characters used in each piece of an IPv6 address +HEXDIG_RE = '[0-9A-Fa-f]{1,4}' +# Least-significant 32 bits of an IPv6 address +LS32_RE = '({hex}:{hex}|{ipv4})'.format(hex=HEXDIG_RE, ipv4=IPv4_RE) +# Substitutions into the following patterns for IPv6 patterns defined +# http://tools.ietf.org/html/rfc3986#page-20 +_subs = {'hex': HEXDIG_RE, 'ls32': LS32_RE} + +# Below: h16 = hexdig, see: https://tools.ietf.org/html/rfc5234 for details +# about ABNF (Augmented Backus-Naur Form) use in the comments +variations = [ + # 6( h16 ":" ) ls32 + '(%(hex)s:){6}%(ls32)s' % _subs, + # "::" 5( h16 ":" ) ls32 + '::(%(hex)s:){5}%(ls32)s' % _subs, + # [ h16 ] "::" 4( h16 ":" ) ls32 + '(%(hex)s)?::(%(hex)s:){4}%(ls32)s' % _subs, + # [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + '((%(hex)s:)?%(hex)s)?::(%(hex)s:){3}%(ls32)s' % _subs, + # [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + '((%(hex)s:){0,2}%(hex)s)?::(%(hex)s:){2}%(ls32)s' % _subs, + # [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + '((%(hex)s:){0,3}%(hex)s)?::%(hex)s:%(ls32)s' % _subs, + # [ *4( h16 ":" ) h16 ] "::" ls32 + '((%(hex)s:){0,4}%(hex)s)?::%(ls32)s' % _subs, + # [ *5( h16 ":" ) h16 ] "::" h16 + '((%(hex)s:){0,5}%(hex)s)?::%(hex)s' % _subs, + # [ *6( h16 ":" ) h16 ] "::" + '((%(hex)s:){0,6}%(hex)s)?::' % _subs, +] + +IPv6_RE = '(({0})|({1})|({2})|({3})|({4})|({5})|({6})|({7})|({8}))'.format( + *variations +) + +IPv_FUTURE_RE = r'v[0-9A-Fa-f]+\.[%s]+' % ( + UNRESERVED_RE + SUB_DELIMITERS_RE + ':' +) + +# RFC 6874 Zone ID ABNF +ZONE_ID = '(?:[' + UNRESERVED_RE + ']|' + PCT_ENCODED + ')+' + +IPv6_ADDRZ_RFC4007_RE = IPv6_RE + '(?:(?:%25|%)' + ZONE_ID + ')?' +IPv6_ADDRZ_RE = IPv6_RE + '(?:%25' + ZONE_ID + ')?' + +IP_LITERAL_RE = r'\[({0}|{1})\]'.format( + IPv6_ADDRZ_RFC4007_RE, + IPv_FUTURE_RE, +) + +# Pattern for matching the host piece of the authority +HOST_RE = HOST_PATTERN = '({0}|{1}|{2})'.format( + REG_NAME, + IPv4_RE, + IP_LITERAL_RE, +) +USERINFO_RE = '^([' + UNRESERVED_RE + SUB_DELIMITERS_RE + ':]|%s)+' % ( + PCT_ENCODED +) +PORT_RE = '[0-9]{1,5}' + +# #################### +# Path Matcher Section +# #################### + +# See http://tools.ietf.org/html/rfc3986#section-3.3 for more information +# about the path patterns defined below. +segments = { + 'segment': PCHAR + '*', + # Non-zero length segment + 'segment-nz': PCHAR + '+', + # Non-zero length segment without ":" + 'segment-nz-nc': PCHAR.replace(':', '') + '+' +} + +# Path types taken from Section 3.3 (linked above) +PATH_EMPTY = '^$' +PATH_ROOTLESS = '%(segment-nz)s(/%(segment)s)*' % segments +PATH_NOSCHEME = '%(segment-nz-nc)s(/%(segment)s)*' % segments +PATH_ABSOLUTE = '/(%s)?' % PATH_ROOTLESS +PATH_ABEMPTY = '(/%(segment)s)*' % segments +PATH_RE = '^(%s|%s|%s|%s|%s)$' % ( + PATH_ABEMPTY, PATH_ABSOLUTE, PATH_NOSCHEME, PATH_ROOTLESS, PATH_EMPTY +) + +FRAGMENT_RE = QUERY_RE = ( + '^([/?:@' + UNRESERVED_RE + SUB_DELIMITERS_RE + ']|%s)*$' % PCT_ENCODED +) + +# ########################## +# Relative reference matcher +# ########################## + +# See http://tools.ietf.org/html/rfc3986#section-4.2 for details +RELATIVE_PART_RE = '(//%s%s|%s|%s|%s)' % ( + COMPONENT_PATTERN_DICT['authority'], + PATH_ABEMPTY, + PATH_ABSOLUTE, + PATH_NOSCHEME, + PATH_EMPTY, +) + +# See http://tools.ietf.org/html/rfc3986#section-3 for definition +HIER_PART_RE = '(//%s%s|%s|%s|%s)' % ( + COMPONENT_PATTERN_DICT['authority'], + PATH_ABEMPTY, + PATH_ABSOLUTE, + PATH_ROOTLESS, + PATH_EMPTY, +) + +# ############### +# IRIs / RFC 3987 +# ############### + +# Only wide-unicode gets the high-ranges of UCSCHAR +if sys.maxunicode > 0xFFFF: # pragma: no cover + IPRIVATE = u'\uE000-\uF8FF\U000F0000-\U000FFFFD\U00100000-\U0010FFFD' + UCSCHAR_RE = ( + u'\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF' + u'\U00010000-\U0001FFFD\U00020000-\U0002FFFD' + u'\U00030000-\U0003FFFD\U00040000-\U0004FFFD' + u'\U00050000-\U0005FFFD\U00060000-\U0006FFFD' + u'\U00070000-\U0007FFFD\U00080000-\U0008FFFD' + u'\U00090000-\U0009FFFD\U000A0000-\U000AFFFD' + u'\U000B0000-\U000BFFFD\U000C0000-\U000CFFFD' + u'\U000D0000-\U000DFFFD\U000E1000-\U000EFFFD' + ) +else: # pragma: no cover + IPRIVATE = u'\uE000-\uF8FF' + UCSCHAR_RE = ( + u'\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF' + ) + +IUNRESERVED_RE = u'A-Za-z0-9\\._~\\-' + UCSCHAR_RE +IPCHAR = u'([' + IUNRESERVED_RE + SUB_DELIMITERS_RE + u':@]|%s)' % PCT_ENCODED + +isegments = { + 'isegment': IPCHAR + u'*', + # Non-zero length segment + 'isegment-nz': IPCHAR + u'+', + # Non-zero length segment without ":" + 'isegment-nz-nc': IPCHAR.replace(':', '') + u'+' +} + +IPATH_ROOTLESS = u'%(isegment-nz)s(/%(isegment)s)*' % isegments +IPATH_NOSCHEME = u'%(isegment-nz-nc)s(/%(isegment)s)*' % isegments +IPATH_ABSOLUTE = u'/(?:%s)?' % IPATH_ROOTLESS +IPATH_ABEMPTY = u'(?:/%(isegment)s)*' % isegments +IPATH_RE = u'^(?:%s|%s|%s|%s|%s)$' % ( + IPATH_ABEMPTY, IPATH_ABSOLUTE, IPATH_NOSCHEME, IPATH_ROOTLESS, PATH_EMPTY +) + +IREGULAR_NAME_RE = IREG_NAME = u'(?:{0}|[{1}])*'.format( + u'%[0-9A-Fa-f]{2}', SUB_DELIMITERS_RE + IUNRESERVED_RE +) + +IHOST_RE = IHOST_PATTERN = u'({0}|{1}|{2})'.format( + IREG_NAME, + IPv4_RE, + IP_LITERAL_RE, +) + +IUSERINFO_RE = u'^(?:[' + IUNRESERVED_RE + SUB_DELIMITERS_RE + u':]|%s)+' % ( + PCT_ENCODED +) + +IFRAGMENT_RE = (u'^(?:[/?:@' + IUNRESERVED_RE + SUB_DELIMITERS_RE + + u']|%s)*$' % PCT_ENCODED) +IQUERY_RE = (u'^(?:[/?:@' + IUNRESERVED_RE + SUB_DELIMITERS_RE + + IPRIVATE + u']|%s)*$' % PCT_ENCODED) + +IRELATIVE_PART_RE = u'(//%s%s|%s|%s|%s)' % ( + COMPONENT_PATTERN_DICT['authority'], + IPATH_ABEMPTY, + IPATH_ABSOLUTE, + IPATH_NOSCHEME, + PATH_EMPTY, +) + +IHIER_PART_RE = u'(//%s%s|%s|%s|%s)' % ( + COMPONENT_PATTERN_DICT['authority'], + IPATH_ABEMPTY, + IPATH_ABSOLUTE, + IPATH_ROOTLESS, + PATH_EMPTY, +) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/api.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/api.py new file mode 100644 index 0000000000000000000000000000000000000000..ddc4a1cd283fe019c2e5c75e84a7ce451e1f104d --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/api.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2014 Rackspace +# 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. +""" +Module containing the simple and functional API for rfc3986. + +This module defines functions and provides access to the public attributes +and classes of rfc3986. +""" + +from .iri import IRIReference +from .parseresult import ParseResult +from .uri import URIReference + + +def uri_reference(uri, encoding='utf-8'): + """Parse a URI string into a URIReference. + + This is a convenience function. You could achieve the same end by using + ``URIReference.from_string(uri)``. + + :param str uri: The URI which needs to be parsed into a reference. + :param str encoding: The encoding of the string provided + :returns: A parsed URI + :rtype: :class:`URIReference` + """ + return URIReference.from_string(uri, encoding) + + +def iri_reference(iri, encoding='utf-8'): + """Parse a IRI string into an IRIReference. + + This is a convenience function. You could achieve the same end by using + ``IRIReference.from_string(iri)``. + + :param str iri: The IRI which needs to be parsed into a reference. + :param str encoding: The encoding of the string provided + :returns: A parsed IRI + :rtype: :class:`IRIReference` + """ + return IRIReference.from_string(iri, encoding) + + +def is_valid_uri(uri, encoding='utf-8', **kwargs): + """Determine if the URI given is valid. + + This is a convenience function. You could use either + ``uri_reference(uri).is_valid()`` or + ``URIReference.from_string(uri).is_valid()`` to achieve the same result. + + :param str uri: The URI to be validated. + :param str encoding: The encoding of the string provided + :param bool require_scheme: Set to ``True`` if you wish to require the + presence of the scheme component. + :param bool require_authority: Set to ``True`` if you wish to require the + presence of the authority component. + :param bool require_path: Set to ``True`` if you wish to require the + presence of the path component. + :param bool require_query: Set to ``True`` if you wish to require the + presence of the query component. + :param bool require_fragment: Set to ``True`` if you wish to require the + presence of the fragment component. + :returns: ``True`` if the URI is valid, ``False`` otherwise. + :rtype: bool + """ + return URIReference.from_string(uri, encoding).is_valid(**kwargs) + + +def normalize_uri(uri, encoding='utf-8'): + """Normalize the given URI. + + This is a convenience function. You could use either + ``uri_reference(uri).normalize().unsplit()`` or + ``URIReference.from_string(uri).normalize().unsplit()`` instead. + + :param str uri: The URI to be normalized. + :param str encoding: The encoding of the string provided + :returns: The normalized URI. + :rtype: str + """ + normalized_reference = URIReference.from_string(uri, encoding).normalize() + return normalized_reference.unsplit() + + +def urlparse(uri, encoding='utf-8'): + """Parse a given URI and return a ParseResult. + + This is a partial replacement of the standard library's urlparse function. + + :param str uri: The URI to be parsed. + :param str encoding: The encoding of the string provided. + :returns: A parsed URI + :rtype: :class:`~rfc3986.parseresult.ParseResult` + """ + return ParseResult.from_string(uri, encoding, strict=False) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/builder.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..7934279995c8aa3aae7514399ea3ada2e51edfb1 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/builder.py @@ -0,0 +1,298 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017 Ian Stapleton Cordasco +# 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. +"""Module containing the logic for the URIBuilder object.""" +from . import compat +from . import normalizers +from . import uri + + +class URIBuilder(object): + """Object to aid in building up a URI Reference from parts. + + .. note:: + + This object should be instantiated by the user, but it's recommended + that it is not provided with arguments. Instead, use the available + method to populate the fields. + + """ + + def __init__(self, scheme=None, userinfo=None, host=None, port=None, + path=None, query=None, fragment=None): + """Initialize our URI builder. + + :param str scheme: + (optional) + :param str userinfo: + (optional) + :param str host: + (optional) + :param int port: + (optional) + :param str path: + (optional) + :param str query: + (optional) + :param str fragment: + (optional) + """ + self.scheme = scheme + self.userinfo = userinfo + self.host = host + self.port = port + self.path = path + self.query = query + self.fragment = fragment + + def __repr__(self): + """Provide a convenient view of our builder object.""" + formatstr = ('URIBuilder(scheme={b.scheme}, userinfo={b.userinfo}, ' + 'host={b.host}, port={b.port}, path={b.path}, ' + 'query={b.query}, fragment={b.fragment})') + return formatstr.format(b=self) + + def add_scheme(self, scheme): + """Add a scheme to our builder object. + + After normalizing, this will generate a new URIBuilder instance with + the specified scheme and all other attributes the same. + + .. code-block:: python + + >>> URIBuilder().add_scheme('HTTPS') + URIBuilder(scheme='https', userinfo=None, host=None, port=None, + path=None, query=None, fragment=None) + + """ + scheme = normalizers.normalize_scheme(scheme) + return URIBuilder( + scheme=scheme, + userinfo=self.userinfo, + host=self.host, + port=self.port, + path=self.path, + query=self.query, + fragment=self.fragment, + ) + + def add_credentials(self, username, password): + """Add credentials as the userinfo portion of the URI. + + .. code-block:: python + + >>> URIBuilder().add_credentials('root', 's3crete') + URIBuilder(scheme=None, userinfo='root:s3crete', host=None, + port=None, path=None, query=None, fragment=None) + + >>> URIBuilder().add_credentials('root', None) + URIBuilder(scheme=None, userinfo='root', host=None, + port=None, path=None, query=None, fragment=None) + """ + if username is None: + raise ValueError('Username cannot be None') + userinfo = normalizers.normalize_username(username) + + if password is not None: + userinfo = '{}:{}'.format( + userinfo, + normalizers.normalize_password(password), + ) + + return URIBuilder( + scheme=self.scheme, + userinfo=userinfo, + host=self.host, + port=self.port, + path=self.path, + query=self.query, + fragment=self.fragment, + ) + + def add_host(self, host): + """Add hostname to the URI. + + .. code-block:: python + + >>> URIBuilder().add_host('google.com') + URIBuilder(scheme=None, userinfo=None, host='google.com', + port=None, path=None, query=None, fragment=None) + + """ + return URIBuilder( + scheme=self.scheme, + userinfo=self.userinfo, + host=normalizers.normalize_host(host), + port=self.port, + path=self.path, + query=self.query, + fragment=self.fragment, + ) + + def add_port(self, port): + """Add port to the URI. + + .. code-block:: python + + >>> URIBuilder().add_port(80) + URIBuilder(scheme=None, userinfo=None, host=None, port='80', + path=None, query=None, fragment=None) + + >>> URIBuilder().add_port(443) + URIBuilder(scheme=None, userinfo=None, host=None, port='443', + path=None, query=None, fragment=None) + + """ + port_int = int(port) + if port_int < 0: + raise ValueError( + 'ports are not allowed to be negative. You provided {}'.format( + port_int, + ) + ) + if port_int > 65535: + raise ValueError( + 'ports are not allowed to be larger than 65535. ' + 'You provided {}'.format( + port_int, + ) + ) + + return URIBuilder( + scheme=self.scheme, + userinfo=self.userinfo, + host=self.host, + port='{}'.format(port_int), + path=self.path, + query=self.query, + fragment=self.fragment, + ) + + def add_path(self, path): + """Add a path to the URI. + + .. code-block:: python + + >>> URIBuilder().add_path('sigmavirus24/rfc3985') + URIBuilder(scheme=None, userinfo=None, host=None, port=None, + path='/sigmavirus24/rfc3986', query=None, fragment=None) + + >>> URIBuilder().add_path('/checkout.php') + URIBuilder(scheme=None, userinfo=None, host=None, port=None, + path='/checkout.php', query=None, fragment=None) + + """ + if not path.startswith('/'): + path = '/{}'.format(path) + + return URIBuilder( + scheme=self.scheme, + userinfo=self.userinfo, + host=self.host, + port=self.port, + path=normalizers.normalize_path(path), + query=self.query, + fragment=self.fragment, + ) + + def add_query_from(self, query_items): + """Generate and add a query a dictionary or list of tuples. + + .. code-block:: python + + >>> URIBuilder().add_query_from({'a': 'b c'}) + URIBuilder(scheme=None, userinfo=None, host=None, port=None, + path=None, query='a=b+c', fragment=None) + + >>> URIBuilder().add_query_from([('a', 'b c')]) + URIBuilder(scheme=None, userinfo=None, host=None, port=None, + path=None, query='a=b+c', fragment=None) + + """ + query = normalizers.normalize_query(compat.urlencode(query_items)) + + return URIBuilder( + scheme=self.scheme, + userinfo=self.userinfo, + host=self.host, + port=self.port, + path=self.path, + query=query, + fragment=self.fragment, + ) + + def add_query(self, query): + """Add a pre-formated query string to the URI. + + .. code-block:: python + + >>> URIBuilder().add_query('a=b&c=d') + URIBuilder(scheme=None, userinfo=None, host=None, port=None, + path=None, query='a=b&c=d', fragment=None) + + """ + return URIBuilder( + scheme=self.scheme, + userinfo=self.userinfo, + host=self.host, + port=self.port, + path=self.path, + query=normalizers.normalize_query(query), + fragment=self.fragment, + ) + + def add_fragment(self, fragment): + """Add a fragment to the URI. + + .. code-block:: python + + >>> URIBuilder().add_fragment('section-2.6.1') + URIBuilder(scheme=None, userinfo=None, host=None, port=None, + path=None, query=None, fragment='section-2.6.1') + + """ + return URIBuilder( + scheme=self.scheme, + userinfo=self.userinfo, + host=self.host, + port=self.port, + path=self.path, + query=self.query, + fragment=normalizers.normalize_fragment(fragment), + ) + + def finalize(self): + """Create a URIReference from our builder. + + .. code-block:: python + + >>> URIBuilder().add_scheme('https').add_host('github.com' + ... ).add_path('sigmavirus24/rfc3986').finalize().unsplit() + 'https://github.com/sigmavirus24/rfc3986' + + >>> URIBuilder().add_scheme('https').add_host('github.com' + ... ).add_path('sigmavirus24/rfc3986').add_credentials( + ... 'sigmavirus24', 'not-re@l').finalize().unsplit() + 'https://sigmavirus24:not-re%40l@github.com/sigmavirus24/rfc3986' + + """ + return uri.URIReference( + self.scheme, + normalizers.normalize_authority( + (self.userinfo, self.host, self.port) + ), + self.path, + self.query, + self.fragment, + ) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/compat.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..8968c3843732361f61101be1f7d71020047c44c8 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/compat.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2014 Rackspace +# 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. +"""Compatibility module for Python 2 and 3 support.""" +import sys + +try: + from urllib.parse import quote as urlquote +except ImportError: # Python 2.x + from urllib import quote as urlquote + +try: + from urllib.parse import urlencode +except ImportError: # Python 2.x + from urllib import urlencode + +__all__ = ( + 'to_bytes', + 'to_str', + 'urlquote', + 'urlencode', +) + +PY3 = (3, 0) <= sys.version_info < (4, 0) +PY2 = (2, 6) <= sys.version_info < (2, 8) + + +if PY3: + unicode = str # Python 3.x + + +def to_str(b, encoding='utf-8'): + """Ensure that b is text in the specified encoding.""" + if hasattr(b, 'decode') and not isinstance(b, unicode): + b = b.decode(encoding) + return b + + +def to_bytes(s, encoding='utf-8'): + """Ensure that s is converted to bytes from the encoding.""" + if hasattr(s, 'encode') and not isinstance(s, bytes): + s = s.encode(encoding) + return s diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/exceptions.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..da8ca7cb1f395515fab2ffc3ab28250553d4e361 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/exceptions.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- +"""Exceptions module for rfc3986.""" + +from . import compat + + +class RFC3986Exception(Exception): + """Base class for all rfc3986 exception classes.""" + + pass + + +class InvalidAuthority(RFC3986Exception): + """Exception when the authority string is invalid.""" + + def __init__(self, authority): + """Initialize the exception with the invalid authority.""" + super(InvalidAuthority, self).__init__( + u"The authority ({0}) is not valid.".format( + compat.to_str(authority))) + + +class InvalidPort(RFC3986Exception): + """Exception when the port is invalid.""" + + def __init__(self, port): + """Initialize the exception with the invalid port.""" + super(InvalidPort, self).__init__( + 'The port ("{0}") is not valid.'.format(port)) + + +class ResolutionError(RFC3986Exception): + """Exception to indicate a failure to resolve a URI.""" + + def __init__(self, uri): + """Initialize the error with the failed URI.""" + super(ResolutionError, self).__init__( + "{0} is not an absolute URI.".format(uri.unsplit())) + + +class ValidationError(RFC3986Exception): + """Exception raised during Validation of a URI.""" + + pass + + +class MissingComponentError(ValidationError): + """Exception raised when a required component is missing.""" + + def __init__(self, uri, *component_names): + """Initialize the error with the missing component name.""" + verb = 'was' + if len(component_names) > 1: + verb = 'were' + + self.uri = uri + self.components = sorted(component_names) + components = ', '.join(self.components) + super(MissingComponentError, self).__init__( + "{} {} required but missing".format(components, verb), + uri, + self.components, + ) + + +class UnpermittedComponentError(ValidationError): + """Exception raised when a component has an unpermitted value.""" + + def __init__(self, component_name, component_value, allowed_values): + """Initialize the error with the unpermitted component.""" + super(UnpermittedComponentError, self).__init__( + "{} was required to be one of {!r} but was {!r}".format( + component_name, list(sorted(allowed_values)), component_value, + ), + component_name, + component_value, + allowed_values, + ) + self.component_name = component_name + self.component_value = component_value + self.allowed_values = allowed_values + + +class PasswordForbidden(ValidationError): + """Exception raised when a URL has a password in the userinfo section.""" + + def __init__(self, uri): + """Initialize the error with the URI that failed validation.""" + unsplit = getattr(uri, 'unsplit', lambda: uri) + super(PasswordForbidden, self).__init__( + '"{}" contained a password when validation forbade it'.format( + unsplit() + ) + ) + self.uri = uri + + +class InvalidComponentsError(ValidationError): + """Exception raised when one or more components are invalid.""" + + def __init__(self, uri, *component_names): + """Initialize the error with the invalid component name(s).""" + verb = 'was' + if len(component_names) > 1: + verb = 'were' + + self.uri = uri + self.components = sorted(component_names) + components = ', '.join(self.components) + super(InvalidComponentsError, self).__init__( + "{} {} found to be invalid".format(components, verb), + uri, + self.components, + ) + + +class MissingDependencyError(RFC3986Exception): + """Exception raised when an IRI is encoded without the 'idna' module.""" diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/iri.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/iri.py new file mode 100644 index 0000000000000000000000000000000000000000..9c01fe1cd041996d36cef0171cea5a5901f3f2cb --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/iri.py @@ -0,0 +1,147 @@ +"""Module containing the implementation of the IRIReference class.""" +# -*- coding: utf-8 -*- +# Copyright (c) 2014 Rackspace +# Copyright (c) 2015 Ian Stapleton Cordasco +# 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. +from collections import namedtuple + +from . import compat +from . import exceptions +from . import misc +from . import normalizers +from . import uri + + +try: + import idna +except ImportError: # pragma: no cover + idna = None + + +class IRIReference(namedtuple('IRIReference', misc.URI_COMPONENTS), + uri.URIMixin): + """Immutable object representing a parsed IRI Reference. + + Can be encoded into an URIReference object via the procedure + specified in RFC 3987 Section 3.1 + + .. note:: + The IRI submodule is a new interface and may possibly change in + the future. Check for changes to the interface when upgrading. + """ + + slots = () + + def __new__(cls, scheme, authority, path, query, fragment, + encoding='utf-8'): + """Create a new IRIReference.""" + ref = super(IRIReference, cls).__new__( + cls, + scheme or None, + authority or None, + path or None, + query, + fragment) + ref.encoding = encoding + return ref + + def __eq__(self, other): + """Compare this reference to another.""" + other_ref = other + if isinstance(other, tuple): + other_ref = self.__class__(*other) + elif not isinstance(other, IRIReference): + try: + other_ref = self.__class__.from_string(other) + except TypeError: + raise TypeError( + 'Unable to compare {0}() to {1}()'.format( + type(self).__name__, type(other).__name__)) + + # See http://tools.ietf.org/html/rfc3986#section-6.2 + return tuple(self) == tuple(other_ref) + + def _match_subauthority(self): + return misc.ISUBAUTHORITY_MATCHER.match(self.authority) + + @classmethod + def from_string(cls, iri_string, encoding='utf-8'): + """Parse a IRI reference from the given unicode IRI string. + + :param str iri_string: Unicode IRI to be parsed into a reference. + :param str encoding: The encoding of the string provided + :returns: :class:`IRIReference` or subclass thereof + """ + iri_string = compat.to_str(iri_string, encoding) + + split_iri = misc.IRI_MATCHER.match(iri_string).groupdict() + return cls( + split_iri['scheme'], split_iri['authority'], + normalizers.encode_component(split_iri['path'], encoding), + normalizers.encode_component(split_iri['query'], encoding), + normalizers.encode_component(split_iri['fragment'], encoding), + encoding, + ) + + def encode(self, idna_encoder=None): # noqa: C901 + """Encode an IRIReference into a URIReference instance. + + If the ``idna`` module is installed or the ``rfc3986[idna]`` + extra is used then unicode characters in the IRI host + component will be encoded with IDNA2008. + + :param idna_encoder: + Function that encodes each part of the host component + If not given will raise an exception if the IRI + contains a host component. + :rtype: uri.URIReference + :returns: A URI reference + """ + authority = self.authority + if authority: + if idna_encoder is None: + if idna is None: # pragma: no cover + raise exceptions.MissingDependencyError( + "Could not import the 'idna' module " + "and the IRI hostname requires encoding" + ) + + def idna_encoder(name): + if any(ord(c) > 128 for c in name): + try: + return idna.encode(name.lower(), + strict=True, + std3_rules=True) + except idna.IDNAError: + raise exceptions.InvalidAuthority(self.authority) + return name + + authority = "" + if self.host: + authority = ".".join([compat.to_str(idna_encoder(part)) + for part in self.host.split(".")]) + + if self.userinfo is not None: + authority = (normalizers.encode_component( + self.userinfo, self.encoding) + '@' + authority) + + if self.port is not None: + authority += ":" + str(self.port) + + return uri.URIReference(self.scheme, + authority, + path=self.path, + query=self.query, + fragment=self.fragment, + encoding=self.encoding) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/misc.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..b735e04402cbf303eea85887635bd458062b0d7b --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/misc.py @@ -0,0 +1,124 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2014 Rackspace +# 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. +""" +Module containing compiled regular expressions and constants. + +This module contains important constants, patterns, and compiled regular +expressions for parsing and validating URIs and their components. +""" + +import re + +from . import abnf_regexp + +# These are enumerated for the named tuple used as a superclass of +# URIReference +URI_COMPONENTS = ['scheme', 'authority', 'path', 'query', 'fragment'] + +important_characters = { + 'generic_delimiters': abnf_regexp.GENERIC_DELIMITERS, + 'sub_delimiters': abnf_regexp.SUB_DELIMITERS, + # We need to escape the '*' in this case + 're_sub_delimiters': abnf_regexp.SUB_DELIMITERS_RE, + 'unreserved_chars': abnf_regexp.UNRESERVED_CHARS, + # We need to escape the '-' in this case: + 're_unreserved': abnf_regexp.UNRESERVED_RE, +} + +# For details about delimiters and reserved characters, see: +# http://tools.ietf.org/html/rfc3986#section-2.2 +GENERIC_DELIMITERS = abnf_regexp.GENERIC_DELIMITERS_SET +SUB_DELIMITERS = abnf_regexp.SUB_DELIMITERS_SET +RESERVED_CHARS = abnf_regexp.RESERVED_CHARS_SET +# For details about unreserved characters, see: +# http://tools.ietf.org/html/rfc3986#section-2.3 +UNRESERVED_CHARS = abnf_regexp.UNRESERVED_CHARS_SET +NON_PCT_ENCODED = abnf_regexp.NON_PCT_ENCODED_SET + +URI_MATCHER = re.compile(abnf_regexp.URL_PARSING_RE) + +SUBAUTHORITY_MATCHER = re.compile(( + '^(?:(?P{0})@)?' # userinfo + '(?P{1})' # host + ':?(?P{2})?$' # port + ).format(abnf_regexp.USERINFO_RE, + abnf_regexp.HOST_PATTERN, + abnf_regexp.PORT_RE)) + + +HOST_MATCHER = re.compile('^' + abnf_regexp.HOST_RE + '$') +IPv4_MATCHER = re.compile('^' + abnf_regexp.IPv4_RE + '$') +IPv6_MATCHER = re.compile(r'^\[' + abnf_regexp.IPv6_ADDRZ_RFC4007_RE + r'\]$') + +# Used by host validator +IPv6_NO_RFC4007_MATCHER = re.compile(r'^\[%s\]$' % ( + abnf_regexp.IPv6_ADDRZ_RE +)) + +# Matcher used to validate path components +PATH_MATCHER = re.compile(abnf_regexp.PATH_RE) + + +# ################################## +# Query and Fragment Matcher Section +# ################################## + +QUERY_MATCHER = re.compile(abnf_regexp.QUERY_RE) + +FRAGMENT_MATCHER = QUERY_MATCHER + +# Scheme validation, see: http://tools.ietf.org/html/rfc3986#section-3.1 +SCHEME_MATCHER = re.compile('^{0}$'.format(abnf_regexp.SCHEME_RE)) + +RELATIVE_REF_MATCHER = re.compile(r'^%s(\?%s)?(#%s)?$' % ( + abnf_regexp.RELATIVE_PART_RE, + abnf_regexp.QUERY_RE, + abnf_regexp.FRAGMENT_RE, +)) + +# See http://tools.ietf.org/html/rfc3986#section-4.3 +ABSOLUTE_URI_MATCHER = re.compile(r'^%s:%s(\?%s)?$' % ( + abnf_regexp.COMPONENT_PATTERN_DICT['scheme'], + abnf_regexp.HIER_PART_RE, + abnf_regexp.QUERY_RE[1:-1], +)) + +# ############### +# IRIs / RFC 3987 +# ############### + +IRI_MATCHER = re.compile(abnf_regexp.URL_PARSING_RE, re.UNICODE) + +ISUBAUTHORITY_MATCHER = re.compile(( + u'^(?:(?P{0})@)?' # iuserinfo + u'(?P{1})' # ihost + u':?(?P{2})?$' # port + ).format(abnf_regexp.IUSERINFO_RE, + abnf_regexp.IHOST_RE, + abnf_regexp.PORT_RE), re.UNICODE) + + +# Path merger as defined in http://tools.ietf.org/html/rfc3986#section-5.2.3 +def merge_paths(base_uri, relative_path): + """Merge a base URI's path with a relative URI's path.""" + if base_uri.path is None and base_uri.authority is not None: + return '/' + relative_path + else: + path = base_uri.path or '' + index = path.rfind('/') + return path[:index] + '/' + relative_path + + +UseExisting = object() diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/normalizers.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/normalizers.py new file mode 100644 index 0000000000000000000000000000000000000000..2eb1bb36f744527fb7763eda552b9e773df8a47f --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/normalizers.py @@ -0,0 +1,167 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2014 Rackspace +# 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. +"""Module with functions to normalize components.""" +import re + +from . import compat +from . import misc + + +def normalize_scheme(scheme): + """Normalize the scheme component.""" + return scheme.lower() + + +def normalize_authority(authority): + """Normalize an authority tuple to a string.""" + userinfo, host, port = authority + result = '' + if userinfo: + result += normalize_percent_characters(userinfo) + '@' + if host: + result += normalize_host(host) + if port: + result += ':' + port + return result + + +def normalize_username(username): + """Normalize a username to make it safe to include in userinfo.""" + return compat.urlquote(username) + + +def normalize_password(password): + """Normalize a password to make safe for userinfo.""" + return compat.urlquote(password) + + +def normalize_host(host): + """Normalize a host string.""" + if misc.IPv6_MATCHER.match(host): + percent = host.find('%') + if percent != -1: + percent_25 = host.find('%25') + + # Replace RFC 4007 IPv6 Zone ID delimiter '%' with '%25' + # from RFC 6874. If the host is '[%25]' then we + # assume RFC 4007 and normalize to '[%2525]' + if percent_25 == -1 or percent < percent_25 or \ + (percent == percent_25 and percent_25 == len(host) - 4): + host = host.replace('%', '%25', 1) + + # Don't normalize the casing of the Zone ID + return host[:percent].lower() + host[percent:] + + return host.lower() + + +def normalize_path(path): + """Normalize the path string.""" + if not path: + return path + + path = normalize_percent_characters(path) + return remove_dot_segments(path) + + +def normalize_query(query): + """Normalize the query string.""" + if not query: + return query + return normalize_percent_characters(query) + + +def normalize_fragment(fragment): + """Normalize the fragment string.""" + if not fragment: + return fragment + return normalize_percent_characters(fragment) + + +PERCENT_MATCHER = re.compile('%[A-Fa-f0-9]{2}') + + +def normalize_percent_characters(s): + """All percent characters should be upper-cased. + + For example, ``"%3afoo%DF%ab"`` should be turned into ``"%3Afoo%DF%AB"``. + """ + matches = set(PERCENT_MATCHER.findall(s)) + for m in matches: + if not m.isupper(): + s = s.replace(m, m.upper()) + return s + + +def remove_dot_segments(s): + """Remove dot segments from the string. + + See also Section 5.2.4 of :rfc:`3986`. + """ + # See http://tools.ietf.org/html/rfc3986#section-5.2.4 for pseudo-code + segments = s.split('/') # Turn the path into a list of segments + output = [] # Initialize the variable to use to store output + + for segment in segments: + # '.' is the current directory, so ignore it, it is superfluous + if segment == '.': + continue + # Anything other than '..', should be appended to the output + elif segment != '..': + output.append(segment) + # In this case segment == '..', if we can, we should pop the last + # element + elif output: + output.pop() + + # If the path starts with '/' and the output is empty or the first string + # is non-empty + if s.startswith('/') and (not output or output[0]): + output.insert(0, '') + + # If the path starts with '/.' or '/..' ensure we add one more empty + # string to add a trailing '/' + if s.endswith(('/.', '/..')): + output.append('') + + return '/'.join(output) + + +def encode_component(uri_component, encoding): + """Encode the specific component in the provided encoding.""" + if uri_component is None: + return uri_component + + # Try to see if the component we're encoding is already percent-encoded + # so we can skip all '%' characters but still encode all others. + percent_encodings = len(PERCENT_MATCHER.findall( + compat.to_str(uri_component, encoding))) + + uri_bytes = compat.to_bytes(uri_component, encoding) + is_percent_encoded = percent_encodings == uri_bytes.count(b'%') + + encoded_uri = bytearray() + + for i in range(0, len(uri_bytes)): + # Will return a single character bytestring on both Python 2 & 3 + byte = uri_bytes[i:i+1] + byte_ord = ord(byte) + if ((is_percent_encoded and byte == b'%') + or (byte_ord < 128 and byte.decode() in misc.NON_PCT_ENCODED)): + encoded_uri.extend(byte) + continue + encoded_uri.extend('%{0:02x}'.format(byte_ord).encode().upper()) + + return encoded_uri.decode(encoding) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/parseresult.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/parseresult.py new file mode 100644 index 0000000000000000000000000000000000000000..0a7345669397b9d3d298812d8e3febc454506cac --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/parseresult.py @@ -0,0 +1,385 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015 Ian Stapleton Cordasco +# 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. +"""Module containing the urlparse compatibility logic.""" +from collections import namedtuple + +from . import compat +from . import exceptions +from . import misc +from . import normalizers +from . import uri + +__all__ = ('ParseResult', 'ParseResultBytes') + +PARSED_COMPONENTS = ('scheme', 'userinfo', 'host', 'port', 'path', 'query', + 'fragment') + + +class ParseResultMixin(object): + def _generate_authority(self, attributes): + # I swear I did not align the comparisons below. That's just how they + # happened to align based on pep8 and attribute lengths. + userinfo, host, port = (attributes[p] + for p in ('userinfo', 'host', 'port')) + if (self.userinfo != userinfo or + self.host != host or + self.port != port): + if port: + port = '{0}'.format(port) + return normalizers.normalize_authority( + (compat.to_str(userinfo, self.encoding), + compat.to_str(host, self.encoding), + port) + ) + return self.authority + + def geturl(self): + """Shim to match the standard library method.""" + return self.unsplit() + + @property + def hostname(self): + """Shim to match the standard library.""" + return self.host + + @property + def netloc(self): + """Shim to match the standard library.""" + return self.authority + + @property + def params(self): + """Shim to match the standard library.""" + return self.query + + +class ParseResult(namedtuple('ParseResult', PARSED_COMPONENTS), + ParseResultMixin): + """Implementation of urlparse compatibility class. + + This uses the URIReference logic to handle compatibility with the + urlparse.ParseResult class. + """ + + slots = () + + def __new__(cls, scheme, userinfo, host, port, path, query, fragment, + uri_ref, encoding='utf-8'): + """Create a new ParseResult.""" + parse_result = super(ParseResult, cls).__new__( + cls, + scheme or None, + userinfo or None, + host, + port or None, + path or None, + query, + fragment) + parse_result.encoding = encoding + parse_result.reference = uri_ref + return parse_result + + @classmethod + def from_parts(cls, scheme=None, userinfo=None, host=None, port=None, + path=None, query=None, fragment=None, encoding='utf-8'): + """Create a ParseResult instance from its parts.""" + authority = '' + if userinfo is not None: + authority += userinfo + '@' + if host is not None: + authority += host + if port is not None: + authority += ':{0}'.format(port) + uri_ref = uri.URIReference(scheme=scheme, + authority=authority, + path=path, + query=query, + fragment=fragment, + encoding=encoding).normalize() + userinfo, host, port = authority_from(uri_ref, strict=True) + return cls(scheme=uri_ref.scheme, + userinfo=userinfo, + host=host, + port=port, + path=uri_ref.path, + query=uri_ref.query, + fragment=uri_ref.fragment, + uri_ref=uri_ref, + encoding=encoding) + + @classmethod + def from_string(cls, uri_string, encoding='utf-8', strict=True, + lazy_normalize=True): + """Parse a URI from the given unicode URI string. + + :param str uri_string: Unicode URI to be parsed into a reference. + :param str encoding: The encoding of the string provided + :param bool strict: Parse strictly according to :rfc:`3986` if True. + If False, parse similarly to the standard library's urlparse + function. + :returns: :class:`ParseResult` or subclass thereof + """ + reference = uri.URIReference.from_string(uri_string, encoding) + if not lazy_normalize: + reference = reference.normalize() + userinfo, host, port = authority_from(reference, strict) + + return cls(scheme=reference.scheme, + userinfo=userinfo, + host=host, + port=port, + path=reference.path, + query=reference.query, + fragment=reference.fragment, + uri_ref=reference, + encoding=encoding) + + @property + def authority(self): + """Return the normalized authority.""" + return self.reference.authority + + def copy_with(self, scheme=misc.UseExisting, userinfo=misc.UseExisting, + host=misc.UseExisting, port=misc.UseExisting, + path=misc.UseExisting, query=misc.UseExisting, + fragment=misc.UseExisting): + """Create a copy of this instance replacing with specified parts.""" + attributes = zip(PARSED_COMPONENTS, + (scheme, userinfo, host, port, path, query, fragment)) + attrs_dict = {} + for name, value in attributes: + if value is misc.UseExisting: + value = getattr(self, name) + attrs_dict[name] = value + authority = self._generate_authority(attrs_dict) + ref = self.reference.copy_with(scheme=attrs_dict['scheme'], + authority=authority, + path=attrs_dict['path'], + query=attrs_dict['query'], + fragment=attrs_dict['fragment']) + return ParseResult(uri_ref=ref, encoding=self.encoding, **attrs_dict) + + def encode(self, encoding=None): + """Convert to an instance of ParseResultBytes.""" + encoding = encoding or self.encoding + attrs = dict( + zip(PARSED_COMPONENTS, + (attr.encode(encoding) if hasattr(attr, 'encode') else attr + for attr in self))) + return ParseResultBytes( + uri_ref=self.reference, + encoding=encoding, + **attrs + ) + + def unsplit(self, use_idna=False): + """Create a URI string from the components. + + :returns: The parsed URI reconstituted as a string. + :rtype: str + """ + parse_result = self + if use_idna and self.host: + hostbytes = self.host.encode('idna') + host = hostbytes.decode(self.encoding) + parse_result = self.copy_with(host=host) + return parse_result.reference.unsplit() + + +class ParseResultBytes(namedtuple('ParseResultBytes', PARSED_COMPONENTS), + ParseResultMixin): + """Compatibility shim for the urlparse.ParseResultBytes object.""" + + def __new__(cls, scheme, userinfo, host, port, path, query, fragment, + uri_ref, encoding='utf-8', lazy_normalize=True): + """Create a new ParseResultBytes instance.""" + parse_result = super(ParseResultBytes, cls).__new__( + cls, + scheme or None, + userinfo or None, + host, + port or None, + path or None, + query or None, + fragment or None) + parse_result.encoding = encoding + parse_result.reference = uri_ref + parse_result.lazy_normalize = lazy_normalize + return parse_result + + @classmethod + def from_parts(cls, scheme=None, userinfo=None, host=None, port=None, + path=None, query=None, fragment=None, encoding='utf-8', + lazy_normalize=True): + """Create a ParseResult instance from its parts.""" + authority = '' + if userinfo is not None: + authority += userinfo + '@' + if host is not None: + authority += host + if port is not None: + authority += ':{0}'.format(int(port)) + uri_ref = uri.URIReference(scheme=scheme, + authority=authority, + path=path, + query=query, + fragment=fragment, + encoding=encoding) + if not lazy_normalize: + uri_ref = uri_ref.normalize() + to_bytes = compat.to_bytes + userinfo, host, port = authority_from(uri_ref, strict=True) + return cls(scheme=to_bytes(scheme, encoding), + userinfo=to_bytes(userinfo, encoding), + host=to_bytes(host, encoding), + port=port, + path=to_bytes(path, encoding), + query=to_bytes(query, encoding), + fragment=to_bytes(fragment, encoding), + uri_ref=uri_ref, + encoding=encoding, + lazy_normalize=lazy_normalize) + + @classmethod + def from_string(cls, uri_string, encoding='utf-8', strict=True, + lazy_normalize=True): + """Parse a URI from the given unicode URI string. + + :param str uri_string: Unicode URI to be parsed into a reference. + :param str encoding: The encoding of the string provided + :param bool strict: Parse strictly according to :rfc:`3986` if True. + If False, parse similarly to the standard library's urlparse + function. + :returns: :class:`ParseResultBytes` or subclass thereof + """ + reference = uri.URIReference.from_string(uri_string, encoding) + if not lazy_normalize: + reference = reference.normalize() + userinfo, host, port = authority_from(reference, strict) + + to_bytes = compat.to_bytes + return cls(scheme=to_bytes(reference.scheme, encoding), + userinfo=to_bytes(userinfo, encoding), + host=to_bytes(host, encoding), + port=port, + path=to_bytes(reference.path, encoding), + query=to_bytes(reference.query, encoding), + fragment=to_bytes(reference.fragment, encoding), + uri_ref=reference, + encoding=encoding, + lazy_normalize=lazy_normalize) + + @property + def authority(self): + """Return the normalized authority.""" + return self.reference.authority.encode(self.encoding) + + def copy_with(self, scheme=misc.UseExisting, userinfo=misc.UseExisting, + host=misc.UseExisting, port=misc.UseExisting, + path=misc.UseExisting, query=misc.UseExisting, + fragment=misc.UseExisting, lazy_normalize=True): + """Create a copy of this instance replacing with specified parts.""" + attributes = zip(PARSED_COMPONENTS, + (scheme, userinfo, host, port, path, query, fragment)) + attrs_dict = {} + for name, value in attributes: + if value is misc.UseExisting: + value = getattr(self, name) + if not isinstance(value, bytes) and hasattr(value, 'encode'): + value = value.encode(self.encoding) + attrs_dict[name] = value + authority = self._generate_authority(attrs_dict) + to_str = compat.to_str + ref = self.reference.copy_with( + scheme=to_str(attrs_dict['scheme'], self.encoding), + authority=to_str(authority, self.encoding), + path=to_str(attrs_dict['path'], self.encoding), + query=to_str(attrs_dict['query'], self.encoding), + fragment=to_str(attrs_dict['fragment'], self.encoding) + ) + if not lazy_normalize: + ref = ref.normalize() + return ParseResultBytes( + uri_ref=ref, + encoding=self.encoding, + lazy_normalize=lazy_normalize, + **attrs_dict + ) + + def unsplit(self, use_idna=False): + """Create a URI bytes object from the components. + + :returns: The parsed URI reconstituted as a string. + :rtype: bytes + """ + parse_result = self + if use_idna and self.host: + # self.host is bytes, to encode to idna, we need to decode it + # first + host = self.host.decode(self.encoding) + hostbytes = host.encode('idna') + parse_result = self.copy_with(host=hostbytes) + if self.lazy_normalize: + parse_result = parse_result.copy_with(lazy_normalize=False) + uri = parse_result.reference.unsplit() + return uri.encode(self.encoding) + + +def split_authority(authority): + # Initialize our expected return values + userinfo = host = port = None + # Initialize an extra var we may need to use + extra_host = None + # Set-up rest in case there is no userinfo portion + rest = authority + + if '@' in authority: + userinfo, rest = authority.rsplit('@', 1) + + # Handle IPv6 host addresses + if rest.startswith('['): + host, rest = rest.split(']', 1) + host += ']' + + if ':' in rest: + extra_host, port = rest.split(':', 1) + elif not host and rest: + host = rest + + if extra_host and not host: + host = extra_host + + return userinfo, host, port + + +def authority_from(reference, strict): + try: + subauthority = reference.authority_info() + except exceptions.InvalidAuthority: + if strict: + raise + userinfo, host, port = split_authority(reference.authority) + else: + # Thanks to Richard Barrell for this idea: + # https://twitter.com/0x2ba22e11/status/617338811975139328 + userinfo, host, port = (subauthority.get(p) + for p in ('userinfo', 'host', 'port')) + + if port: + try: + port = int(port) + except ValueError: + raise exceptions.InvalidPort(port) + return userinfo, host, port diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/uri.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/uri.py new file mode 100644 index 0000000000000000000000000000000000000000..d1d71505e2a8b39567d420a3ce1bdbe45cf2bd36 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/uri.py @@ -0,0 +1,153 @@ +"""Module containing the implementation of the URIReference class.""" +# -*- coding: utf-8 -*- +# Copyright (c) 2014 Rackspace +# Copyright (c) 2015 Ian Stapleton Cordasco +# 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. +from collections import namedtuple + +from . import compat +from . import misc +from . import normalizers +from ._mixin import URIMixin + + +class URIReference(namedtuple('URIReference', misc.URI_COMPONENTS), URIMixin): + """Immutable object representing a parsed URI Reference. + + .. note:: + + This class is not intended to be directly instantiated by the user. + + This object exposes attributes for the following components of a + URI: + + - scheme + - authority + - path + - query + - fragment + + .. attribute:: scheme + + The scheme that was parsed for the URI Reference. For example, + ``http``, ``https``, ``smtp``, ``imap``, etc. + + .. attribute:: authority + + Component of the URI that contains the user information, host, + and port sub-components. For example, + ``google.com``, ``127.0.0.1:5000``, ``username@[::1]``, + ``username:password@example.com:443``, etc. + + .. attribute:: path + + The path that was parsed for the given URI Reference. For example, + ``/``, ``/index.php``, etc. + + .. attribute:: query + + The query component for a given URI Reference. For example, ``a=b``, + ``a=b%20c``, ``a=b+c``, ``a=b,c=d,e=%20f``, etc. + + .. attribute:: fragment + + The fragment component of a URI. For example, ``section-3.1``. + + This class also provides extra attributes for easier access to information + like the subcomponents of the authority component. + + .. attribute:: userinfo + + The user information parsed from the authority. + + .. attribute:: host + + The hostname, IPv4, or IPv6 adddres parsed from the authority. + + .. attribute:: port + + The port parsed from the authority. + """ + + slots = () + + def __new__(cls, scheme, authority, path, query, fragment, + encoding='utf-8'): + """Create a new URIReference.""" + ref = super(URIReference, cls).__new__( + cls, + scheme or None, + authority or None, + path or None, + query, + fragment) + ref.encoding = encoding + return ref + + __hash__ = tuple.__hash__ + + def __eq__(self, other): + """Compare this reference to another.""" + other_ref = other + if isinstance(other, tuple): + other_ref = URIReference(*other) + elif not isinstance(other, URIReference): + try: + other_ref = URIReference.from_string(other) + except TypeError: + raise TypeError( + 'Unable to compare URIReference() to {0}()'.format( + type(other).__name__)) + + # See http://tools.ietf.org/html/rfc3986#section-6.2 + naive_equality = tuple(self) == tuple(other_ref) + return naive_equality or self.normalized_equality(other_ref) + + def normalize(self): + """Normalize this reference as described in Section 6.2.2. + + This is not an in-place normalization. Instead this creates a new + URIReference. + + :returns: A new reference object with normalized components. + :rtype: URIReference + """ + # See http://tools.ietf.org/html/rfc3986#section-6.2.2 for logic in + # this method. + return URIReference(normalizers.normalize_scheme(self.scheme or ''), + normalizers.normalize_authority( + (self.userinfo, self.host, self.port)), + normalizers.normalize_path(self.path or ''), + normalizers.normalize_query(self.query), + normalizers.normalize_fragment(self.fragment), + self.encoding) + + @classmethod + def from_string(cls, uri_string, encoding='utf-8'): + """Parse a URI reference from the given unicode URI string. + + :param str uri_string: Unicode URI to be parsed into a reference. + :param str encoding: The encoding of the string provided + :returns: :class:`URIReference` or subclass thereof + """ + uri_string = compat.to_str(uri_string, encoding) + + split_uri = misc.URI_MATCHER.match(uri_string).groupdict() + return cls( + split_uri['scheme'], split_uri['authority'], + normalizers.encode_component(split_uri['path'], encoding), + normalizers.encode_component(split_uri['query'], encoding), + normalizers.encode_component(split_uri['fragment'], encoding), + encoding, + ) diff --git a/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/validators.py b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..7fc97215b1f3ec5b7d689848eee044f2d3d7dc02 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/urllib3/packages/rfc3986/validators.py @@ -0,0 +1,450 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017 Ian Stapleton Cordasco +# 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. +"""Module containing the validation logic for rfc3986.""" +from . import exceptions +from . import misc +from . import normalizers + + +class Validator(object): + """Object used to configure validation of all objects in rfc3986. + + .. versionadded:: 1.0 + + Example usage:: + + >>> from rfc3986 import api, validators + >>> uri = api.uri_reference('https://github.com/') + >>> validator = validators.Validator().require_presence_of( + ... 'scheme', 'host', 'path', + ... ).allow_schemes( + ... 'http', 'https', + ... ).allow_hosts( + ... '127.0.0.1', 'github.com', + ... ) + >>> validator.validate(uri) + >>> invalid_uri = rfc3986.uri_reference('imap://mail.google.com') + >>> validator.validate(invalid_uri) + Traceback (most recent call last): + ... + rfc3986.exceptions.MissingComponentError: ('path was required but + missing', URIReference(scheme=u'imap', authority=u'mail.google.com', + path=None, query=None, fragment=None), ['path']) + + """ + + COMPONENT_NAMES = frozenset([ + 'scheme', + 'userinfo', + 'host', + 'port', + 'path', + 'query', + 'fragment', + ]) + + def __init__(self): + """Initialize our default validations.""" + self.allowed_schemes = set() + self.allowed_hosts = set() + self.allowed_ports = set() + self.allow_password = True + self.required_components = { + 'scheme': False, + 'userinfo': False, + 'host': False, + 'port': False, + 'path': False, + 'query': False, + 'fragment': False, + } + self.validated_components = self.required_components.copy() + + def allow_schemes(self, *schemes): + """Require the scheme to be one of the provided schemes. + + .. versionadded:: 1.0 + + :param schemes: + Schemes, without ``://`` that are allowed. + :returns: + The validator instance. + :rtype: + Validator + """ + for scheme in schemes: + self.allowed_schemes.add(normalizers.normalize_scheme(scheme)) + return self + + def allow_hosts(self, *hosts): + """Require the host to be one of the provided hosts. + + .. versionadded:: 1.0 + + :param hosts: + Hosts that are allowed. + :returns: + The validator instance. + :rtype: + Validator + """ + for host in hosts: + self.allowed_hosts.add(normalizers.normalize_host(host)) + return self + + def allow_ports(self, *ports): + """Require the port to be one of the provided ports. + + .. versionadded:: 1.0 + + :param ports: + Ports that are allowed. + :returns: + The validator instance. + :rtype: + Validator + """ + for port in ports: + port_int = int(port, base=10) + if 0 <= port_int <= 65535: + self.allowed_ports.add(port) + return self + + def allow_use_of_password(self): + """Allow passwords to be present in the URI. + + .. versionadded:: 1.0 + + :returns: + The validator instance. + :rtype: + Validator + """ + self.allow_password = True + return self + + def forbid_use_of_password(self): + """Prevent passwords from being included in the URI. + + .. versionadded:: 1.0 + + :returns: + The validator instance. + :rtype: + Validator + """ + self.allow_password = False + return self + + def check_validity_of(self, *components): + """Check the validity of the components provided. + + This can be specified repeatedly. + + .. versionadded:: 1.1 + + :param components: + Names of components from :attr:`Validator.COMPONENT_NAMES`. + :returns: + The validator instance. + :rtype: + Validator + """ + components = [c.lower() for c in components] + for component in components: + if component not in self.COMPONENT_NAMES: + raise ValueError( + '"{}" is not a valid component'.format(component) + ) + self.validated_components.update({ + component: True for component in components + }) + return self + + def require_presence_of(self, *components): + """Require the components provided. + + This can be specified repeatedly. + + .. versionadded:: 1.0 + + :param components: + Names of components from :attr:`Validator.COMPONENT_NAMES`. + :returns: + The validator instance. + :rtype: + Validator + """ + components = [c.lower() for c in components] + for component in components: + if component not in self.COMPONENT_NAMES: + raise ValueError( + '"{}" is not a valid component'.format(component) + ) + self.required_components.update({ + component: True for component in components + }) + return self + + def validate(self, uri): + """Check a URI for conditions specified on this validator. + + .. versionadded:: 1.0 + + :param uri: + Parsed URI to validate. + :type uri: + rfc3986.uri.URIReference + :raises MissingComponentError: + When a required component is missing. + :raises UnpermittedComponentError: + When a component is not one of those allowed. + :raises PasswordForbidden: + When a password is present in the userinfo component but is + not permitted by configuration. + :raises InvalidComponentsError: + When a component was found to be invalid. + """ + if not self.allow_password: + check_password(uri) + + required_components = [ + component + for component, required in self.required_components.items() + if required + ] + validated_components = [ + component + for component, required in self.validated_components.items() + if required + ] + if required_components: + ensure_required_components_exist(uri, required_components) + if validated_components: + ensure_components_are_valid(uri, validated_components) + + ensure_one_of(self.allowed_schemes, uri, 'scheme') + ensure_one_of(self.allowed_hosts, uri, 'host') + ensure_one_of(self.allowed_ports, uri, 'port') + + +def check_password(uri): + """Assert that there is no password present in the uri.""" + userinfo = uri.userinfo + if not userinfo: + return + credentials = userinfo.split(':', 1) + if len(credentials) <= 1: + return + raise exceptions.PasswordForbidden(uri) + + +def ensure_one_of(allowed_values, uri, attribute): + """Assert that the uri's attribute is one of the allowed values.""" + value = getattr(uri, attribute) + if value is not None and allowed_values and value not in allowed_values: + raise exceptions.UnpermittedComponentError( + attribute, value, allowed_values, + ) + + +def ensure_required_components_exist(uri, required_components): + """Assert that all required components are present in the URI.""" + missing_components = sorted([ + component + for component in required_components + if getattr(uri, component) is None + ]) + if missing_components: + raise exceptions.MissingComponentError(uri, *missing_components) + + +def is_valid(value, matcher, require): + """Determine if a value is valid based on the provided matcher. + + :param str value: + Value to validate. + :param matcher: + Compiled regular expression to use to validate the value. + :param require: + Whether or not the value is required. + """ + if require: + return (value is not None + and matcher.match(value)) + + # require is False and value is not None + return value is None or matcher.match(value) + + +def authority_is_valid(authority, host=None, require=False): + """Determine if the authority string is valid. + + :param str authority: + The authority to validate. + :param str host: + (optional) The host portion of the authority to validate. + :param bool require: + (optional) Specify if authority must not be None. + :returns: + ``True`` if valid, ``False`` otherwise + :rtype: + bool + """ + validated = is_valid(authority, misc.SUBAUTHORITY_MATCHER, require) + if validated and host is not None: + return host_is_valid(host, require) + return validated + + +def host_is_valid(host, require=False): + """Determine if the host string is valid. + + :param str host: + The host to validate. + :param bool require: + (optional) Specify if host must not be None. + :returns: + ``True`` if valid, ``False`` otherwise + :rtype: + bool + """ + validated = is_valid(host, misc.HOST_MATCHER, require) + if validated and host is not None and misc.IPv4_MATCHER.match(host): + return valid_ipv4_host_address(host) + elif validated and host is not None and misc.IPv6_MATCHER.match(host): + return misc.IPv6_NO_RFC4007_MATCHER.match(host) is not None + return validated + + +def scheme_is_valid(scheme, require=False): + """Determine if the scheme is valid. + + :param str scheme: + The scheme string to validate. + :param bool require: + (optional) Set to ``True`` to require the presence of a scheme. + :returns: + ``True`` if the scheme is valid. ``False`` otherwise. + :rtype: + bool + """ + return is_valid(scheme, misc.SCHEME_MATCHER, require) + + +def path_is_valid(path, require=False): + """Determine if the path component is valid. + + :param str path: + The path string to validate. + :param bool require: + (optional) Set to ``True`` to require the presence of a path. + :returns: + ``True`` if the path is valid. ``False`` otherwise. + :rtype: + bool + """ + return is_valid(path, misc.PATH_MATCHER, require) + + +def query_is_valid(query, require=False): + """Determine if the query component is valid. + + :param str query: + The query string to validate. + :param bool require: + (optional) Set to ``True`` to require the presence of a query. + :returns: + ``True`` if the query is valid. ``False`` otherwise. + :rtype: + bool + """ + return is_valid(query, misc.QUERY_MATCHER, require) + + +def fragment_is_valid(fragment, require=False): + """Determine if the fragment component is valid. + + :param str fragment: + The fragment string to validate. + :param bool require: + (optional) Set to ``True`` to require the presence of a fragment. + :returns: + ``True`` if the fragment is valid. ``False`` otherwise. + :rtype: + bool + """ + return is_valid(fragment, misc.FRAGMENT_MATCHER, require) + + +def valid_ipv4_host_address(host): + """Determine if the given host is a valid IPv4 address.""" + # If the host exists, and it might be IPv4, check each byte in the + # address. + return all([0 <= int(byte, base=10) <= 255 for byte in host.split('.')]) + + +_COMPONENT_VALIDATORS = { + 'scheme': scheme_is_valid, + 'path': path_is_valid, + 'query': query_is_valid, + 'fragment': fragment_is_valid, +} + +_SUBAUTHORITY_VALIDATORS = set(['userinfo', 'host', 'port']) + + +def subauthority_component_is_valid(uri, component): + """Determine if the userinfo, host, and port are valid.""" + try: + subauthority_dict = uri.authority_info() + except exceptions.InvalidAuthority: + return False + + # If we can parse the authority into sub-components and we're not + # validating the port, we can assume it's valid. + if component == 'host': + return host_is_valid(subauthority_dict['host']) + elif component != 'port': + return True + + try: + port = int(subauthority_dict['port']) + except TypeError: + # If the port wasn't provided it'll be None and int(None) raises a + # TypeError + return True + + return (0 <= port <= 65535) + + +def ensure_components_are_valid(uri, validated_components): + """Assert that all components are valid in the URI.""" + invalid_components = set([]) + for component in validated_components: + if component in _SUBAUTHORITY_VALIDATORS: + if not subauthority_component_is_valid(uri, component): + invalid_components.add(component) + # Python's peephole optimizer means that while this continue *is* + # actually executed, coverage.py cannot detect that. See also, + # https://bitbucket.org/ned/coveragepy/issues/198/continue-marked-as-not-covered + continue # nocov: Python 2.7, 3.3, 3.4 + + validator = _COMPONENT_VALIDATORS[component] + if not validator(getattr(uri, component)): + invalid_components.add(component) + + if invalid_components: + raise exceptions.InvalidComponentsError(uri, *invalid_components) diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/55/55d7ecbc2558647e4d07658e9f35084d b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/55/55d7ecbc2558647e4d07658e9f35084d new file mode 100644 index 0000000000000000000000000000000000000000..d7dbf67f405b81ac000fd504fde097ef38c7d8a5 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/55/55d7ecbc2558647e4d07658e9f35084d differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6b/6b06de95736a543690fabad349d028f5 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6b/6b06de95736a543690fabad349d028f5 new file mode 100644 index 0000000000000000000000000000000000000000..3b837d45eaa4f55f3e370a4e72ed7127025f0664 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6b/6b06de95736a543690fabad349d028f5 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6b/6b2d41265dfd0662993ce94e37a50fd2 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6b/6b2d41265dfd0662993ce94e37a50fd2 new file mode 100644 index 0000000000000000000000000000000000000000..9bc7a28683e63e0a5bc5a431efa41ced981969e3 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6b/6b2d41265dfd0662993ce94e37a50fd2 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6b/6b3d8320a5a4938cbf58865346194a31 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6b/6b3d8320a5a4938cbf58865346194a31 new file mode 100644 index 0000000000000000000000000000000000000000..162e7372410317f065ce4c35f1a35140025d2a78 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6b/6b3d8320a5a4938cbf58865346194a31 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6b/6b5121d915772e19a8eb706cbdf646dc b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6b/6b5121d915772e19a8eb706cbdf646dc new file mode 100644 index 0000000000000000000000000000000000000000..09d58464af63e497f9ddc41e89e44d8ae3cf880b Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6b/6b5121d915772e19a8eb706cbdf646dc differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6f/6f27eb51c8f743c58bbcd8fffc49e9fe b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6f/6f27eb51c8f743c58bbcd8fffc49e9fe new file mode 100644 index 0000000000000000000000000000000000000000..07bf817ebf64f442e05ff7686b40be223be71d81 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6f/6f27eb51c8f743c58bbcd8fffc49e9fe differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6f/6f322ff9c99ef52c974b774672397f07 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6f/6f322ff9c99ef52c974b774672397f07 new file mode 100644 index 0000000000000000000000000000000000000000..b3baebec274f9bdff39212a5553c67ee3bc23d3f Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6f/6f322ff9c99ef52c974b774672397f07 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6f/6f34b6fd118e954ad4927be1c72c3a3a b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6f/6f34b6fd118e954ad4927be1c72c3a3a new file mode 100644 index 0000000000000000000000000000000000000000..c2bdc3e77f00495d18a736486663d4f59b12b774 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6f/6f34b6fd118e954ad4927be1c72c3a3a differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6f/6f3912bec2044b5bdb2210fdd8fbf5c0 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6f/6f3912bec2044b5bdb2210fdd8fbf5c0 new file mode 100644 index 0000000000000000000000000000000000000000..a1514ba2abab34e206b01aef4e2fce6935944059 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6f/6f3912bec2044b5bdb2210fdd8fbf5c0 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6f/6f5c8825315c514f14707a91d95ba44d b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6f/6f5c8825315c514f14707a91d95ba44d new file mode 100644 index 0000000000000000000000000000000000000000..9c7667929fd6162d3202d1678f0e54edd7d45dbf Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6f/6f5c8825315c514f14707a91d95ba44d differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6f/6f5fbe6f40987e16cb70ccde7b08e0ac b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6f/6f5fbe6f40987e16cb70ccde7b08e0ac new file mode 100644 index 0000000000000000000000000000000000000000..6f7abc735241bea19e37542e69d5e37918cb8e74 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/6f/6f5fbe6f40987e16cb70ccde7b08e0ac differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/757a804039dbf927ef33a4d18416c1b3 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/757a804039dbf927ef33a4d18416c1b3 new file mode 100644 index 0000000000000000000000000000000000000000..e65d7a450226e93c43f230962a9cd52e32279324 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/757a804039dbf927ef33a4d18416c1b3 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/757b6fad865394b9b6474d7dea7432a3 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/757b6fad865394b9b6474d7dea7432a3 new file mode 100644 index 0000000000000000000000000000000000000000..cc853fde76a6f082b9d0ab7b4125c0cbab021c99 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/757b6fad865394b9b6474d7dea7432a3 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/7599a45f153421e114f2e4d4d1fc15cb b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/7599a45f153421e114f2e4d4d1fc15cb new file mode 100644 index 0000000000000000000000000000000000000000..3a50825ccb0642a14ad07335b1f9b4297e79bfb6 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/7599a45f153421e114f2e4d4d1fc15cb differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/759f22f803c74b4cde9e1bdfa87df5b7 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/759f22f803c74b4cde9e1bdfa87df5b7 new file mode 100644 index 0000000000000000000000000000000000000000..991cbb4e99d4c796ac947decdf19d01f6d51fd7a Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/759f22f803c74b4cde9e1bdfa87df5b7 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/75a44d40697897e7eaa14c61911ff8b5 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/75a44d40697897e7eaa14c61911ff8b5 new file mode 100644 index 0000000000000000000000000000000000000000..c7c5445b9e4575ba70d71ac41cbe197c2d29c715 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/75a44d40697897e7eaa14c61911ff8b5 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/75aa02bc796f13aaf4546cd1431a4f5b b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/75aa02bc796f13aaf4546cd1431a4f5b new file mode 100644 index 0000000000000000000000000000000000000000..7d0ac8fbe916cf10a6dab02765fe14848863f395 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/75aa02bc796f13aaf4546cd1431a4f5b differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/75fd9f487663f73bd9e156e4931eac86 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/75fd9f487663f73bd9e156e4931eac86 new file mode 100644 index 0000000000000000000000000000000000000000..86cc3021d6bda88c7566ba7e9beb2f29b59f446a Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/75/75fd9f487663f73bd9e156e4931eac86 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/76086686adf7f1c528c6920a749a9653 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/76086686adf7f1c528c6920a749a9653 new file mode 100644 index 0000000000000000000000000000000000000000..9102b75e2e7b09bc9a4da11822c11d5e96cb5e12 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/76086686adf7f1c528c6920a749a9653 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/762aecc948daa44b4904a52a492e24f8 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/762aecc948daa44b4904a52a492e24f8 new file mode 100644 index 0000000000000000000000000000000000000000..7cfdcdee6fe3900f0cef14bf52672b37479f1119 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/762aecc948daa44b4904a52a492e24f8 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/764672dfd95379aad6c58646a33e49d7 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/764672dfd95379aad6c58646a33e49d7 new file mode 100644 index 0000000000000000000000000000000000000000..4a2bf66fdf3657cc1e86808408798df395f28122 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/764672dfd95379aad6c58646a33e49d7 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/765510cad9b91f246a51b4b81d69c8e7 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/765510cad9b91f246a51b4b81d69c8e7 new file mode 100644 index 0000000000000000000000000000000000000000..e170f4414656bce1df9e8a5061c2d9526dfc0f83 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/765510cad9b91f246a51b4b81d69c8e7 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/76808de0f85152524b8a56d1447ca141 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/76808de0f85152524b8a56d1447ca141 new file mode 100644 index 0000000000000000000000000000000000000000..71093934d81adff1299e05905982833abc84e4c9 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/76808de0f85152524b8a56d1447ca141 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/768559ec898c21c15ec32f03ab957b73 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/768559ec898c21c15ec32f03ab957b73 new file mode 100644 index 0000000000000000000000000000000000000000..8eb6d1ce788fec03818a34fa0d42cfc059388367 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/768559ec898c21c15ec32f03ab957b73 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/7689603d4c9069d1f80d12cb45012e3e b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/7689603d4c9069d1f80d12cb45012e3e new file mode 100644 index 0000000000000000000000000000000000000000..02feccc76225e5dfe8fae9e93fdb575690f89289 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/7689603d4c9069d1f80d12cb45012e3e differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/76ab3726298b142d318dc0dfa42f5e0a b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/76ab3726298b142d318dc0dfa42f5e0a new file mode 100644 index 0000000000000000000000000000000000000000..42abc6c35b5a4bbdbdabe089779141ff04505202 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/76ab3726298b142d318dc0dfa42f5e0a differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/76c04c34dd6ac035be479e0c2f6fae85 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/76c04c34dd6ac035be479e0c2f6fae85 new file mode 100644 index 0000000000000000000000000000000000000000..987e5f45b79a13e0807aef3af8ba5f395c52ae88 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/76c04c34dd6ac035be479e0c2f6fae85 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/76cb53a68c4ec124f01ea1f4a5fb895f b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/76cb53a68c4ec124f01ea1f4a5fb895f new file mode 100644 index 0000000000000000000000000000000000000000..80a8bc7b22661fc980386b7b58ddc932c3ea2761 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/76cb53a68c4ec124f01ea1f4a5fb895f differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/76cf6da1c358632a422fabbb4d8cbe81 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/76cf6da1c358632a422fabbb4d8cbe81 new file mode 100644 index 0000000000000000000000000000000000000000..7fab1b537b4951ceeba56968fee03d824ee80e89 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/76/76cf6da1c358632a422fabbb4d8cbe81 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/77/771b172b6237c80e48865b77630004a8 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/77/771b172b6237c80e48865b77630004a8 new file mode 100644 index 0000000000000000000000000000000000000000..dbd71f5c76cc1907ec4b47456dbd4edd33759f85 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/77/771b172b6237c80e48865b77630004a8 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/77/772949872d4e6179b9b4d73f81c72c96 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/77/772949872d4e6179b9b4d73f81c72c96 new file mode 100644 index 0000000000000000000000000000000000000000..73989040edcbd9815bd021b219c7b8519038d7ad Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/77/772949872d4e6179b9b4d73f81c72c96 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/77/7735f7e7cbe14d3d895c493542642274 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/77/7735f7e7cbe14d3d895c493542642274 new file mode 100644 index 0000000000000000000000000000000000000000..63e68d2fc9c61810dc9e89eeac378eec88f9e38b Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/77/7735f7e7cbe14d3d895c493542642274 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/79/79db6be6f662a88b9fac93a8fa893ab6 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/79/79db6be6f662a88b9fac93a8fa893ab6 new file mode 100644 index 0000000000000000000000000000000000000000..4baab81b5859e1a054519e540c59731e2ecbf51c Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/79/79db6be6f662a88b9fac93a8fa893ab6 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7a/7a572adb2a99800e7ef6903c081b93e2 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7a/7a572adb2a99800e7ef6903c081b93e2 new file mode 100644 index 0000000000000000000000000000000000000000..594200496bb9eb3abe1aef7d80137d5b38023ee0 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7a/7a572adb2a99800e7ef6903c081b93e2 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7a/7a9449e0bcfc2d3b4f092be66d739310 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7a/7a9449e0bcfc2d3b4f092be66d739310 new file mode 100644 index 0000000000000000000000000000000000000000..8a6aacdecaed90cde3f12725647b1972faed9058 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7a/7a9449e0bcfc2d3b4f092be66d739310 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7a/7aa4969433dfc3bbd0e917d50f5f80e9 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7a/7aa4969433dfc3bbd0e917d50f5f80e9 new file mode 100644 index 0000000000000000000000000000000000000000..1072bc7cf54e9859f5108f0e553c910f45388c6b Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7a/7aa4969433dfc3bbd0e917d50f5f80e9 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b56af3f5b96802af2a8fa0878e91e42 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b56af3f5b96802af2a8fa0878e91e42 new file mode 100644 index 0000000000000000000000000000000000000000..7d9a64577fd0c2ca134c70d95a1b6675f4cc76d6 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b56af3f5b96802af2a8fa0878e91e42 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b5b320840597f78cbe9d1d4fb04239f b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b5b320840597f78cbe9d1d4fb04239f new file mode 100644 index 0000000000000000000000000000000000000000..88dc4a0945366be013ecabd2a3c00e90fee99b14 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b5b320840597f78cbe9d1d4fb04239f differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b5bc08654edc128c41b81240c7de937 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b5bc08654edc128c41b81240c7de937 new file mode 100644 index 0000000000000000000000000000000000000000..eb22097f89927f195da6062c037da0262c1d2bbb Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b5bc08654edc128c41b81240c7de937 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b5d2786e66b7027533eb5e622a1f20c b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b5d2786e66b7027533eb5e622a1f20c new file mode 100644 index 0000000000000000000000000000000000000000..dc637b4f5aa1b970716f25e946a92a3d9b5e599f Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b5d2786e66b7027533eb5e622a1f20c differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b7a523e47c01a7467460c4b18924440 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b7a523e47c01a7467460c4b18924440 new file mode 100644 index 0000000000000000000000000000000000000000..e11b5f1daf2e382c5ecdefb25947cf11814e9dc3 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b7a523e47c01a7467460c4b18924440 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b7c6ccc590be3b376fd8143a586f3b6 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b7c6ccc590be3b376fd8143a586f3b6 new file mode 100644 index 0000000000000000000000000000000000000000..a4f0b1cc0a491c59b2d2d07bb45ff7acacb80856 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b7c6ccc590be3b376fd8143a586f3b6 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b9187d57355f1ec110d6f979fd723c2 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b9187d57355f1ec110d6f979fd723c2 new file mode 100644 index 0000000000000000000000000000000000000000..4ea273d45a75a4626adbe988b31c40ce64db4181 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7b/7b9187d57355f1ec110d6f979fd723c2 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7e514ae950d23cc672b7981e29a4b3a6 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7e514ae950d23cc672b7981e29a4b3a6 new file mode 100644 index 0000000000000000000000000000000000000000..5a1d4f69f2feb64e36ce367291e3ae7eb9a0a01c Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7e514ae950d23cc672b7981e29a4b3a6 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7e637b81ab1f9d4dcf711aed57e49092 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7e637b81ab1f9d4dcf711aed57e49092 new file mode 100644 index 0000000000000000000000000000000000000000..b8f80c4e95baa4763e9e64dc9f3bb211aed6a59d Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7e637b81ab1f9d4dcf711aed57e49092 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7e76cd4b7459459b807f9b2170868b1a b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7e76cd4b7459459b807f9b2170868b1a new file mode 100644 index 0000000000000000000000000000000000000000..fb66603a1f7ffa7dcd8af056af25d2f6c75b9375 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7e76cd4b7459459b807f9b2170868b1a differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7eabb8ca07182bf7f2328c0db6fcb886 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7eabb8ca07182bf7f2328c0db6fcb886 new file mode 100644 index 0000000000000000000000000000000000000000..db32c81a2365dba99d160afa4c89dbdb55f00b7d Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7eabb8ca07182bf7f2328c0db6fcb886 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7eaf3303b5fb3a31d4aa7451425a2ecb b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7eaf3303b5fb3a31d4aa7451425a2ecb new file mode 100644 index 0000000000000000000000000000000000000000..8e3c632f3eb66633e18a555230f6daf63762e45d Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7eaf3303b5fb3a31d4aa7451425a2ecb differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7eb842463eac5b05ed0172d1de7869ec b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7eb842463eac5b05ed0172d1de7869ec new file mode 100644 index 0000000000000000000000000000000000000000..c8972bbdf0e3be3edef4d7d6d5f5334bb7c76b96 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7eb842463eac5b05ed0172d1de7869ec differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7ed3e9d705ff61a0f11ba9cd7c267bbf b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7ed3e9d705ff61a0f11ba9cd7c267bbf new file mode 100644 index 0000000000000000000000000000000000000000..6e38412c6587229983a8c24b26f138f3ee2b083b Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7e/7ed3e9d705ff61a0f11ba9cd7c267bbf differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f215b09dea9d9be1ca66cef013e8d61 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f215b09dea9d9be1ca66cef013e8d61 new file mode 100644 index 0000000000000000000000000000000000000000..f4500f9ca28b346c83c7883fd637f2c40d0b3e6f Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f215b09dea9d9be1ca66cef013e8d61 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f562b7782e1514c90804f43e715bece b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f562b7782e1514c90804f43e715bece new file mode 100644 index 0000000000000000000000000000000000000000..b4b7485318e72e9a809791ee56f853e8262a524f Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f562b7782e1514c90804f43e715bece differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f6ac16b8089dc4f223701c6cf0c52b1 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f6ac16b8089dc4f223701c6cf0c52b1 new file mode 100644 index 0000000000000000000000000000000000000000..c76286cadcb8b749654d4d5e6b2476a2b7cd60a7 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f6ac16b8089dc4f223701c6cf0c52b1 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f6ec344c43c995df5be87c18ee0b0bf b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f6ec344c43c995df5be87c18ee0b0bf new file mode 100644 index 0000000000000000000000000000000000000000..f7e9120859ec7f667da38c13525235a2d81b735e Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f6ec344c43c995df5be87c18ee0b0bf differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f78d0019426fa64ae70bb9bfdb841de b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f78d0019426fa64ae70bb9bfdb841de new file mode 100644 index 0000000000000000000000000000000000000000..e9ddd9ab3dcc2bc3533305517cdc40d0b8afa634 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f78d0019426fa64ae70bb9bfdb841de differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f8e105a1d78fa4ed520b118e5cc006b b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f8e105a1d78fa4ed520b118e5cc006b new file mode 100644 index 0000000000000000000000000000000000000000..e2cbb7bc8953b001dd7469d210079fc5e682140a Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f8e105a1d78fa4ed520b118e5cc006b differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f9da9ee5577690c0a4e25bccd93b8cb b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f9da9ee5577690c0a4e25bccd93b8cb new file mode 100644 index 0000000000000000000000000000000000000000..021fe0678cf035393bb337a4937559f5335eb154 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7f9da9ee5577690c0a4e25bccd93b8cb differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7fa2b40b79370fa1230bbbb2667fdbaa b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7fa2b40b79370fa1230bbbb2667fdbaa new file mode 100644 index 0000000000000000000000000000000000000000..c39b7173f4b9f588834c68ae7bcc92d47a7b54af Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7fa2b40b79370fa1230bbbb2667fdbaa differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7fa96887b83516d97b2e804193faa402 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7fa96887b83516d97b2e804193faa402 new file mode 100644 index 0000000000000000000000000000000000000000..fedfaeecbbdf6e4832e7901893f6e2aff6ef7d80 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7fa96887b83516d97b2e804193faa402 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7fb5aefb15ca46014abaf6e612046e6a b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7fb5aefb15ca46014abaf6e612046e6a new file mode 100644 index 0000000000000000000000000000000000000000..4b5afb6c70ec795b8edb0c6320fa4c5de1aa7344 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7fb5aefb15ca46014abaf6e612046e6a differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7fc628b703054d52a5daf75394bd7a8f b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7fc628b703054d52a5daf75394bd7a8f new file mode 100644 index 0000000000000000000000000000000000000000..cc0625e3d7e864ab373f55d320edb3ad92d6e0e7 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7fc628b703054d52a5daf75394bd7a8f differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7fcb0f03d6704f25f4debf08f3ebf80c b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7fcb0f03d6704f25f4debf08f3ebf80c new file mode 100644 index 0000000000000000000000000000000000000000..f90942c9e8e74ee9a098c3f2987279a7d26b496d Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7fcb0f03d6704f25f4debf08f3ebf80c differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7fe600b68206c2399f8a199b424ab5b9 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7fe600b68206c2399f8a199b424ab5b9 new file mode 100644 index 0000000000000000000000000000000000000000..aecc04a2f6a25614db2ee3cff5c067a4c17ac475 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/7f/7fe600b68206c2399f8a199b424ab5b9 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/80/804712689991b2ed29d9acf3567bf922 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/80/804712689991b2ed29d9acf3567bf922 new file mode 100644 index 0000000000000000000000000000000000000000..a96b723ecce5e6ddf275785e0bea022503a8ed01 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/80/804712689991b2ed29d9acf3567bf922 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/80/80622a5192579615d83105ba744d4385 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/80/80622a5192579615d83105ba744d4385 new file mode 100644 index 0000000000000000000000000000000000000000..967df80484959ef1d9ab853a0a693b9a3f4d44ef Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/80/80622a5192579615d83105ba744d4385 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/80/808c59169372cff2985e0f725a6f376e b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/80/808c59169372cff2985e0f725a6f376e new file mode 100644 index 0000000000000000000000000000000000000000..9620d17a744110acc9c78ec91acdf9828f81fa7b Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/80/808c59169372cff2985e0f725a6f376e differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/80/80ac49cb93df5506f20ebdb9e9a88e1e b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/80/80ac49cb93df5506f20ebdb9e9a88e1e new file mode 100644 index 0000000000000000000000000000000000000000..b9427ace1d1fa2aa12b6cc733ae4feb56b6b267b Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/80/80ac49cb93df5506f20ebdb9e9a88e1e differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/822af15bd2ff58416f5d993f4e771628 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/822af15bd2ff58416f5d993f4e771628 new file mode 100644 index 0000000000000000000000000000000000000000..696d26a815b1f11f2df2c7366151969e21f8e65a Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/822af15bd2ff58416f5d993f4e771628 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/826170c268672e5cc7b108388b7da03f b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/826170c268672e5cc7b108388b7da03f new file mode 100644 index 0000000000000000000000000000000000000000..83f3ce31482055167e287c0812f90aa42fe7d93b Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/826170c268672e5cc7b108388b7da03f differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/8284388fb0914c755ba583cb26d3980f b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/8284388fb0914c755ba583cb26d3980f new file mode 100644 index 0000000000000000000000000000000000000000..f841facc1424a6d2be4ed4493da96d82273cb72d Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/8284388fb0914c755ba583cb26d3980f differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/82893b7665266690cf37ac7b2c95a815 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/82893b7665266690cf37ac7b2c95a815 new file mode 100644 index 0000000000000000000000000000000000000000..25f76a6c1e61ecc673296b8929527faf6aa44df3 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/82893b7665266690cf37ac7b2c95a815 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/828c05da2986f94dbf0816f159d9b18c b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/828c05da2986f94dbf0816f159d9b18c new file mode 100644 index 0000000000000000000000000000000000000000..c3cf3d50b2e4a92a15c34596628ea11fab761626 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/828c05da2986f94dbf0816f159d9b18c differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/828ceaa86758b63cd4ea396552086e1d b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/828ceaa86758b63cd4ea396552086e1d new file mode 100644 index 0000000000000000000000000000000000000000..3564a2410bde8997567ad3a7b9412988782912b9 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/828ceaa86758b63cd4ea396552086e1d differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/8297df0f88369c794662f9e2e8a44e98 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/8297df0f88369c794662f9e2e8a44e98 new file mode 100644 index 0000000000000000000000000000000000000000..e92319fc73bb60ad91988d0ad5209db9cf714f70 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/8297df0f88369c794662f9e2e8a44e98 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/82c81e2117c31fc44fd2c3261ebe3bd0 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/82c81e2117c31fc44fd2c3261ebe3bd0 new file mode 100644 index 0000000000000000000000000000000000000000..f593e88186cf41254c6b5222a96a122977c32bae Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/82c81e2117c31fc44fd2c3261ebe3bd0 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/82c841e0e71bda2fd21aa7352bcbf040 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/82c841e0e71bda2fd21aa7352bcbf040 new file mode 100644 index 0000000000000000000000000000000000000000..80830da45e7487ee7902cb0679a85886401293b4 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/82c841e0e71bda2fd21aa7352bcbf040 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/82de29d767265d235b3fb5bab3499ac9 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/82de29d767265d235b3fb5bab3499ac9 new file mode 100644 index 0000000000000000000000000000000000000000..7433da21a4b063dd2ad20d3abee926d73af9ddda Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/82de29d767265d235b3fb5bab3499ac9 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/82f29ebd6a2dabd976a558fdf2954fdc b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/82f29ebd6a2dabd976a558fdf2954fdc new file mode 100644 index 0000000000000000000000000000000000000000..a57ccf8fa0bba3af07d77c0cb640360e5aa6ff79 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/82f29ebd6a2dabd976a558fdf2954fdc differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/82f678844b1df5069195e9997410ef50 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/82f678844b1df5069195e9997410ef50 new file mode 100644 index 0000000000000000000000000000000000000000..34613bf7388c243706b3c18957b2c4bcaeaf8c42 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/82/82f678844b1df5069195e9997410ef50 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/83/8396495fe35447e74094f1b5fdbb4294 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/83/8396495fe35447e74094f1b5fdbb4294 new file mode 100644 index 0000000000000000000000000000000000000000..c5b94922aa7cb457ad43941d0c2031774a65f709 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/83/8396495fe35447e74094f1b5fdbb4294 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/83/83a8b0f70cc693fb7dbe9acce6040f48 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/83/83a8b0f70cc693fb7dbe9acce6040f48 new file mode 100644 index 0000000000000000000000000000000000000000..fdc245172ec35f8e203035921cb60f65e3f9e0b0 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/83/83a8b0f70cc693fb7dbe9acce6040f48 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/83/83a9d1d65d16b4ce69380fe33e9b13c3 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/83/83a9d1d65d16b4ce69380fe33e9b13c3 new file mode 100644 index 0000000000000000000000000000000000000000..7e59ce8f67e84c7230a0b5b1c4ac3d70adbadfcc Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/83/83a9d1d65d16b4ce69380fe33e9b13c3 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/83/83ac352a670f6b66f44a02caf1e5a4ff b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/83/83ac352a670f6b66f44a02caf1e5a4ff new file mode 100644 index 0000000000000000000000000000000000000000..6d73a1d0b73988b798e1a4538b9131d650906ec6 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/83/83ac352a670f6b66f44a02caf1e5a4ff differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/83/83f67d7733b808e47dd7cd5eb11a3f8d b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/83/83f67d7733b808e47dd7cd5eb11a3f8d new file mode 100644 index 0000000000000000000000000000000000000000..210e4522f89f1ea6ec262889009095601e6b3b8a Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/83/83f67d7733b808e47dd7cd5eb11a3f8d differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/84/84e60cca22b65bbd283ba919c4dd7fb9 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/84/84e60cca22b65bbd283ba919c4dd7fb9 new file mode 100644 index 0000000000000000000000000000000000000000..43f186429d2eccf49440b14fe6311858dc9aad1f Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/84/84e60cca22b65bbd283ba919c4dd7fb9 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/84/84e907d9e5b27507b9ede99a69396319 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/84/84e907d9e5b27507b9ede99a69396319 new file mode 100644 index 0000000000000000000000000000000000000000..5e9d04adc2a9e6e28ba22be1cffd8c525962435f Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/84/84e907d9e5b27507b9ede99a69396319 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/84/84ea381b0c5ecb34c7160a31f7a55316 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/84/84ea381b0c5ecb34c7160a31f7a55316 new file mode 100644 index 0000000000000000000000000000000000000000..31f94453e4ef20ba973698e60e96b063cdddd289 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/84/84ea381b0c5ecb34c7160a31f7a55316 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/84/84f0976b1652046c01b3a50bd4319ffe b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/84/84f0976b1652046c01b3a50bd4319ffe new file mode 100644 index 0000000000000000000000000000000000000000..c235c4da2129d09cb63e281324fe5e16e230ab8f Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/84/84f0976b1652046c01b3a50bd4319ffe differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/85/8512a3c0ec7eea281b058199cd4abca0 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/85/8512a3c0ec7eea281b058199cd4abca0 new file mode 100644 index 0000000000000000000000000000000000000000..3ebef0f67bd2a181335d95ada0c37c64e66e920b Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/85/8512a3c0ec7eea281b058199cd4abca0 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/85/851575b862a42b910d49bc4eb979600a b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/85/851575b862a42b910d49bc4eb979600a new file mode 100644 index 0000000000000000000000000000000000000000..8f4fffee34eadf4eec0e1b141b72b8e9b2c221de Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/85/851575b862a42b910d49bc4eb979600a differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/85/85a10600d950c716aadfb9169e942915 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/85/85a10600d950c716aadfb9169e942915 new file mode 100644 index 0000000000000000000000000000000000000000..c00c5e83f75b4e65c7b094aa1ea69db58bd3d644 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/85/85a10600d950c716aadfb9169e942915 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/85/85a61a581fe5d344bf8cf00d2e46112b b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/85/85a61a581fe5d344bf8cf00d2e46112b new file mode 100644 index 0000000000000000000000000000000000000000..403e1142cd3e2c92c537399f895727bac9d32283 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/85/85a61a581fe5d344bf8cf00d2e46112b differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/85/85b60906bcaedbd3cd5b998a35ce1647 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/85/85b60906bcaedbd3cd5b998a35ce1647 new file mode 100644 index 0000000000000000000000000000000000000000..53791079aa1fbb2354535877e4e836ab1388e721 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/85/85b60906bcaedbd3cd5b998a35ce1647 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/85/85bd2d51a4509b15cd85df3d63bff2cb b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/85/85bd2d51a4509b15cd85df3d63bff2cb new file mode 100644 index 0000000000000000000000000000000000000000..efe655b92e772e499067f320bdedbdf70c4084da Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/85/85bd2d51a4509b15cd85df3d63bff2cb differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/86/86a01a44b1298a06040dbfc8bf064561 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/86/86a01a44b1298a06040dbfc8bf064561 new file mode 100644 index 0000000000000000000000000000000000000000..6c6192663dbea5751f84b1bffb2ddb54d9b405e5 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/86/86a01a44b1298a06040dbfc8bf064561 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/86/86ce9b8aaf248f9293f6ddae56e34cd8 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/86/86ce9b8aaf248f9293f6ddae56e34cd8 new file mode 100644 index 0000000000000000000000000000000000000000..a986c33a815f3830a80d588cdf62a61054bcfd62 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/86/86ce9b8aaf248f9293f6ddae56e34cd8 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/86/86dab41c246309e725bcfdb82c997019 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/86/86dab41c246309e725bcfdb82c997019 new file mode 100644 index 0000000000000000000000000000000000000000..5c61975f3a51bcc83825f2c26d1ee67bbb38ea74 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/86/86dab41c246309e725bcfdb82c997019 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/86/86e2ac5d04215d928f4e014df3fea158 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/86/86e2ac5d04215d928f4e014df3fea158 new file mode 100644 index 0000000000000000000000000000000000000000..272662a22d314f7b0ee5595c0b89b1bcadda053b Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/86/86e2ac5d04215d928f4e014df3fea158 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/87/8707ee59edfe2212c7af8a1084f85ac3 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/87/8707ee59edfe2212c7af8a1084f85ac3 new file mode 100644 index 0000000000000000000000000000000000000000..b50bde2fbbbe63bdac351e613b442585bb23ea42 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/87/8707ee59edfe2212c7af8a1084f85ac3 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/87/87ad94a02209096a3a5251e6a7187140 b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/87/87ad94a02209096a3a5251e6a7187140 new file mode 100644 index 0000000000000000000000000000000000000000..50cea8420bbe396cbe54db95175f0985e73f3206 Binary files /dev/null and b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/Artifacts/87/87ad94a02209096a3a5251e6a7187140 differ diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/DelayedCallback.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/DelayedCallback.cs new file mode 100644 index 0000000000000000000000000000000000000000..b331d155b1b813c70086cd1c02d07df23c5e9e4d --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/DelayedCallback.cs @@ -0,0 +1,44 @@ +namespace UnityEditor.TestTools.TestRunner +{ + internal class DelayedCallback + { + private System.Action m_Callback; + private double m_CallbackTime; + private double m_Delay; + + public DelayedCallback(System.Action function, double timeFromNow) + { + m_Callback = function; + m_CallbackTime = EditorApplication.timeSinceStartup + timeFromNow; + m_Delay = timeFromNow; + EditorApplication.update += Update; + } + + public void Clear() + { + EditorApplication.update -= Update; + m_CallbackTime = 0.0; + m_Callback = null; + } + + private void Update() + { + if (EditorApplication.timeSinceStartup > m_CallbackTime) + { + // Clear state before firing callback to ensure reset (callback could call ExitGUI) + var callback = m_Callback; + Clear(); + + callback?.Invoke(); + } + } + + public void Reset() + { + if (m_Callback != null) + { + m_CallbackTime = EditorApplication.timeSinceStartup + m_Delay; + } + } + } +} \ No newline at end of file diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/DelayedCallback.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/DelayedCallback.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..5218c8ec80bf8cbb72ba2d629f14de8017a8efcf --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/DelayedCallback.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b9d121df8c444236a5b38ccfadfdd1a7 +timeCreated: 1583140472 \ No newline at end of file diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/EditModeLauncher.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/EditModeLauncher.cs new file mode 100644 index 0000000000000000000000000000000000000000..12683dcfa006f0a50617c4c02befe769130c17ce --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/EditModeLauncher.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Generic; +using NUnit.Framework.Interfaces; +using UnityEditor.SceneManagement; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEditor.TestTools.TestRunner.GUI; +using UnityEngine; +using UnityEngine.SceneManagement; +using UnityEngine.TestRunner.Utils; +using UnityEngine.TestTools; +using UnityEngine.TestTools.TestRunner; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditModeLauncher : TestLauncherBase + { + public static bool IsRunning; + internal readonly EditModeRunner m_EditModeRunner; + public bool launchedOutsideApi; + + // provided for backward compatibility with Rider UnitTesting prior to Rider package v.1.1.1 + public EditModeLauncher(UITestRunnerFilter filter, TestPlatform platform) + { + launchedOutsideApi = true; + var apiFilter = new[] + { + new Filter() + { + testMode = TestMode.EditMode, + testNames = filter.testNames, + categoryNames = filter.categoryNames, + groupNames = filter.groupNames, + assemblyNames = filter.assemblyNames + } + }; + + ScriptableObject.CreateInstance().Execute(new ExecutionSettings(apiFilter)); + } + + public EditModeLauncher(Filter[] filters, TestPlatform platform, bool runSynchronously) + { + TestEnumerator.Reset(); + m_EditModeRunner = ScriptableObject.CreateInstance(); + m_EditModeRunner.UnityTestAssemblyRunnerFactory = new UnityTestAssemblyRunnerFactory(); + m_EditModeRunner.Init(filters, platform, runSynchronously); + } + + public override void Run() + { + if (launchedOutsideApi) + { + // Do not use the launcher, as it will be relaunched trough the api. See ctor. + return; + } + + IsRunning = true; + + SceneSetup[] previousSceneSetup; + if (!OpenNewScene(out previousSceneSetup)) + return; + + var callback = AddEventHandler(); + callback.previousSceneSetup = previousSceneSetup; + callback.runner = m_EditModeRunner; + AddEventHandler(); + + m_EditModeRunner.Run(); + AddEventHandler(); + AddEventHandler(); + + if (m_EditModeRunner.RunningSynchronously) + m_EditModeRunner.CompleteSynchronously(); + } + + private static bool OpenNewScene(out SceneSetup[] previousSceneSetup) + { + previousSceneSetup = null; + + var sceneCount = SceneManager.sceneCount; + + var scene = SceneManager.GetSceneAt(0); + var isSceneNotPersisted = string.IsNullOrEmpty(scene.path); + + if (sceneCount == 1 && isSceneNotPersisted) + { + EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single); + return true; + } + RemoveUntitledScenes(); + + // In case the user chose not to save the dirty scenes we reload them + ReloadUnsavedDirtyScene(); + + previousSceneSetup = EditorSceneManager.GetSceneManagerSetup(); + + scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); + SceneManager.SetActiveScene(scene); + + return true; + } + + private static void ReloadUnsavedDirtyScene() + { + for (var i = 0; i < SceneManager.sceneCount; i++) + { + var scene = SceneManager.GetSceneAt(i); + var isSceneNotPersisted = string.IsNullOrEmpty(scene.path); + var isSceneDirty = scene.isDirty; + if (isSceneNotPersisted && isSceneDirty) + { + EditorSceneManager.ReloadScene(scene); + } + } + } + + private static void RemoveUntitledScenes() + { + int sceneCount = SceneManager.sceneCount; + + var scenesToClose = new List(); + for (var i = 0; i < sceneCount; i++) + { + var scene = SceneManager.GetSceneAt(i); + var isSceneNotPersisted = string.IsNullOrEmpty(scene.path); + if (isSceneNotPersisted) + { + scenesToClose.Add(scene); + } + } + foreach (Scene scene in scenesToClose) + { + EditorSceneManager.CloseScene(scene, true); + } + } + + public class BackgroundListener : ScriptableObject, ITestRunnerListener + { + public void RunStarted(ITest testsToRun) + { + } + + public void RunFinished(ITestResult testResults) + { + IsRunning = false; + } + + public void TestStarted(ITest test) + { + } + + public void TestFinished(ITestResult result) + { + } + } + + public T AddEventHandler() where T : ScriptableObject, ITestRunnerListener + { + return m_EditModeRunner.AddEventHandler(); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/EditModeLauncher.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/EditModeLauncher.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..694d7d6a59b624bed6eba649ff5565dccfd0ccd7 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/EditModeLauncher.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ac68f5ae37c8957468562b8da42f9984 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/EditModeLauncherContextSettings.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/EditModeLauncherContextSettings.cs new file mode 100644 index 0000000000000000000000000000000000000000..e20305cd117de059f79aa8228ef5ffed86fb6a78 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/EditModeLauncherContextSettings.cs @@ -0,0 +1,31 @@ +using System; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditModeLauncherContextSettings : IDisposable + { + private bool m_RunInBackground; + + public EditModeLauncherContextSettings() + { + SetupProjectParameters(); + } + + public void Dispose() + { + CleanupProjectParameters(); + } + + private void SetupProjectParameters() + { + m_RunInBackground = Application.runInBackground; + Application.runInBackground = true; + } + + private void CleanupProjectParameters() + { + Application.runInBackground = m_RunInBackground; + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/EditModeLauncherContextSettings.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/EditModeLauncherContextSettings.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..2bed8fde488a5bb5bb4fab579fc82029a3f31a00 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/EditModeLauncherContextSettings.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a582090813554df479fb9ca03e9857d3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PlatformSetup.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PlatformSetup.meta new file mode 100644 index 0000000000000000000000000000000000000000..494738260080a51e89c533829b9ab73a9f576f0f --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PlatformSetup.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ebc4d20cc106cea49b1df1153f0b3b5e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PlayerLauncher.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PlayerLauncher.cs new file mode 100644 index 0000000000000000000000000000000000000000..ea3e5968ff63d30c2c320b8a9d973c2458cf8f58 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PlayerLauncher.cs @@ -0,0 +1,251 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using NUnit.Framework.Internal.Filters; +using UnityEditor; +using UnityEditor.TestRunner.TestLaunchers; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; +using UnityEngine.SceneManagement; +using UnityEngine.TestRunner.Utils; +using UnityEngine.TestTools.TestRunner; +using UnityEngine.TestTools.TestRunner.Callbacks; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class TestLaunchFailedException : Exception + { + public TestLaunchFailedException() {} + public TestLaunchFailedException(string message) : base(message) {} + } + + [Serializable] + internal class PlayerLauncher : RuntimeTestLauncherBase + { + private readonly PlaymodeTestsControllerSettings m_Settings; + private readonly BuildTarget m_TargetPlatform; + private ITestRunSettings m_OverloadTestRunSettings; + private string m_SceneName; + private int m_HeartbeatTimeout; + + public PlayerLauncher(PlaymodeTestsControllerSettings settings, BuildTarget? targetPlatform, ITestRunSettings overloadTestRunSettings, int heartbeatTimeout) + { + m_Settings = settings; + m_TargetPlatform = targetPlatform ?? EditorUserBuildSettings.activeBuildTarget; + m_OverloadTestRunSettings = overloadTestRunSettings; + m_HeartbeatTimeout = heartbeatTimeout; + } + + protected override RuntimePlatform? TestTargetPlatform + { + get { return BuildTargetConverter.TryConvertToRuntimePlatform(m_TargetPlatform); } + } + + public override void Run() + { + var editorConnectionTestCollector = RemoteTestRunController.instance; + editorConnectionTestCollector.hideFlags = HideFlags.HideAndDontSave; + editorConnectionTestCollector.Init(m_TargetPlatform, m_HeartbeatTimeout); + + var remotePlayerLogController = RemotePlayerLogController.instance; + remotePlayerLogController.hideFlags = HideFlags.HideAndDontSave; + + using (var settings = new PlayerLauncherContextSettings(m_OverloadTestRunSettings)) + { + m_SceneName = CreateSceneName(); + var scene = PrepareScene(m_SceneName); + string scenePath = scene.path; + + var filter = m_Settings.BuildNUnitFilter(); + var runner = LoadTests(filter); + var exceptionThrown = ExecutePreBuildSetupMethods(runner.LoadedTest, filter); + if (exceptionThrown) + { + ReopenOriginalScene(m_Settings.originalScene); + AssetDatabase.DeleteAsset(m_SceneName); + CallbacksDelegator.instance.RunFailed("Run Failed: One or more errors in a prebuild setup. See the editor log for details."); + return; + } + + var playerBuildOptions = GetBuildOptions(scenePath); + + var success = BuildAndRunPlayer(playerBuildOptions); + + editorConnectionTestCollector.PostBuildAction(); + ExecutePostBuildCleanupMethods(runner.LoadedTest, filter); + + ReopenOriginalScene(m_Settings.originalScene); + AssetDatabase.DeleteAsset(m_SceneName); + + if (!success) + { + editorConnectionTestCollector.CleanUp(); + ScriptableObject.DestroyImmediate(editorConnectionTestCollector); + Debug.LogError("Player build failed"); + throw new TestLaunchFailedException("Player build failed"); + } + + if ((playerBuildOptions.BuildPlayerOptions.options & BuildOptions.AutoRunPlayer) != 0) + { + editorConnectionTestCollector.PostSuccessfulBuildAction(); + editorConnectionTestCollector.PostSuccessfulLaunchAction(); + } + + var runSettings = m_OverloadTestRunSettings as PlayerLauncherTestRunSettings; + if (success && runSettings != null && runSettings.buildOnly) + { + EditorUtility.RevealInFinder(playerBuildOptions.BuildPlayerOptions.locationPathName); + } + } + } + + public Scene PrepareScene(string sceneName) + { + var scene = CreateBootstrapScene(sceneName, runner => + { + runner.AddEventHandlerMonoBehaviour(); + runner.settings = m_Settings; + var commandLineArgs = Environment.GetCommandLineArgs(); + if (!commandLineArgs.Contains("-doNotReportTestResultsBackToEditor")) + { + runner.AddEventHandlerMonoBehaviour(); + } + runner.AddEventHandlerMonoBehaviour(); + runner.AddEventHandlerScriptableObject(); + }); + return scene; + } + + private static bool BuildAndRunPlayer(PlayerLauncherBuildOptions buildOptions) + { + Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, null, "Building player with following options:\n{0}", buildOptions); + + + // Android has to be in listen mode to establish player connection + if (buildOptions.BuildPlayerOptions.target == BuildTarget.Android) + { + buildOptions.BuildPlayerOptions.options &= ~BuildOptions.ConnectToHost; + } + + // For now, so does Lumin + if (buildOptions.BuildPlayerOptions.target == BuildTarget.Lumin) + { + buildOptions.BuildPlayerOptions.options &= ~BuildOptions.ConnectToHost; + } + + var result = BuildPipeline.BuildPlayer(buildOptions.BuildPlayerOptions); + if (result.summary.result != Build.Reporting.BuildResult.Succeeded) + Debug.LogError(result.SummarizeErrors()); + + return result.summary.result == Build.Reporting.BuildResult.Succeeded; + } + + internal PlayerLauncherBuildOptions GetBuildOptions(string scenePath) + { + var buildOnly = false; + var runSettings = m_OverloadTestRunSettings as PlayerLauncherTestRunSettings; + if (runSettings != null) + { + buildOnly = runSettings.buildOnly; + } + + var buildOptions = new BuildPlayerOptions(); + + var scenes = new List() { scenePath }; + scenes.AddRange(EditorBuildSettings.scenes.Select(x => x.path)); + buildOptions.scenes = scenes.ToArray(); + + buildOptions.options |= BuildOptions.Development | BuildOptions.ConnectToHost | BuildOptions.IncludeTestAssemblies | BuildOptions.StrictMode; + buildOptions.target = m_TargetPlatform; + + if (EditorUserBuildSettings.waitForPlayerConnection) + buildOptions.options |= BuildOptions.WaitForPlayerConnection; + + if (EditorUserBuildSettings.allowDebugging) + buildOptions.options |= BuildOptions.AllowDebugging; + + if (EditorUserBuildSettings.installInBuildFolder) + buildOptions.options |= BuildOptions.InstallInBuildFolder; + else if (!buildOnly) + buildOptions.options |= BuildOptions.AutoRunPlayer; + + var buildTargetGroup = EditorUserBuildSettings.activeBuildTargetGroup; + + //Check if Lz4 is supported for the current buildtargetgroup and enable it if need be + if (PostprocessBuildPlayer.SupportsLz4Compression(buildTargetGroup, m_TargetPlatform)) + { + if (EditorUserBuildSettings.GetCompressionType(buildTargetGroup) == Compression.Lz4) + buildOptions.options |= BuildOptions.CompressWithLz4; + else if (EditorUserBuildSettings.GetCompressionType(buildTargetGroup) == Compression.Lz4HC) + buildOptions.options |= BuildOptions.CompressWithLz4HC; + } + + string buildLocation; + if (buildOnly) + { + buildLocation = buildOptions.locationPathName = runSettings.buildOnlyLocationPath; + } + else + { + var reduceBuildLocationPathLength = false; + + //Some platforms hit MAX_PATH limits during the build process, in these cases minimize the path length + if ((m_TargetPlatform == BuildTarget.WSAPlayer) || (m_TargetPlatform == BuildTarget.XboxOne)) + { + reduceBuildLocationPathLength = true; + } + + var uniqueTempPathInProject = FileUtil.GetUniqueTempPathInProject(); + var playerDirectoryName = reduceBuildLocationPathLength ? "PwT" : "PlayerWithTests"; + + if (reduceBuildLocationPathLength) + { + uniqueTempPathInProject = Path.GetTempFileName(); + File.Delete(uniqueTempPathInProject); + Directory.CreateDirectory(uniqueTempPathInProject); + } + + var tempPath = Path.GetFullPath(uniqueTempPathInProject); + buildLocation = Path.Combine(tempPath, playerDirectoryName); + + // iOS builds create a folder with Xcode project instead of an executable, therefore no executable name is added + if (m_TargetPlatform == BuildTarget.iOS) + { + buildOptions.locationPathName = buildLocation; + } + else + { + string extensionForBuildTarget = + PostprocessBuildPlayer.GetExtensionForBuildTarget(buildTargetGroup, buildOptions.target, + buildOptions.options); + var playerExecutableName = "PlayerWithTests"; + playerExecutableName += string.Format(".{0}", extensionForBuildTarget); + buildOptions.locationPathName = Path.Combine(buildLocation, playerExecutableName); + } + } + + return new PlayerLauncherBuildOptions + { + BuildPlayerOptions = ModifyBuildOptions(buildOptions), + PlayerDirectory = buildLocation, + }; + } + + private BuildPlayerOptions ModifyBuildOptions(BuildPlayerOptions buildOptions) + { + var allAssemblies = AppDomain.CurrentDomain.GetAssemblies() + .Where(x => x.GetReferencedAssemblies().Any(z => z.Name == "UnityEditor.TestRunner")).ToArray(); + var attributes = allAssemblies.SelectMany(assembly => assembly.GetCustomAttributes(typeof(TestPlayerBuildModifierAttribute), true).OfType()).ToArray(); + var modifiers = attributes.Select(attribute => attribute.ConstructModifier()).ToArray(); + + foreach (var modifier in modifiers) + { + buildOptions = modifier.ModifyOptions(buildOptions); + } + + return buildOptions; + } + } +} \ No newline at end of file diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PlayerLauncher.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PlayerLauncher.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..60bb1c7fe62e3d50bcc767fa6ebeea6007afc2ba --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PlayerLauncher.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d973fc1524e4d724081553934c55958c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PlayerLauncherBuildOptions.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PlayerLauncherBuildOptions.cs new file mode 100644 index 0000000000000000000000000000000000000000..b4985147cf08ef363f9cd387e0a4bd81003ea677 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PlayerLauncherBuildOptions.cs @@ -0,0 +1,23 @@ +using System.Text; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class PlayerLauncherBuildOptions + { + public BuildPlayerOptions BuildPlayerOptions; + public string PlayerDirectory; + + public override string ToString() + { + var str = new StringBuilder(); + str.AppendLine("locationPathName = " + BuildPlayerOptions.locationPathName); + str.AppendLine("target = " + BuildPlayerOptions.target); + str.AppendLine("scenes = " + string.Join(", ", BuildPlayerOptions.scenes)); + str.AppendLine("assetBundleManifestPath = " + BuildPlayerOptions.assetBundleManifestPath); + str.AppendLine("options.Development = " + ((BuildPlayerOptions.options & BuildOptions.Development) != 0)); + str.AppendLine("options.AutoRunPlayer = " + ((BuildPlayerOptions.options & BuildOptions.AutoRunPlayer) != 0)); + str.AppendLine("options.ForceEnableAssertions = " + ((BuildPlayerOptions.options & BuildOptions.ForceEnableAssertions) != 0)); + return str.ToString(); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PlayerLauncherBuildOptions.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PlayerLauncherBuildOptions.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..73c1779649184b9e3e4412001cf7e7b66fa95790 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PlayerLauncherBuildOptions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2a0bd678385f98e4d8eabdfc07d62b4f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PrebuildSetupAttributeFinder.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PrebuildSetupAttributeFinder.cs new file mode 100644 index 0000000000000000000000000000000000000000..b51241f5c9ae3c422351abc3305037e105f61eec --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PrebuildSetupAttributeFinder.cs @@ -0,0 +1,9 @@ +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class PrebuildSetupAttributeFinder : AttributeFinderBase + { + public PrebuildSetupAttributeFinder() : base((attribute) => attribute.TargetClass) {} + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PrebuildSetupAttributeFinder.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PrebuildSetupAttributeFinder.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..d524e56e5918a5188afcdb43e525bd0666834b40 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/PrebuildSetupAttributeFinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3c4ccfb0896bcf44da13e152b267aa49 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RemotePlayerLogController.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RemotePlayerLogController.cs new file mode 100644 index 0000000000000000000000000000000000000000..abaa2192e3e7c08c59e3ab3fa5b9a3dea25f9758 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RemotePlayerLogController.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using UnityEditor.DeploymentTargets; +using UnityEditor.TestTools.TestRunner.CommandLineTest; +using UnityEngine; + +namespace UnityEditor.TestRunner.TestLaunchers +{ + [Serializable] + internal class RemotePlayerLogController : ScriptableSingleton + { + private List m_LogWriters; + + private Dictionary m_Loggers; + + private string m_DeviceLogsDirectory; + + public void SetBuildTarget(BuildTarget buildTarget) + { + m_Loggers = GetDeploymentTargetLoggers(buildTarget); + + if (m_Loggers == null) + Debug.Log("Deployment target logger could not be created"); + } + + public void SetLogsDirectory(string dir) + { + m_DeviceLogsDirectory = dir; + } + + public void StartLogWriters() + { + if (m_DeviceLogsDirectory == null || m_Loggers == null) + return; + + m_LogWriters = new List(); + + foreach (var logger in m_Loggers) + { + m_LogWriters.Add(new LogWriter(m_DeviceLogsDirectory, logger.Key, logger.Value)); + logger.Value.Start(); + } + } + + public void StopLogWriters() + { + if (m_LogWriters == null) + return; + + foreach (var logWriter in m_LogWriters) + { + logWriter.Stop(); + } + } + + private Dictionary GetDeploymentTargetLoggers(BuildTarget buildTarget) + { + DeploymentTargetManager deploymentTargetManager; + + try + { + deploymentTargetManager = DeploymentTargetManager.CreateInstance(EditorUserBuildSettings.activeBuildTargetGroup, buildTarget); + + if (deploymentTargetManager == null) + return null; + } + catch (NotSupportedException ex) + { + Debug.Log(ex.Message); + Debug.Log("Deployment target logger not initialised"); + return null; + } + + var targets = deploymentTargetManager.GetKnownTargets(); + var loggers = new Dictionary(); + + foreach (var target in targets) + { + if (target.status != DeploymentTargetStatus.Ready) continue; + + var logger = deploymentTargetManager.GetTargetLogger(target.id); + logger.Clear(); + loggers.Add(target.id, logger); + } + + return loggers; + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RemotePlayerLogController.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RemotePlayerLogController.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..b20841926889c74704a8a06b2da8fb4079b11e8c --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RemotePlayerLogController.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: edd2a1fe1acbbde43aad39862bb3f4a8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RemotePlayerTestController.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RemotePlayerTestController.cs new file mode 100644 index 0000000000000000000000000000000000000000..fc21332c4b4f525eb5a727f55e5ed71609493b5b --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RemotePlayerTestController.cs @@ -0,0 +1,115 @@ +using System; +using UnityEditor.Networking.PlayerConnection; +using UnityEditor.TestTools.TestRunner; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEditor.TestTools.TestRunner.UnityTestProtocol; +using UnityEngine; +using UnityEngine.Networking.PlayerConnection; +using UnityEngine.TestRunner.TestLaunchers; + +namespace UnityEditor.TestRunner.TestLaunchers +{ + [Serializable] + internal class RemoteTestRunController : ScriptableSingleton + { + internal const int k_HeartbeatTimeout = 60 * 10; + + [SerializeField] + private RemoteTestResultReciever m_RemoteTestResultReciever; + + [SerializeField] + private PlatformSpecificSetup m_PlatformSpecificSetup; + + [SerializeField] + private bool m_RegisteredConnectionCallbacks; + + [SerializeField] + private int m_HearbeatTimeOut; + + private UnityEditor.TestTools.TestRunner.DelayedCallback m_TimeoutCallback; + + public void Init(BuildTarget buildTarget, int heartbeatTimeout) + { + m_HearbeatTimeOut = heartbeatTimeout; + m_PlatformSpecificSetup = new PlatformSpecificSetup(buildTarget); + m_PlatformSpecificSetup.Setup(); + m_RemoteTestResultReciever = new RemoteTestResultReciever(); + EditorConnection.instance.Initialize(); + if (!m_RegisteredConnectionCallbacks) + { + EditorConnection.instance.Initialize(); + DelegateEditorConnectionEvents(); + } + } + + private void DelegateEditorConnectionEvents() + { + m_RegisteredConnectionCallbacks = true; + //This is needed because RemoteTestResultReceiver is not a ScriptableObject + EditorConnection.instance.Register(PlayerConnectionMessageIds.runStartedMessageId, RunStarted); + EditorConnection.instance.Register(PlayerConnectionMessageIds.runFinishedMessageId, RunFinished); + EditorConnection.instance.Register(PlayerConnectionMessageIds.testStartedMessageId, TestStarted); + EditorConnection.instance.Register(PlayerConnectionMessageIds.testFinishedMessageId, TestFinished); + EditorConnection.instance.Register(PlayerConnectionMessageIds.playerAliveHeartbeat, PlayerAliveHeartbeat); + } + + private void RunStarted(MessageEventArgs messageEventArgs) + { + m_TimeoutCallback?.Reset(); + m_RemoteTestResultReciever.RunStarted(messageEventArgs); + CallbacksDelegator.instance.RunStartedRemotely(messageEventArgs.data); + } + + private void RunFinished(MessageEventArgs messageEventArgs) + { + m_TimeoutCallback?.Clear(); + m_RemoteTestResultReciever.RunFinished(messageEventArgs); + m_PlatformSpecificSetup.CleanUp(); + + CallbacksDelegator.instance.RunFinishedRemotely(messageEventArgs.data); + } + + private void TestStarted(MessageEventArgs messageEventArgs) + { + m_TimeoutCallback?.Reset(); + CallbacksDelegator.instance.TestStartedRemotely(messageEventArgs.data); + } + + private void TestFinished(MessageEventArgs messageEventArgs) + { + m_TimeoutCallback?.Reset(); + CallbacksDelegator.instance.TestFinishedRemotely(messageEventArgs.data); + } + + private void PlayerAliveHeartbeat(MessageEventArgs messageEventArgs) + { + m_TimeoutCallback?.Reset(); + } + + private void TimeoutCallback() + { + CallbacksDelegator.instance.RunFailed($"Test execution timed out. No activity received from the player in {m_HearbeatTimeOut} seconds."); + } + + public void PostBuildAction() + { + m_PlatformSpecificSetup.PostBuildAction(); + } + + public void PostSuccessfulBuildAction() + { + m_PlatformSpecificSetup.PostSuccessfulBuildAction(); + m_TimeoutCallback = new UnityEditor.TestTools.TestRunner.DelayedCallback(TimeoutCallback, m_HearbeatTimeOut); + } + + public void PostSuccessfulLaunchAction() + { + m_PlatformSpecificSetup.PostSuccessfulLaunchAction(); + } + + public void CleanUp() + { + m_PlatformSpecificSetup.CleanUp(); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RemotePlayerTestController.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RemotePlayerTestController.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..020222b5b95b1373421b94b687a5d9a30b0d63bb --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RemotePlayerTestController.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7d36034e63ad8254b9b2f55280fcc040 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RemoteTestResultReciever.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RemoteTestResultReciever.cs new file mode 100644 index 0000000000000000000000000000000000000000..75b07125738f71d7c16f38eaea5b47cbf6ac104b --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RemoteTestResultReciever.cs @@ -0,0 +1,22 @@ +using System; +using UnityEditor.Networking.PlayerConnection; +using UnityEngine; +using UnityEngine.Networking.PlayerConnection; +using UnityEngine.TestRunner.TestLaunchers; + +namespace UnityEditor.TestTools.TestRunner +{ + [Serializable] + internal class RemoteTestResultReciever + { + public void RunStarted(MessageEventArgs messageEventArgs) + { + } + + public void RunFinished(MessageEventArgs messageEventArgs) + { + EditorConnection.instance.Send(PlayerConnectionMessageIds.quitPlayerMessageId, null, messageEventArgs.playerId); + EditorConnection.instance.DisconnectAll(); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RemoteTestResultReciever.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RemoteTestResultReciever.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..e7010151571245a3786a0db6469d349a64b8ec0b --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RemoteTestResultReciever.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fdb35ef8fc437e14fa4b6c74a0609e86 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RuntimeTestLauncherBase.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RuntimeTestLauncherBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..87d9672809cc0a6fd82f145e5c34277d23127bc8 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RuntimeTestLauncherBase.cs @@ -0,0 +1,92 @@ +using System; +using System.Linq; +using NUnit.Framework.Interfaces; +using UnityEditor.Events; +using UnityEditor.SceneManagement; +using UnityEngine; +using UnityEngine.SceneManagement; +using UnityEngine.TestRunner.NUnitExtensions.Runner; +using UnityEngine.TestTools; +using UnityEngine.TestTools.NUnitExtensions; +using UnityEngine.TestTools.TestRunner; +using UnityEngine.TestTools.Utils; + +namespace UnityEditor.TestTools.TestRunner +{ + internal abstract class RuntimeTestLauncherBase : TestLauncherBase + { + protected Scene CreateBootstrapScene(string sceneName, Action runnerSetup) + { + var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); + var go = new GameObject(PlaymodeTestsController.kPlaymodeTestControllerName); + + var editorLoadedTestAssemblyProvider = new EditorLoadedTestAssemblyProvider(new EditorCompilationInterfaceProxy(), new EditorAssembliesProxy()); + + var runner = go.AddComponent(); + runnerSetup(runner); + runner.settings.bootstrapScene = sceneName; + runner.AssembliesWithTests = editorLoadedTestAssemblyProvider.GetAssembliesGroupedByType(TestPlatform.PlayMode).Select(x => x.Assembly.GetName().Name).ToList(); + + EditorSceneManager.MarkSceneDirty(scene); + AssetDatabase.SaveAssets(); + EditorSceneManager.SaveScene(scene, sceneName, false); + + return scene; + } + + public string CreateSceneName() + { + return "Assets/InitTestScene" + DateTime.Now.Ticks + ".unity"; + } + + protected UnityTestAssemblyRunner LoadTests(ITestFilter filter) + { + var editorLoadedTestAssemblyProvider = new EditorLoadedTestAssemblyProvider(new EditorCompilationInterfaceProxy(), new EditorAssembliesProxy()); + var assembliesWithTests = editorLoadedTestAssemblyProvider.GetAssembliesGroupedByType(TestPlatform.PlayMode).Select(x => x.Assembly.GetName().Name).ToList(); + + var nUnitTestAssemblyRunner = new UnityTestAssemblyRunner(new UnityTestAssemblyBuilder(), null); + var assemblyProvider = new PlayerTestAssemblyProvider(new AssemblyLoadProxy(), assembliesWithTests); + nUnitTestAssemblyRunner.Load(assemblyProvider.GetUserAssemblies().Select(a => a.Assembly).ToArray(), TestPlatform.PlayMode, UnityTestAssemblyBuilder.GetNUnitTestBuilderSettings(TestPlatform.PlayMode)); + return nUnitTestAssemblyRunner; + } + + protected static void ReopenOriginalScene(string originalSceneName) + { + EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects); + if (!string.IsNullOrEmpty(originalSceneName)) + { + EditorSceneManager.OpenScene(originalSceneName); + } + } + } + + internal static class PlaymodeTestsControllerExtensions + { + internal static T AddEventHandlerMonoBehaviour(this PlaymodeTestsController controller) where T : MonoBehaviour, ITestRunnerListener + { + var eventHandler = controller.gameObject.AddComponent(); + SetListeners(controller, eventHandler); + return eventHandler; + } + + internal static T AddEventHandlerScriptableObject(this PlaymodeTestsController controller) where T : ScriptableObject, ITestRunnerListener + { + var eventListener = ScriptableObject.CreateInstance(); + AddEventHandlerScriptableObject(controller, eventListener); + return eventListener; + } + + internal static void AddEventHandlerScriptableObject(this PlaymodeTestsController controller, ITestRunnerListener obj) + { + SetListeners(controller, obj); + } + + private static void SetListeners(PlaymodeTestsController controller, ITestRunnerListener eventHandler) + { + UnityEventTools.AddPersistentListener(controller.testStartedEvent, eventHandler.TestStarted); + UnityEventTools.AddPersistentListener(controller.testFinishedEvent, eventHandler.TestFinished); + UnityEventTools.AddPersistentListener(controller.runStartedEvent, eventHandler.RunStarted); + UnityEventTools.AddPersistentListener(controller.runFinishedEvent, eventHandler.RunFinished); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RuntimeTestLauncherBase.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RuntimeTestLauncherBase.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..28c74163f14142b16ac718673112a92433ec99b9 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/RuntimeTestLauncherBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0efb23ecb373b6d4bbe5217485785138 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/TestLauncherBase.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/TestLauncherBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..7bfd3546525fdd2deca202b97d33612fbea0aea3 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/TestLauncherBase.cs @@ -0,0 +1,85 @@ +using System; +using System.Linq; +using NUnit.Framework.Interfaces; +using UnityEngine; +using UnityEngine.TestTools; +using UnityEngine.TestTools.Logging; +using UnityEngine.TestTools.TestRunner; + +namespace UnityEditor.TestTools.TestRunner +{ + internal abstract class TestLauncherBase + { + public abstract void Run(); + + protected virtual RuntimePlatform? TestTargetPlatform + { + get { return Application.platform; } + } + + protected bool ExecutePreBuildSetupMethods(ITest tests, ITestFilter testRunnerFilter) + { + var attributeFinder = new PrebuildSetupAttributeFinder(); + var logString = "Executing setup for: {0}"; + return ExecuteMethods(tests, testRunnerFilter, attributeFinder, logString, targetClass => targetClass.Setup(), TestTargetPlatform); + } + + public void ExecutePostBuildCleanupMethods(ITest tests, ITestFilter testRunnerFilter) + { + ExecutePostBuildCleanupMethods(tests, testRunnerFilter, TestTargetPlatform); + } + + public static void ExecutePostBuildCleanupMethods(ITest tests, ITestFilter testRunnerFilter, RuntimePlatform? testTargetPlatform) + { + var attributeFinder = new PostbuildCleanupAttributeFinder(); + var logString = "Executing cleanup for: {0}"; + ExecuteMethods(tests, testRunnerFilter, attributeFinder, logString, targetClass => targetClass.Cleanup(), testTargetPlatform); + } + + private static bool ExecuteMethods(ITest tests, ITestFilter testRunnerFilter, AttributeFinderBase attributeFinder, string logString, Action action, RuntimePlatform? testTargetPlatform) + { + var exceptionsThrown = false; + + if (testTargetPlatform == null) + { + Debug.LogError("Could not determine test target platform from build target " + EditorUserBuildSettings.activeBuildTarget); + return true; + } + + foreach (var targetClassType in attributeFinder.Search(tests, testRunnerFilter, testTargetPlatform.Value)) + { + try + { + var targetClass = (T)Activator.CreateInstance(targetClassType); + + Debug.LogFormat(logString, targetClassType.FullName); + + using (var logScope = new LogScope()) + { + action(targetClass); + + if (logScope.AnyFailingLogs()) + { + var failingLog = logScope.FailingLogs.First(); + throw new UnhandledLogMessageException(failingLog); + } + + if (logScope.ExpectedLogs.Any()) + { + var expectedLogs = logScope.ExpectedLogs.First(); + throw new UnexpectedLogMessageException(expectedLogs); + } + } + } + catch (InvalidCastException) {} + catch (Exception e) + { + Debug.LogException(e); + exceptionsThrown = true; + } + } + + return exceptionsThrown; + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/TestLauncherBase.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/TestLauncherBase.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..c36990c79f61a5101c721a4cd5be199db4ef3913 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestLaunchers/TestLauncherBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1cddf785b0d07434d8e0607c97b09135 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/Tasks.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/Tasks.meta new file mode 100644 index 0000000000000000000000000000000000000000..bb019b794b667517a025c267bc7bf7d256b7c32e --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/Tasks.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6dba53789da15814387fa5b1445e81e0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/Tasks/BuildActionTaskBase.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/Tasks/BuildActionTaskBase.cs new file mode 100644 index 0000000000000000000000000000000000000000..7efaecb2417c4a6bfa544712bc0699dd838688e6 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/Tasks/BuildActionTaskBase.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework.Interfaces; +using UnityEngine; +using UnityEngine.TestTools.Logging; +using UnityEngine.TestTools.TestRunner; + +namespace UnityEditor.TestTools.TestRunner.TestRun.Tasks +{ + internal abstract class BuildActionTaskBase : TestTaskBase + { + private string typeName; + internal IAttributeFinder attributeFinder; + internal RuntimePlatform targetPlatform = Application.platform; + internal Action logAction = Debug.Log; + internal Func logScopeProvider = () => new LogScope(); + internal Func createInstance = Activator.CreateInstance; + + protected BuildActionTaskBase(IAttributeFinder attributeFinder) + { + this.attributeFinder = attributeFinder; + typeName = typeof(T).Name; + } + + protected abstract void Action(T target); + + public override IEnumerator Execute(TestJobData testJobData) + { + if (testJobData.testTree == null) + { + throw new Exception($"Test tree is not available for {GetType().Name}."); + } + + var enumerator = ExecuteMethods(testJobData.testTree, testJobData.executionSettings.BuildNUnitFilter()); + while (enumerator.MoveNext()) + { + yield return null; + } + } + + protected IEnumerator ExecuteMethods(ITest testTree, ITestFilter testRunnerFilter) + { + var exceptions = new List(); + + foreach (var targetClassType in attributeFinder.Search(testTree, testRunnerFilter, targetPlatform)) + { + try + { + var targetClass = (T) createInstance(targetClassType); + + logAction($"Executing {typeName} for: {targetClassType.FullName}."); + + using (var logScope = logScopeProvider()) + { + Action(targetClass); + + if (logScope.AnyFailingLogs()) + { + var failingLog = logScope.FailingLogs.First(); + throw new UnhandledLogMessageException(failingLog); + } + + if (logScope.ExpectedLogs.Any()) + { + var expectedLogs = logScope.ExpectedLogs.First(); + throw new UnexpectedLogMessageException(expectedLogs); + } + } + } + catch (Exception ex) + { + exceptions.Add(ex); + } + + yield return null; + } + + if (exceptions.Count > 0) + { + throw new AggregateException($"One or more exceptions when executing {typeName}.", exceptions); + } + } + } +} \ No newline at end of file diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/Tasks/BuildActionTaskBase.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/Tasks/BuildActionTaskBase.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..54afd57c3f20b48d1385ffda3143361259dde9fb --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/Tasks/BuildActionTaskBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c2441d353f9c42a44af6e224e4901b52 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/Tasks/BuildTestTreeTask.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/Tasks/BuildTestTreeTask.cs new file mode 100644 index 0000000000000000000000000000000000000000..b66f50738272b59091c95e04e73a0c255b5c2acb --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/Tasks/BuildTestTreeTask.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections; +using System.Linq; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine.TestRunner.NUnitExtensions; +using UnityEngine.TestTools; +using UnityEngine.TestTools.NUnitExtensions; + +namespace UnityEditor.TestTools.TestRunner.TestRun.Tasks +{ + internal class BuildTestTreeTask : TestTaskBase + { + private TestPlatform m_TestPlatform; + + public BuildTestTreeTask(TestPlatform testPlatform) + { + m_TestPlatform = testPlatform; + } + + internal IEditorLoadedTestAssemblyProvider m_testAssemblyProvider = new EditorLoadedTestAssemblyProvider(new EditorCompilationInterfaceProxy(), new EditorAssembliesProxy()); + internal IAsyncTestAssemblyBuilder m_testAssemblyBuilder = new UnityTestAssemblyBuilder(); + internal ICallbacksDelegator m_CallbacksDelegator = CallbacksDelegator.instance; + + public override IEnumerator Execute(TestJobData testJobData) + { + if (testJobData.testTree != null) + { + yield break; + } + + var assembliesEnumerator = m_testAssemblyProvider.GetAssembliesGroupedByTypeAsync(m_TestPlatform); + while (assembliesEnumerator.MoveNext()) + { + yield return null; + } + + if (assembliesEnumerator.Current == null) + { + throw new Exception("Assemblies not retrieved."); + } + + var assemblies = assembliesEnumerator.Current.Where(pair => m_TestPlatform.IsFlagIncluded(pair.Key)).SelectMany(pair => pair.Value).Select(x => x.Assembly).ToArray(); + var buildSettings = UnityTestAssemblyBuilder.GetNUnitTestBuilderSettings(m_TestPlatform); + var enumerator = m_testAssemblyBuilder.BuildAsync(assemblies, Enumerable.Repeat(m_TestPlatform, assemblies.Length).ToArray(), buildSettings); + while (enumerator.MoveNext()) + { + yield return null; + } + + var testList = enumerator.Current; + if (testList== null) + { + throw new Exception("Test list not retrieved."); + } + + testList.ParseForNameDuplicates(); + testJobData.testTree = testList; + m_CallbacksDelegator.TestTreeRebuild(testList); + } + } +} \ No newline at end of file diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/Tasks/BuildTestTreeTask.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/Tasks/BuildTestTreeTask.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..b00d7b1d9ac6bef5fd0d1a39d86143c8c798e920 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/Tasks/BuildTestTreeTask.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a0288e1c9324e824bab7e2044a72a434 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestJobData.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestJobData.cs new file mode 100644 index 0000000000000000000000000000000000000000..05ab50348736c7677ca475bf2acbd79d7b0661ec --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestJobData.cs @@ -0,0 +1,49 @@ +using System; +using NUnit.Framework.Interfaces; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner.TestRun +{ + [Serializable] + internal class TestJobData + { + [SerializeField] + public string guid; + + [SerializeField] + public int taskIndex; + + [SerializeField] + public int taskPC; + + [SerializeField] + public bool isRunning; + + [SerializeField] + public ExecutionSettings executionSettings; + + [SerializeField] + public string[] existingFiles; + + [SerializeField] + public int undoGroup = -1; + + [SerializeField] + public EditModeRunner editModeRunner; + + [NonSerialized] + public bool isHandledByRunner; + + public ITest testTree; + + public TestJobData(ExecutionSettings settings) + { + guid = Guid.NewGuid().ToString(); + executionSettings = settings; + isRunning = false; + taskIndex = 0; + taskPC = 0; + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestJobData.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestJobData.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..5da5662e91e7965a18dfc9c1101f76960f0bbe46 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestJobData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 80ac8f5b2a7fa904dbc80111be88c8be +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestJobDataHolder.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestJobDataHolder.cs new file mode 100644 index 0000000000000000000000000000000000000000..7852f739c8317513db3854ce262284d4930b26c2 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestJobDataHolder.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner.TestRun +{ + internal class TestJobDataHolder : ScriptableSingleton + { + [SerializeField] + public List TestRuns = new List(); + + [InitializeOnLoadMethod] + private static void ResumeRunningJobs() + { + foreach (var testRun in instance.TestRuns.ToArray()) + { + if (testRun.isRunning) + { + var runner = new TestJobRunner(); + runner.RunJob(testRun); + } + else + { + instance.TestRuns.Remove(testRun); + } + } + } + } +} \ No newline at end of file diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestJobDataHolder.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestJobDataHolder.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..3612b80a2847b0401b53dc009212814c8e3bf90c --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestJobDataHolder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 612b00d793cac3c49808ab3ee5428f16 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestJobRunner.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestJobRunner.cs new file mode 100644 index 0000000000000000000000000000000000000000..8a9cd4f989e5f999e054a08b0208d3bcba04ed6c --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestJobRunner.cs @@ -0,0 +1,166 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEditor.TestTools.TestRunner.TestRun.Tasks; +using UnityEngine; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner.TestRun +{ + internal class TestJobRunner + { + private static IEnumerable GetTaskList(ExecutionSettings settings) + { + if (settings == null) + { + yield break; + } + + if (settings.EditModeIncluded() || (PlayerSettings.runPlayModeTestAsEditModeTest && settings.PlayModeInEditorIncluded())) + { + yield return new SaveModiedSceneTask(); + yield return new RegisterFilesForCleanupVerificationTask(); + yield return new SaveUndoIndexTask(); + yield return new BuildTestTreeTask(TestPlatform.EditMode); + yield return new PrebuildSetupTask(); + yield return new LegacyEditModeRunTask(); + yield return new PerformUndoTask(); + yield return new CleanupVerificationTask(); + yield break; + } + + if (settings.PlayModeInEditorIncluded() && !PlayerSettings.runPlayModeTestAsEditModeTest) + { + yield return new SaveModiedSceneTask(); + yield return new LegacyPlayModeRunTask(); + yield break; + } + + if (settings.PlayerIncluded()) + { + yield return new LegacyPlayerRunTask(); + yield break; + } + } + + internal List SavedTestJobData = TestJobDataHolder.instance.TestRuns; + internal Action SubscribeCallback = (callback) => EditorApplication.update += callback; + // ReSharper disable once DelegateSubtraction + internal Action UnsubscribeCallback = (callback) => EditorApplication.update -= callback; + internal TestCommandPcHelper PcHelper = new EditModePcHelper(); + internal Func> GetTasks = GetTaskList; + internal Action LogException = Debug.LogException; + internal Action LogError = Debug.LogError; + internal Action ReportRunFailed = CallbacksDelegator.instance.RunFailed; + + private TestJobData m_JobData; + private TestTaskBase[] Tasks; + private IEnumerator m_Enumerator = null; + + public string RunJob(TestJobData data) + { + if (data == null) + { + throw new ArgumentException(null, nameof(data)); + } + + if (m_JobData != null && m_JobData.isRunning) + { + throw new Exception("TestJobRunner is already running a job."); + } + + if (data.isHandledByRunner) + { + throw new Exception("Test job is already being handled."); + } + + m_JobData = data; + m_JobData.isHandledByRunner = true; + + if (!m_JobData.isRunning) + { + m_JobData.isRunning = true; + SavedTestJobData.Add(m_JobData); + } + + Tasks = GetTasks(data.executionSettings).ToArray(); + if (!data.executionSettings.runSynchronously) + { + SubscribeCallback(ExecuteStep); + } + else + { + while (data.isRunning) + { + ExecuteStep(); + } + } + + return data.guid; + } + + private void ExecuteStep() + { + try + { + if (m_JobData.taskIndex >= Tasks.Length) + { + StopRun(); + return; + } + + if (m_Enumerator == null) + { + var task = Tasks[m_JobData.taskIndex]; + m_Enumerator = task.Execute(m_JobData); + if (task.SupportsResumingEnumerator) + { + PcHelper.SetEnumeratorPC(m_Enumerator, m_JobData.taskPC); + } + } + + if (!m_Enumerator.MoveNext()) + { + m_JobData.taskIndex++; + m_JobData.taskPC = 0; + m_Enumerator = null; + return; + } + + if (Tasks[m_JobData.taskIndex].SupportsResumingEnumerator) + { + m_JobData.taskPC = PcHelper.GetEnumeratorPC(m_Enumerator); + } + } + catch (TestRunCanceledException) + { + StopRun(); + } + catch (AggregateException ex) + { + StopRun(); + LogError(ex.Message); + foreach (var innerException in ex.InnerExceptions) + { + LogException(innerException); + } + ReportRunFailed("Multiple unexpected errors happened while running tests."); + } + catch (Exception ex) + { + StopRun(); + LogException(ex); + ReportRunFailed("An unexpected error happened while running tests."); + } + } + + private void StopRun() + { + m_JobData.isRunning = false; + UnsubscribeCallback(ExecuteStep); + SavedTestJobData.Remove(m_JobData); + } + } +} \ No newline at end of file diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestJobRunner.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestJobRunner.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..df11aa02113da3b14339993dcec458d2b2ce5be8 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestJobRunner.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0b677ddfd54046c498a20446baa4f932 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestRunCanceledException.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestRunCanceledException.cs new file mode 100644 index 0000000000000000000000000000000000000000..542c501f98376f58a2f71a6a42a7b6b4acec7284 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestRunCanceledException.cs @@ -0,0 +1,9 @@ +using System; + +namespace UnityEditor.TestTools.TestRunner.TestRun +{ + internal class TestRunCanceledException : Exception + { + + } +} \ No newline at end of file diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestRunCanceledException.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestRunCanceledException.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..2237e64260e3c8eeb71d45133260b8072583ce6d --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRun/TestRunCanceledException.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1d45b9d3cf85bee4f99c1492fca8438a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks.meta new file mode 100644 index 0000000000000000000000000000000000000000..9e611a480401c52d1901a8237174d8c223fd0979 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5d7f0d6acfced954682a89e7002c04d9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/EditModeRunnerCallback.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/EditModeRunnerCallback.cs new file mode 100644 index 0000000000000000000000000000000000000000..a22c7988f20790b1366f1604d84440704bfc053e --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/EditModeRunnerCallback.cs @@ -0,0 +1,186 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using UnityEditor.SceneManagement; +using UnityEngine; +using UnityEngine.TestTools.TestRunner; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditModeRunnerCallback : ScriptableObject, ITestRunnerListener + { + private EditModeLauncherContextSettings m_Settings; + public SceneSetup[] previousSceneSetup; + public EditModeRunner runner; + + private bool m_Canceled; + private ITest m_CurrentTest; + private int m_TotalTests; + + [SerializeField] + private List m_PendingTests; + [SerializeField] + private string m_LastCountedTestName; + [SerializeField] + private bool m_RunRestarted; + + public void OnDestroy() + { + CleanUp(); + } + + public void RunStarted(ITest testsToRun) + { + Setup(); + if (m_PendingTests == null) + { + m_PendingTests = GetTestsExpectedToRun(testsToRun, runner.GetFilter()); + m_TotalTests = m_PendingTests.Count; + } + } + + public void OnEnable() + { + if (m_RunRestarted) + { + Setup(); + } + } + + private void Setup() + { + m_Settings = new EditModeLauncherContextSettings(); + Application.logMessageReceivedThreaded += LogReceived; + EditorApplication.playModeStateChanged += WaitForExitPlaymode; + EditorApplication.update += DisplayProgressBar; + AssemblyReloadEvents.beforeAssemblyReload += BeforeAssemblyReload; + } + + private void BeforeAssemblyReload() + { + if (m_CurrentTest != null) + { + m_LastCountedTestName = m_CurrentTest.FullName; + m_RunRestarted = true; + } + } + + private void DisplayProgressBar() + { + if (m_CurrentTest == null) + return; + if (!m_Canceled && EditorUtility.DisplayCancelableProgressBar("Test Runner", "Running test " + m_CurrentTest.Name, Math.Min(1.0f, (float)(m_TotalTests - m_PendingTests.Count) / m_TotalTests))) + { + EditorApplication.update -= DisplayProgressBar; + m_Canceled = true; + EditorUtility.ClearProgressBar(); + runner.OnRunCancel(); + } + } + + private static void LogReceived(string message, string stacktrace, LogType type) + { + if (TestContext.Out != null) + TestContext.Out.WriteLine(message); + } + + private static void WaitForExitPlaymode(PlayModeStateChange state) + { + if (state == PlayModeStateChange.EnteredEditMode) + { + EditorApplication.playModeStateChanged -= WaitForExitPlaymode; + //because logMessage is reset on Enter EditMode + //we remove and add the callback + //because Unity + Application.logMessageReceivedThreaded -= LogReceived; + Application.logMessageReceivedThreaded += LogReceived; + } + } + + public void RunFinished(ITestResult result) + { + if (previousSceneSetup != null && previousSceneSetup.Length > 0) + { + try + { + EditorSceneManager.RestoreSceneManagerSetup(previousSceneSetup); + } + catch (ArgumentException e) + { + Debug.LogWarning(e.Message); + } + } + else + { + foreach (var obj in FindObjectsOfType()) + { + if (obj != null && obj.transform.parent != null && (obj.transform.parent.hideFlags & HideFlags.DontSaveInEditor) == HideFlags.DontSaveInEditor && obj.transform.parent.gameObject != null) + { + DestroyImmediate(obj.transform.parent.gameObject); + } + } + + EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single); + } + CleanUp(); + } + + private void CleanUp() + { + m_CurrentTest = null; + EditorUtility.ClearProgressBar(); + if (m_Settings != null) + { + m_Settings.Dispose(); + } + Application.logMessageReceivedThreaded -= LogReceived; + EditorApplication.update -= DisplayProgressBar; + } + + public void TestStarted(ITest test) + { + if (test.IsSuite || !(test is TestMethod)) + { + return; + } + + m_CurrentTest = test; + + if (m_RunRestarted) + { + if (test.FullName == m_LastCountedTestName) + m_RunRestarted = false; + } + } + + public void TestFinished(ITestResult result) + { + if (result.Test is TestMethod) + { + m_PendingTests.Remove(result.Test.FullName); + } + } + + private static List GetTestsExpectedToRun(ITest test, ITestFilter filter) + { + var expectedTests = new List(); + + if (filter.Pass(test)) + { + if (test.IsSuite) + { + expectedTests.AddRange(test.Tests.SelectMany(subTest => GetTestsExpectedToRun(subTest, filter))); + } + else + { + expectedTests.Add(test.FullName); + } + } + + return expectedTests; + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/EditModeRunnerCallback.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/EditModeRunnerCallback.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..1a0d71c8ac4e7115de23ca41cb7337fb076bf017 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/EditModeRunnerCallback.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cc456ba93311a3a43ad896449fee9868 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallback.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallback.cs new file mode 100644 index 0000000000000000000000000000000000000000..a4976af27f059b14850dd184df411e7a04257854 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallback.cs @@ -0,0 +1,86 @@ +using UnityEditor.TestTools.TestRunner.Api; +using UnityEditor.TestTools.TestRunner.CommandLineTest; +using UnityEditor.TestTools.TestRunner.GUI; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class RerunCallback : ScriptableObject, ICallbacks + { + public static bool useMockRunFilter = false; + public static UITestRunnerFilter mockRunFilter = null; + + public void RunFinished(ITestResultAdaptor result) + { + if (RerunCallbackData.instance.runFilters == null || RerunCallbackData.instance.runFilters.Length == 0) + RerunCallbackData.instance.runFilters = new[] {new UITestRunnerFilter()}; + + var runFilter = RerunCallbackData.instance.runFilters[0]; + + if (useMockRunFilter) + { + runFilter = mockRunFilter; + } + + runFilter.testRepetitions--; + if (runFilter.testRepetitions <= 0 || result.TestStatus != TestStatus.Passed) + { + ExitCallbacks.preventExit = false; + return; + } + + ExitCallbacks.preventExit = true; + if (EditorApplication.isPlaying) + { + EditorApplication.playModeStateChanged += WaitForExitPlaymode; + return; + } + + if (!useMockRunFilter) + { + ExecuteTestRunnerAPI(); + } + } + + private static void WaitForExitPlaymode(PlayModeStateChange state) + { + if (state == PlayModeStateChange.EnteredEditMode) + { + ExecuteTestRunnerAPI(); + } + } + + private static void ExecuteTestRunnerAPI() + { + var runFilter = RerunCallbackData.instance.runFilters[0]; + var testMode = RerunCallbackData.instance.testMode; + + var testRunnerApi = ScriptableObject.CreateInstance(); + testRunnerApi.Execute(new Api.ExecutionSettings() + { + filters = new[] + { + new Filter() + { + categoryNames = runFilter.categoryNames, + groupNames = runFilter.groupNames, + testMode = testMode, + testNames = runFilter.testNames + } + } + }); + } + + public void TestStarted(ITestAdaptor test) + { + } + + public void TestFinished(ITestResultAdaptor result) + { + } + + public void RunStarted(ITestAdaptor testsToRun) + { + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallback.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallback.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..6dae8f259bcbf057c81e850e9a7aee9d4eee3b83 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallback.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 34d30300ba8eb4959a74ac1f8f413c8d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallbackData.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallbackData.cs new file mode 100644 index 0000000000000000000000000000000000000000..d6abd3fcd64a2a5a941f6b637f69f967bd4fdf7a --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallbackData.cs @@ -0,0 +1,15 @@ +using UnityEditor.TestTools.TestRunner.Api; +using UnityEditor.TestTools.TestRunner.GUI; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class RerunCallbackData : ScriptableSingleton + { + [SerializeField] + internal UITestRunnerFilter[] runFilters; + + [SerializeField] + internal TestMode testMode; + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallbackData.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallbackData.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..8615d9b00745c0134ab7c745e4f9bcb5a1a6e919 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallbackData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5be0e972cb9434b7797b1d37dcd127c3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallbackInitializer.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallbackInitializer.cs new file mode 100644 index 0000000000000000000000000000000000000000..2260d4da26aed9c9a5f63f5925deec0b8c3ef5b7 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallbackInitializer.cs @@ -0,0 +1,17 @@ +using UnityEngine; +using UnityEditor.TestTools.TestRunner.Api; + +namespace UnityEditor.TestTools.TestRunner +{ + [InitializeOnLoad] + static class RerunCallbackInitializer + { + static RerunCallbackInitializer() + { + var testRunnerApi = ScriptableObject.CreateInstance(); + + var rerunCallback = ScriptableObject.CreateInstance(); + testRunnerApi.RegisterCallbacks(rerunCallback); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallbackInitializer.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallbackInitializer.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..778b8fcaca558e885e6ae9d7071b9b7fa29c3cf0 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/RerunCallbackInitializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9cb48d7d0e6784c81ad36cdbfe8e4b6b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/TestRunnerCallback.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/TestRunnerCallback.cs new file mode 100644 index 0000000000000000000000000000000000000000..4234754ab1e366420a041bce96fa541c19029a38 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/TestRunnerCallback.cs @@ -0,0 +1,37 @@ +using NUnit.Framework.Interfaces; +using UnityEngine; +using UnityEngine.TestTools.TestRunner; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class TestRunnerCallback : ScriptableObject, ITestRunnerListener + { + public void RunStarted(ITest testsToRun) + { + EditorApplication.playModeStateChanged += OnPlayModeStateChanged; + } + + private void OnPlayModeStateChanged(PlayModeStateChange state) + { + if (state == PlayModeStateChange.ExitingPlayMode) + { + EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; + //We need to make sure we don't block NUnit thread in case we exit PlayMode earlier + PlaymodeTestsController.TryCleanup(); + } + } + + public void RunFinished(ITestResult testResults) + { + EditorApplication.isPlaying = false; + } + + public void TestStarted(ITest testName) + { + } + + public void TestFinished(ITestResult test) + { + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/TestRunnerCallback.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/TestRunnerCallback.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..1356ff989185c0dcef9c9466748edf64b62cbbe5 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/TestRunnerCallback.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d44e6804bc58be84ea71a619b468f150 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/WindowResultUpdater.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/WindowResultUpdater.cs new file mode 100644 index 0000000000000000000000000000000000000000..05465d8589e652039ce158105675bad2d58339f1 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/WindowResultUpdater.cs @@ -0,0 +1,59 @@ +using System.Linq; +using TestRunner.Callbacks; +using UnityEditor.TestTools.TestRunner.Api; + +namespace UnityEditor.TestTools.TestRunner.GUI +{ + internal class WindowResultUpdater : ICallbacks, ITestTreeRebuildCallbacks + { + public WindowResultUpdater() + { + var cachedResults = WindowResultUpdaterDataHolder.instance.CachedResults; + var testList = TestRunnerWindow.s_Instance.m_SelectedTestTypes; + foreach (var result in cachedResults) + { + testList.UpdateResult(result); + } + + cachedResults.Clear(); + + } + public void RunStarted(ITestAdaptor testsToRun) + { + } + + public void RunFinished(ITestResultAdaptor testResults) + { + if (TestRunnerWindow.s_Instance != null) + { + TestRunnerWindow.s_Instance.RebuildUIFilter(); + } + } + + public void TestStarted(ITestAdaptor testName) + { + } + + public void TestFinished(ITestResultAdaptor test) + { + var result = new TestRunnerResult(test); + if (TestRunnerWindow.s_Instance == null) + { + WindowResultUpdaterDataHolder.instance.CachedResults.Add(result); + return; + } + + TestRunnerWindow.s_Instance.m_SelectedTestTypes.UpdateResult(result); + } + + public void TestTreeRebuild(ITestAdaptor test) + { + if (TestRunnerWindow.s_Instance == null) + { + return; + } + + TestRunnerWindow.s_Instance.m_SelectedTestTypes.UpdateTestTree(test); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/WindowResultUpdater.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/WindowResultUpdater.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..d9e35df836ff11ca96f40d39e3ff9affe400ccf4 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/WindowResultUpdater.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6d468ee3657be7a43a2ef2178ec14239 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/WindowResultUpdaterDataHolder.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/WindowResultUpdaterDataHolder.cs new file mode 100644 index 0000000000000000000000000000000000000000..a1fd48d329421cd72cd2f8f18236509b02558c05 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/WindowResultUpdaterDataHolder.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; +using UnityEditor; +using UnityEditor.TestTools.TestRunner.GUI; + +namespace TestRunner.Callbacks +{ + internal class WindowResultUpdaterDataHolder : ScriptableSingleton + { + public List CachedResults = new List(); + } +} \ No newline at end of file diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/WindowResultUpdaterDataHolder.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/WindowResultUpdaterDataHolder.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..aed0d8c00a4bead9deac20ec70d866d99502f58c --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Callbacks/WindowResultUpdaterDataHolder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 82075836be5e0c64bbe84e1f9436682e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditModePCHelper.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditModePCHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..8776887c00b7fd205aa1a02ecaac3ed1d1eb27c0 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditModePCHelper.cs @@ -0,0 +1,32 @@ +using System.Collections; +using System.Reflection; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditModePcHelper : TestCommandPcHelper + { + public override void SetEnumeratorPC(IEnumerator enumerator, int pc) + { + GetPCFieldInfo(enumerator).SetValue(enumerator, pc); + } + + public override int GetEnumeratorPC(IEnumerator enumerator) + { + if (enumerator == null) + { + return 0; + } + return (int)GetPCFieldInfo(enumerator).GetValue(enumerator); + } + + private FieldInfo GetPCFieldInfo(IEnumerator enumerator) + { + var field = enumerator.GetType().GetField("$PC", BindingFlags.NonPublic | BindingFlags.Instance); + if (field == null) // Roslyn + field = enumerator.GetType().GetField("<>1__state", BindingFlags.NonPublic | BindingFlags.Instance); + + return field; + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditModePCHelper.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditModePCHelper.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..ce559af2c83dfd7dc41b01db0a03ed1752361f7e --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditModePCHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6d16f2e78a356d34c9a32108929de932 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditModeRunner.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditModeRunner.cs new file mode 100644 index 0000000000000000000000000000000000000000..91481825ac6f4c8e1af0483f13e6c56ffac55397 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditModeRunner.cs @@ -0,0 +1,447 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Filters; +using UnityEngine; +using UnityEngine.TestTools.NUnitExtensions; +using UnityEngine.TestTools.TestRunner; +using UnityEngine.TestTools; +using UnityEngine.TestTools.TestRunner.GUI; +using UnityEditor.Callbacks; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine.TestRunner.NUnitExtensions; +using UnityEngine.TestRunner.NUnitExtensions.Runner; + +namespace UnityEditor.TestTools.TestRunner +{ + internal interface IUnityTestAssemblyRunnerFactory + { + IUnityTestAssemblyRunner Create(TestPlatform testPlatform, WorkItemFactory factory); + } + + internal class UnityTestAssemblyRunnerFactory : IUnityTestAssemblyRunnerFactory + { + public IUnityTestAssemblyRunner Create(TestPlatform testPlatform, WorkItemFactory factory) + { + return new UnityTestAssemblyRunner(new UnityTestAssemblyBuilder(), factory); + } + } + + [Serializable] + internal class EditModeRunner : ScriptableObject, IDisposable + { + [SerializeField] + private Filter[] m_Filters; + + //The counter from the IEnumerator object + [SerializeField] + private int m_CurrentPC; + + [SerializeField] + private bool m_ExecuteOnEnable; + + [SerializeField] + private List m_AlreadyStartedTests; + + [SerializeField] + private List m_ExecutedTests; + + [SerializeField] + private List m_CallbackObjects = new List(); + + [SerializeField] + private TestStartedEvent m_TestStartedEvent = new TestStartedEvent(); + + [SerializeField] + private TestFinishedEvent m_TestFinishedEvent = new TestFinishedEvent(); + + [SerializeField] + private RunStartedEvent m_RunStartedEvent = new RunStartedEvent(); + + [SerializeField] + private RunFinishedEvent m_RunFinishedEvent = new RunFinishedEvent(); + + [SerializeField] + private TestRunnerStateSerializer m_TestRunnerStateSerializer = new TestRunnerStateSerializer(); + + [SerializeField] + private bool m_RunningTests; + + [SerializeField] + private TestPlatform m_TestPlatform; + + [SerializeField] + private object m_CurrentYieldObject; + + [SerializeField] + private BeforeAfterTestCommandState m_SetUpTearDownState; + [SerializeField] + private BeforeAfterTestCommandState m_OuterUnityTestActionState; + + [SerializeField] + private EnumerableTestState m_EnumerableTestState; + + [SerializeField] + public bool RunFinished = false; + + public bool RunningSynchronously { get; private set; } + + internal IUnityTestAssemblyRunner m_Runner; + + private ConstructDelegator m_ConstructDelegator; + + private IEnumerator m_RunStep; + + public IUnityTestAssemblyRunnerFactory UnityTestAssemblyRunnerFactory { get; set; } + + public void Init(Filter[] filters, TestPlatform platform, bool runningSynchronously) + { + m_Filters = filters; + m_TestPlatform = platform; + m_AlreadyStartedTests = new List(); + m_ExecutedTests = new List(); + RunningSynchronously = runningSynchronously; + InitRunner(); + } + + private void InitRunner() + { + //We give the EditMode platform here so we dont suddenly create Playmode work items in the test Runner. + m_Runner = (UnityTestAssemblyRunnerFactory ?? new UnityTestAssemblyRunnerFactory()).Create(TestPlatform.EditMode, new EditmodeWorkItemFactory()); + var testAssemblyProvider = new EditorLoadedTestAssemblyProvider(new EditorCompilationInterfaceProxy(), new EditorAssembliesProxy()); + var assemblies = testAssemblyProvider.GetAssembliesGroupedByType(m_TestPlatform).Select(x => x.Assembly).ToArray(); + var loadedTests = m_Runner.Load(assemblies, TestPlatform.EditMode, + UnityTestAssemblyBuilder.GetNUnitTestBuilderSettings(m_TestPlatform)); + loadedTests.ParseForNameDuplicates(); + CallbacksDelegator.instance.TestTreeRebuild(loadedTests); + hideFlags |= HideFlags.DontSave; + EnumerableSetUpTearDownCommand.ActivePcHelper = new EditModePcHelper(); + OuterUnityTestActionCommand.ActivePcHelper = new EditModePcHelper(); + } + + public void OnEnable() + { + if (m_ExecuteOnEnable) + { + InitRunner(); + m_ExecuteOnEnable = false; + foreach (var callback in m_CallbackObjects) + { + AddListeners(callback as ITestRunnerListener); + } + m_ConstructDelegator = new ConstructDelegator(m_TestRunnerStateSerializer); + + EnumeratorStepHelper.SetEnumeratorPC(m_CurrentPC); + + UnityWorkItemDataHolder.alreadyExecutedTests = m_ExecutedTests.Select(x => x.uniqueName).ToList(); + UnityWorkItemDataHolder.alreadyStartedTests = m_AlreadyStartedTests; + Run(); + } + } + + public void TestStartedEvent(ITest test) + { + m_AlreadyStartedTests.Add(test.GetUniqueName()); + } + + public void TestFinishedEvent(ITestResult testResult) + { + m_AlreadyStartedTests.Remove(testResult.Test.GetUniqueName()); + m_ExecutedTests.Add(TestResultSerializer.MakeFromTestResult(testResult)); + } + + public void Run() + { + EditModeTestCallbacks.RestoringTestContext += OnRestoringTest; + var context = m_Runner.GetCurrentContext(); + if (m_SetUpTearDownState == null) + { + m_SetUpTearDownState = CreateInstance(); + } + context.SetUpTearDownState = m_SetUpTearDownState; + + if (m_OuterUnityTestActionState == null) + { + m_OuterUnityTestActionState = CreateInstance(); + } + context.OuterUnityTestActionState = m_OuterUnityTestActionState; + + if (m_EnumerableTestState == null) + { + m_EnumerableTestState = CreateInstance(); + } + context.EnumerableTestState = m_EnumerableTestState; + + if (!m_RunningTests) + { + m_RunStartedEvent.Invoke(m_Runner.LoadedTest); + } + + if (m_ConstructDelegator == null) + m_ConstructDelegator = new ConstructDelegator(m_TestRunnerStateSerializer); + + Reflect.ConstructorCallWrapper = m_ConstructDelegator.Delegate; + m_TestStartedEvent.AddListener(TestStartedEvent); + m_TestFinishedEvent.AddListener(TestFinishedEvent); + + AssemblyReloadEvents.beforeAssemblyReload += OnBeforeAssemblyReload; + + RunningTests = true; + + EditorApplication.LockReloadAssemblies(); + + var testListenerWrapper = new TestListenerWrapper(m_TestStartedEvent, m_TestFinishedEvent); + m_RunStep = m_Runner.Run(testListenerWrapper, GetFilter()).GetEnumerator(); + m_RunningTests = true; + + if (!RunningSynchronously) + EditorApplication.update += TestConsumer; + } + + public void CompleteSynchronously() + { + while (!m_Runner.IsTestComplete) + TestConsumer(); + } + + private void OnBeforeAssemblyReload() + { + EditorApplication.update -= TestConsumer; + + if (m_ExecuteOnEnable) + { + AssemblyReloadEvents.beforeAssemblyReload -= OnBeforeAssemblyReload; + return; + } + + if (m_Runner != null && m_Runner.TopLevelWorkItem != null) + m_Runner.TopLevelWorkItem.ResultedInDomainReload = true; + + if (RunningTests) + { + Debug.LogError("TestRunner: Unexpected assembly reload happened while running tests"); + + EditorUtility.ClearProgressBar(); + + if (m_Runner.GetCurrentContext() != null && m_Runner.GetCurrentContext().CurrentResult != null) + { + m_Runner.GetCurrentContext().CurrentResult.SetResult(ResultState.Cancelled, "Unexpected assembly reload happened"); + } + OnRunCancel(); + } + } + + private bool RunningTests; + + private Stack StepStack = new Stack(); + + private bool MoveNextAndUpdateYieldObject() + { + var result = m_RunStep.MoveNext(); + + if (result) + { + m_CurrentYieldObject = m_RunStep.Current; + while (m_CurrentYieldObject is IEnumerator) // going deeper + { + var currentEnumerator = (IEnumerator)m_CurrentYieldObject; + + // go deeper and add parent to stack + StepStack.Push(m_RunStep); + + m_RunStep = currentEnumerator; + m_CurrentYieldObject = m_RunStep.Current; + } + + if (StepStack.Count > 0 && m_CurrentYieldObject != null) // not null and not IEnumerator, nested + { + Debug.LogError("EditMode test can only yield null, but not <" + m_CurrentYieldObject.GetType().Name + ">"); + } + + return true; + } + + if (StepStack.Count == 0) // done + return false; + + m_RunStep = StepStack.Pop(); // going up + return MoveNextAndUpdateYieldObject(); + } + + private void TestConsumer() + { + var moveNext = MoveNextAndUpdateYieldObject(); + + if (m_CurrentYieldObject != null) + { + InvokeDelegator(); + } + + if (!moveNext && !m_Runner.IsTestComplete) + { + CompleteTestRun(); + throw new IndexOutOfRangeException("There are no more elements to process and IsTestComplete is false"); + } + + if (m_Runner.IsTestComplete) + { + CompleteTestRun(); + } + } + + private void CompleteTestRun() + { + if (!RunningSynchronously) + EditorApplication.update -= TestConsumer; + + TestLauncherBase.ExecutePostBuildCleanupMethods(this.GetLoadedTests(), this.GetFilter(), Application.platform); + + m_RunFinishedEvent.Invoke(m_Runner.Result); + RunFinished = true; + + if (m_ConstructDelegator != null) + m_ConstructDelegator.DestroyCurrentTestObjectIfExists(); + Dispose(); + UnityWorkItemDataHolder.alreadyExecutedTests = null; + } + + private void OnRestoringTest() + { + var item = m_ExecutedTests.Find(t => t.fullName == UnityTestExecutionContext.CurrentContext.CurrentTest.FullName); + if (item != null) + { + item.RestoreTestResult(UnityTestExecutionContext.CurrentContext.CurrentResult); + } + } + + private static bool IsCancelled() + { + return UnityTestExecutionContext.CurrentContext.ExecutionStatus == TestExecutionStatus.AbortRequested || UnityTestExecutionContext.CurrentContext.ExecutionStatus == TestExecutionStatus.StopRequested; + } + + private void InvokeDelegator() + { + if (m_CurrentYieldObject == null) + { + return; + } + + if (IsCancelled()) + { + return; + } + + if (m_CurrentYieldObject is RestoreTestContextAfterDomainReload) + { + if (m_TestRunnerStateSerializer.ShouldRestore()) + { + m_TestRunnerStateSerializer.RestoreContext(); + } + + return; + } + + try + { + if (m_CurrentYieldObject is IEditModeTestYieldInstruction) + { + var editModeTestYieldInstruction = (IEditModeTestYieldInstruction)m_CurrentYieldObject; + if (editModeTestYieldInstruction.ExpectDomainReload) + { + PrepareForDomainReload(); + } + return; + } + } + catch (Exception e) + { + UnityTestExecutionContext.CurrentContext.CurrentResult.RecordException(e); + return; + } + + Debug.LogError("EditMode test can only yield null"); + } + + private void CompilationFailureWatch() + { + if (EditorApplication.isCompiling) + return; + + EditorApplication.update -= CompilationFailureWatch; + + if (EditorUtility.scriptCompilationFailed) + { + EditorUtility.ClearProgressBar(); + OnRunCancel(); + } + } + + private void PrepareForDomainReload() + { + m_TestRunnerStateSerializer.SaveContext(); + m_CurrentPC = EnumeratorStepHelper.GetEnumeratorPC(TestEnumerator.Enumerator); + m_ExecuteOnEnable = true; + + RunningTests = false; + } + + public T AddEventHandler() where T : ScriptableObject, ITestRunnerListener + { + var eventHandler = CreateInstance(); + eventHandler.hideFlags |= HideFlags.DontSave; + m_CallbackObjects.Add(eventHandler); + + AddListeners(eventHandler); + + return eventHandler; + } + + private void AddListeners(ITestRunnerListener eventHandler) + { + m_TestStartedEvent.AddListener(eventHandler.TestStarted); + m_TestFinishedEvent.AddListener(eventHandler.TestFinished); + m_RunStartedEvent.AddListener(eventHandler.RunStarted); + m_RunFinishedEvent.AddListener(eventHandler.RunFinished); + } + + public void Dispose() + { + Reflect.MethodCallWrapper = null; + EditorApplication.update -= TestConsumer; + + DestroyImmediate(this); + + if (m_CallbackObjects != null) + { + foreach (var obj in m_CallbackObjects) + { + DestroyImmediate(obj); + } + m_CallbackObjects.Clear(); + } + RunningTests = false; + EditorApplication.UnlockReloadAssemblies(); + } + + public void OnRunCancel() + { + UnityWorkItemDataHolder.alreadyExecutedTests = null; + m_ExecuteOnEnable = false; + m_Runner.StopRun(); + RunFinished = true; + } + + public ITest GetLoadedTests() + { + return m_Runner.LoadedTest; + } + + public ITestFilter GetFilter() + { + return new OrFilter(m_Filters.Select(filter => filter.ToRuntimeTestRunnerFilter(RunningSynchronously).BuildNUnitFilter()).ToArray()); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditModeRunner.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditModeRunner.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..78c00399f3227661de89e7df4b2aa71d02144a4a --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditModeRunner.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c9219e99d466b7741a057132d1994f35 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditmodeWorkItemFactory.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditmodeWorkItemFactory.cs new file mode 100644 index 0000000000000000000000000000000000000000..c2bf921221d4a17fee19e803be878c194fb659c6 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditmodeWorkItemFactory.cs @@ -0,0 +1,14 @@ +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using UnityEngine.TestRunner.NUnitExtensions.Runner; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditmodeWorkItemFactory : WorkItemFactory + { + protected override UnityWorkItem Create(TestMethod method, ITestFilter filter, ITest loadedTest) + { + return new EditorEnumeratorTestWorkItem(method, filter); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditmodeWorkItemFactory.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditmodeWorkItemFactory.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..ab4bd45999a6c6dd8fee1e2562484ffd54f65bf1 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditmodeWorkItemFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3dde15f260b0dd1469e60d16eaa795dc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditorEnumeratorTestWorkItem.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditorEnumeratorTestWorkItem.cs new file mode 100644 index 0000000000000000000000000000000000000000..acf09dde463abddacd6979c9ac598aa93cb2b2d5 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditorEnumeratorTestWorkItem.cs @@ -0,0 +1,181 @@ +using System; +using System.Collections; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Commands; +using NUnit.Framework.Internal.Execution; +using UnityEngine; +using UnityEngine.TestRunner.NUnitExtensions.Runner; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditorEnumeratorTestWorkItem : UnityWorkItem + { + private TestCommand m_Command; + public EditorEnumeratorTestWorkItem(TestMethod test, ITestFilter filter) + : base(test, null) + { + m_Command = TestCommandBuilder.BuildTestCommand(test, filter); + } + + private static IEnumerableTestMethodCommand FindFirstIEnumerableTestMethodCommand(TestCommand command) + { + if (command == null) + { + return null; + } + + if (command is IEnumerableTestMethodCommand) + { + return (IEnumerableTestMethodCommand)command; + } + + if (command is DelegatingTestCommand) + { + var delegatingTestCommand = (DelegatingTestCommand)command; + return FindFirstIEnumerableTestMethodCommand(delegatingTestCommand.GetInnerCommand()); + } + return null; + } + + protected override IEnumerable PerformWork() + { + if (IsCancelledRun()) + { + yield break; + } + + if (m_DontRunRestoringResult) + { + if (EditModeTestCallbacks.RestoringTestContext == null) + { + throw new NullReferenceException("RestoringTestContext is not set"); + } + EditModeTestCallbacks.RestoringTestContext(); + Result = Context.CurrentResult; + yield break; + } + + try + { + if (IsCancelledRun()) + { + yield break; + } + + if (m_Command is SkipCommand) + { + m_Command.Execute(Context); + Result = Context.CurrentResult; + yield break; + } + + //Check if we can execute this test + var firstEnumerableCommand = FindFirstIEnumerableTestMethodCommand(m_Command); + if (firstEnumerableCommand == null) + { + Context.CurrentResult.SetResult(ResultState.Error, "Returning IEnumerator but not using test attribute supporting this"); + yield break; + } + if (Context.TestCaseTimeout == 0) + { + Context.TestCaseTimeout = k_DefaultTimeout; + } + if (m_Command.Test.Method.ReturnType.IsType(typeof(IEnumerator))) + { + if (m_Command is ApplyChangesToContextCommand) + { + var applyChangesToContextCommand = ((ApplyChangesToContextCommand)m_Command); + applyChangesToContextCommand.ApplyChanges(Context); + m_Command = applyChangesToContextCommand.GetInnerCommand(); + } + + var innerCommand = m_Command as IEnumerableTestMethodCommand; + if (innerCommand == null) + { + Debug.Log("failed getting innerCommand"); + throw new Exception("Tests returning IEnumerator can only use test attributes handling those"); + } + + foreach (var workItemStep in innerCommand.ExecuteEnumerable(Context)) + { + if (IsCancelledRun()) + { + yield break; + } + + if (workItemStep is TestEnumerator) + { + if (EnumeratorStepHelper.UpdateEnumeratorPcIfNeeded(TestEnumerator.Enumerator)) + { + yield return new RestoreTestContextAfterDomainReload(); + } + continue; + } + + if (workItemStep is AsyncOperation) + { + var asyncOperation = (AsyncOperation)workItemStep; + while (!asyncOperation.isDone) + { + if (IsCancelledRun()) + { + yield break; + } + + yield return null; + } + continue; + } + + ResultedInDomainReload = false; + + if (workItemStep is IEditModeTestYieldInstruction) + { + var editModeTestYieldInstruction = (IEditModeTestYieldInstruction)workItemStep; + yield return editModeTestYieldInstruction; + var enumerator = editModeTestYieldInstruction.Perform(); + while (true) + { + bool moveNext; + try + { + moveNext = enumerator.MoveNext(); + } + catch (Exception e) + { + Context.CurrentResult.RecordException(e); + break; + } + + if (!moveNext) + { + break; + } + yield return null; + } + } + else + { + yield return workItemStep; + } + } + + Result = Context.CurrentResult; + EditorApplication.isPlaying = false; + yield return null; + } + } + finally + { + WorkItemComplete(); + } + } + + private bool IsCancelledRun() + { + return Context.ExecutionStatus == TestExecutionStatus.AbortRequested || Context.ExecutionStatus == TestExecutionStatus.StopRequested; + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditorEnumeratorTestWorkItem.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditorEnumeratorTestWorkItem.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..982f7eeb08e89ddfb62fb80b858ba98d5780ed38 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EditorEnumeratorTestWorkItem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1ebc1994f9a3d5649a1201d3a84b38df +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EnumeratorStepHelper.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EnumeratorStepHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..46fc714519b8a1a769b9c281f7e00cc258d0bee8 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EnumeratorStepHelper.cs @@ -0,0 +1,51 @@ +using System.Collections; +using System.Reflection; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EnumeratorStepHelper + { + private static int m_PC; + + public static void SetEnumeratorPC(int pc) + { + m_PC = pc; + } + + /// + /// Gets the current enumerator PC + /// + /// + /// The PC + /// 0 if no current Enumeration + /// + public static int GetEnumeratorPC(IEnumerator enumerator) + { + if (enumerator == null) + { + return 0; + } + return (int)GetPCFieldInfo(enumerator).GetValue(enumerator); + } + + public static bool UpdateEnumeratorPcIfNeeded(IEnumerator enumerator) + { + if (m_PC != 0) + { + GetPCFieldInfo(enumerator).SetValue(enumerator, m_PC); + m_PC = 0; + return true; + } + return false; + } + + private static FieldInfo GetPCFieldInfo(IEnumerator enumerator) + { + var field = enumerator.GetType().GetField("$PC", BindingFlags.NonPublic | BindingFlags.Instance); + if (field == null) // Roslyn + field = enumerator.GetType().GetField("<>1__state", BindingFlags.NonPublic | BindingFlags.Instance); + + return field; + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EnumeratorStepHelper.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EnumeratorStepHelper.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..08662b9ec71ec8984e4a831c9602fe815a8c67d8 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/EnumeratorStepHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 901b761c5c1e22d4e8a3ba7d95bc1f5d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages.meta new file mode 100644 index 0000000000000000000000000000000000000000..0660c6371e7062644e23dbd670636c1691372b69 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d9682e749d3efc642af54d789d9090a6 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/EnterPlayMode.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/EnterPlayMode.cs new file mode 100644 index 0000000000000000000000000000000000000000..4c7c9fa75768b9925048e0885cee29eab2f56e5e --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/EnterPlayMode.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections; +using UnityEditor; + +namespace UnityEngine.TestTools +{ + /// + /// Implements . Creates a yield instruction to enter Play Mode. + /// + public class EnterPlayMode : IEditModeTestYieldInstruction + { + /// + /// Returns true if the instruction expects a domain reload to occur. + /// + public bool ExpectDomainReload { get; } + /// + /// Returns true if the instruction expects the Unity Editor to be in **Play Mode**. + /// + public bool ExpectedPlaymodeState { get; private set; } + /// + /// When creating an Editor test that uses the UnityTest attribute, use this to trigger the Editor to enter Play Mode. + /// Throws an exception if the Editor is already in Play Mode or if there is a script compilation error. + /// + /// A flag indication whether to expect a domain reload. + public EnterPlayMode(bool expectDomainReload = true) + { + ExpectDomainReload = expectDomainReload; + } + + /// + /// Performs the multi-step instructions of entering PlayMode. + /// + /// An IEnumerator with the async steps. + /// An exception is thrown if the editor is already in PlayMode or if script compilation failed. + public IEnumerator Perform() + { + if (EditorApplication.isPlaying) + { + throw new Exception("Editor is already in PlayMode"); + } + if (EditorUtility.scriptCompilationFailed) + { + throw new Exception("Script compilation failed"); + } + yield return null; + ExpectedPlaymodeState = true; + + EditorApplication.UnlockReloadAssemblies(); + EditorApplication.isPlaying = true; + + while (!EditorApplication.isPlaying) + { + yield return null; + } + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/EnterPlayMode.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/EnterPlayMode.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..fa1dc2e0f7f5b3a7dcb4c53a6c6072b886f17dac --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/EnterPlayMode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9bd5a110ed89025499ddee8c7e73778e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/ExitPlayMode.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/ExitPlayMode.cs new file mode 100644 index 0000000000000000000000000000000000000000..b4d072dece017a7b83db96043eddf4052944f207 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/ExitPlayMode.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections; +using UnityEditor; + +namespace UnityEngine.TestTools +{ + /// + /// Implements . A new instance of the class is a yield instruction to exit Play Mode. + /// + public class ExitPlayMode : IEditModeTestYieldInstruction + { + /// + /// Gets the value of ExpectDomainReload + /// + public bool ExpectDomainReload { get; } + /// + /// Gets the value of ExpectedPlaymodeState + /// + public bool ExpectedPlaymodeState { get; private set; } + /// + /// Sets ExpectDomainReload and ExpectedPlaymodeState to false. + /// + public ExitPlayMode() + { + ExpectDomainReload = false; + ExpectedPlaymodeState = false; + } + + /// + /// Performs the multi-step instruction of exiting PlayMode. + /// + /// An IEnumerator with the async steps. + /// An exception is thrown if the editor is not in PlayMode. + public IEnumerator Perform() + { + if (!EditorApplication.isPlayingOrWillChangePlaymode) + { + throw new Exception("Editor is already in EditMode"); + } + + EditorApplication.isPlaying = false; + while (EditorApplication.isPlaying) + { + yield return null; + } + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/ExitPlayMode.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/ExitPlayMode.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..1de769dc13dae68a5d339b274fe2db689c406444 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/ExitPlayMode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 408674d91d506a54aac9a7f07951c018 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/RecompileScripts.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/RecompileScripts.cs new file mode 100644 index 0000000000000000000000000000000000000000..2433d0d9c462ee04a47d41d01c60d32012f44666 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/RecompileScripts.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections; +using UnityEditor; + +namespace UnityEngine.TestTools +{ + /// + /// `RecompileScripts` is an that you can yield in Edit Mode tests. It lets you trigger a recompilation of scripts in the Unity Editor. + /// + public class RecompileScripts : IEditModeTestYieldInstruction + { + /// + /// Creates a new instance of the `RecompileScripts` yield instruction. + /// + /// + /// [UnitySetUp] + /// public IEnumerator SetUp() + /// { + /// using (var file = File.CreateText("Assets/temp/myScript.cs")) + /// { + /// file.Write("public class ATempClass { }"); + /// } + /// AssetDatabase.Refresh(); + /// yield return new RecompileScripts(); + /// } + /// + /// + /// + public RecompileScripts() : this(true) + { + } + /// + /// Creates a new instance of the `RecompileScripts` yield instruction. + /// + /// This parameter indicates if you expect a script compilation to start (defaults to true). If a script compilation does not start and `expectScriptCompilation` is true, then it throws an exception. + public RecompileScripts(bool expectScriptCompilation) : this(expectScriptCompilation, true) + { + } + /// + /// Creates a new instance of the `RecompileScripts` yield instruction. + /// + /// This parameter indicates if you expect a script compilation to start (defaults to true). If a script compilation does not start and `expectScriptCompilation` is `true`, then it throws an exception. + /// This parameter indicates if you expect a script compilation to succeed. If not succeeded then an exception will be thrown. + public RecompileScripts(bool expectScriptCompilation, bool expectScriptCompilationSuccess) + { + ExpectScriptCompilation = expectScriptCompilation; + ExpectScriptCompilationSuccess = expectScriptCompilationSuccess; + ExpectDomainReload = true; + } + + /// + /// Returns true if the instruction expects a domain reload to occur. + /// + public bool ExpectDomainReload { get; private set; } + /// + /// Returns true if the instruction expects the Unity Editor to be in **Play Mode**. + /// + public bool ExpectedPlaymodeState { get; } + /// + /// Indicates whether a script compilation is expected. + /// + public bool ExpectScriptCompilation { get; private set; } + /// + /// Indicates whether the expected script compilation is expected to succeed. + /// + public bool ExpectScriptCompilationSuccess { get; private set; } + + /// + /// The current active instance of the RecompileScripts yield instruction. + /// + public static RecompileScripts Current { get; private set; } + + /// + /// Perform the multi step instruction of triggering a recompilation of scripts and waiting for its completion. + /// + /// An IEnumerator with the async steps. + /// Throws an exception if the editor does not need to recompile scripts or if the script compilation failed when expected to succeed. + public IEnumerator Perform() + { + Current = this; + + // We need to yield, to give the test runner a chance to prepare for the domain reload + // If the script compilation happens very fast, then EditModeRunner.MoveNextAndUpdateYieldObject will not have a chance to set m_CurrentYieldObject + // This really should be fixed in EditModeRunner.MoveNextAndUpdateYieldObject + yield return null; + + AssetDatabase.Refresh(); + + if (ExpectScriptCompilation && !EditorApplication.isCompiling) + { + Current = null; + throw new Exception("Editor does not need to recompile scripts"); + } + + EditorApplication.UnlockReloadAssemblies(); + + while (EditorApplication.isCompiling) + { + yield return null; + } + + Current = null; + + if (ExpectScriptCompilationSuccess && EditorUtility.scriptCompilationFailed) + { + EditorApplication.LockReloadAssemblies(); + throw new Exception("Script compilation failed"); + } + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/RecompileScripts.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/RecompileScripts.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..f764d6e80c270be298f60ec9d3574a803136b5d8 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/RecompileScripts.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9202fbba95ea8294cb5e718f028f21b0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/WaitForDomainReload.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/WaitForDomainReload.cs new file mode 100644 index 0000000000000000000000000000000000000000..38cb5747a761829430dfd51e4ecfbaf3d26f07f0 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/WaitForDomainReload.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections; +using UnityEditor; +using UnityEditorInternal; + +namespace UnityEngine.TestTools +{ + /// + /// WaitForDomainReload is an that you can yield in Edit Mode tests. It delays the execution of scripts until after an incoming domain reload. If the domain reload results in a script compilation failure, then it throws an exception. + /// + public class WaitForDomainReload : IEditModeTestYieldInstruction + { + /// + /// Create a new instance of the `WaitForDomainReload` yield instruction. + /// + /// + /// [UnitySetUp] + /// public IEnumerator SetUp() + /// { + /// File.Copy("Resources/MyDll.dll", @"Assets/MyDll.dll", true); // Trigger a domain reload. + /// AssetDatabase.Refresh(); + /// yield return new WaitForDomainReload(); + /// } + /// + /// + /// + public WaitForDomainReload() + { + ExpectDomainReload = true; + } + + /// + /// Returns true if the instruction expects a domain reload to occur. + /// + public bool ExpectDomainReload { get;  } + /// + /// Returns true if the instruction expects the Unity Editor to be in **Play Mode**. + /// + public bool ExpectedPlaymodeState { get; } + + /// + /// Perform the multi step action of waiting for a domain reload. + /// + /// An IEnumerator with steps. + /// Throws an exception if script compilation failed or if the expected domain reload did not occur. + public IEnumerator Perform() + { + EditorApplication.UnlockReloadAssemblies(); + + while (InternalEditorUtility.IsScriptReloadRequested() || EditorApplication.isCompiling) + { + yield return null; + } + + // Add this point the domain reload should have occured and stopped any further progress on the instruction. + EditorApplication.LockReloadAssemblies(); + throw new Exception( + EditorUtility.scriptCompilationFailed ? + "Script compilation failed" : + "Expected domain reload, but it did not occur"); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/WaitForDomainReload.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/WaitForDomainReload.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..7fa45cb540efb1f8a1863342ccf6264c7cec671c --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Messages/WaitForDomainReload.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5df3c21c5237c994db89660fbdfee07d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils.meta new file mode 100644 index 0000000000000000000000000000000000000000..78ceec0c28761e0be3efeed9771619a3319b4659 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1f5bbb88ca730434483440cbc0278ef6 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/CachingTestListProvider.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/CachingTestListProvider.cs new file mode 100644 index 0000000000000000000000000000000000000000..ff540e679a0fb13fc5a7a2bab20b76be8c815fbe --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/CachingTestListProvider.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine.TestRunner.NUnitExtensions; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class CachingTestListProvider + { + private readonly ITestListProvider m_InnerTestListProvider; + private readonly ITestListCache m_TestListCache; + private readonly ITestAdaptorFactory m_TestAdaptorFactory; + public CachingTestListProvider(ITestListProvider innerTestListProvider, ITestListCache testListCache, ITestAdaptorFactory testAdaptorFactory) + { + m_InnerTestListProvider = innerTestListProvider; + m_TestListCache = testListCache; + m_TestAdaptorFactory = testAdaptorFactory; + } + + public IEnumerator GetTestListAsync(TestPlatform platform) + { + var testFromCache = m_TestListCache.GetTestFromCacheAsync(platform); + while (testFromCache.MoveNext()) + { + yield return null; + } + + + if (testFromCache.Current != null) + { + yield return testFromCache.Current; + } + else + { + var test = m_InnerTestListProvider.GetTestListAsync(platform); + while (test.MoveNext()) + { + yield return null; + } + + test.Current.ParseForNameDuplicates(); + m_TestListCache.CacheTest(platform, test.Current); + yield return m_TestAdaptorFactory.Create(test.Current); + } + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/CachingTestListProvider.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/CachingTestListProvider.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..57566236e2878ec6d1d654a861549ebfc32a70b4 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/CachingTestListProvider.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 26f3e7301af463c4ca72fa98d59b429e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorAssembliesProxy.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorAssembliesProxy.cs new file mode 100644 index 0000000000000000000000000000000000000000..bc0fe19320812da700b64de3bafe1e8cae2d1aad --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorAssembliesProxy.cs @@ -0,0 +1,13 @@ +using System.Linq; +using UnityEngine.TestTools.Utils; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditorAssembliesProxy : IEditorAssembliesProxy + { + public IAssemblyWrapper[] loadedAssemblies + { + get { return EditorAssemblies.loadedAssemblies.OrderBy(a => a.FullName).Select(x => new EditorAssemblyWrapper(x)).ToArray(); } + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorAssembliesProxy.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorAssembliesProxy.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..fdb1b6c4d6a6fe9b1ae1a366dceb10cbea966efa --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorAssembliesProxy.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f96d0ea807c081145a1170ed1b6d71e0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorAssemblyWrapper.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorAssemblyWrapper.cs new file mode 100644 index 0000000000000000000000000000000000000000..804eb4b1ffcd21c09399590bf00a3ac7cfc8edee --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorAssemblyWrapper.cs @@ -0,0 +1,18 @@ +using System.Reflection; +using UnityEngine.TestTools.Utils; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditorAssemblyWrapper : AssemblyWrapper + { + public EditorAssemblyWrapper(Assembly assembly) + : base(assembly) {} + + public override AssemblyName[] GetReferencedAssemblies() + { + return Assembly.GetReferencedAssemblies(); + } + + public override string Location { get { return Assembly.Location; } } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorAssemblyWrapper.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorAssemblyWrapper.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..70bd58bf2d3ed6000f62dcc22e2f3223ca51efd5 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorAssemblyWrapper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 20cdb37e6fea6d946bbb84d2c923db85 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorCompilationInterfaceProxy.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorCompilationInterfaceProxy.cs new file mode 100644 index 0000000000000000000000000000000000000000..ad0b5ad58531654abffaadfb3ba9bc25268fd4a9 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorCompilationInterfaceProxy.cs @@ -0,0 +1,17 @@ +using UnityEditor.Scripting.ScriptCompilation; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditorCompilationInterfaceProxy : IEditorCompilationInterfaceProxy + { + public ScriptAssembly[] GetAllEditorScriptAssemblies() + { + return EditorCompilationInterface.Instance.GetAllEditorScriptAssemblies(EditorCompilationInterface.GetAdditionalEditorScriptCompilationOptions()); + } + + public PrecompiledAssembly[] GetAllPrecompiledAssemblies() + { + return EditorCompilationInterface.Instance.GetAllPrecompiledAssemblies(); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorCompilationInterfaceProxy.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorCompilationInterfaceProxy.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..ef5ade0a61358a6a1c43f605de044b6a2cef3c6f --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorCompilationInterfaceProxy.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c9b23632c77de204abfe8bf7168d48c0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorLoadedTestAssemblyProvider.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorLoadedTestAssemblyProvider.cs new file mode 100644 index 0000000000000000000000000000000000000000..363c06f9929d200b1b3f37387fc36e1332534e9c --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorLoadedTestAssemblyProvider.cs @@ -0,0 +1,120 @@ +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using UnityEditor.Scripting.ScriptCompilation; +using UnityEngine.TestTools; +using UnityEngine.TestTools.Utils; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class EditorLoadedTestAssemblyProvider : IEditorLoadedTestAssemblyProvider + { + private const string k_NunitAssemblyName = "nunit.framework"; + private const string k_TestRunnerAssemblyName = "UnityEngine.TestRunner"; + internal const string k_PerformanceTestingAssemblyName = "Unity.PerformanceTesting"; + + private readonly IEditorAssembliesProxy m_EditorAssembliesProxy; + private readonly ScriptAssembly[] m_AllEditorScriptAssemblies; + private readonly PrecompiledAssembly[] m_AllPrecompiledAssemblies; + + public EditorLoadedTestAssemblyProvider(IEditorCompilationInterfaceProxy compilationInterfaceProxy, IEditorAssembliesProxy editorAssembliesProxy) + { + m_EditorAssembliesProxy = editorAssembliesProxy; + m_AllEditorScriptAssemblies = compilationInterfaceProxy.GetAllEditorScriptAssemblies(); + m_AllPrecompiledAssemblies = compilationInterfaceProxy.GetAllPrecompiledAssemblies(); + } + + public List GetAssembliesGroupedByType(TestPlatform mode) + { + var assemblies = GetAssembliesGroupedByTypeAsync(mode); + while (assemblies.MoveNext()) + { + } + + return assemblies.Current.Where(pair => mode.IsFlagIncluded(pair.Key)).SelectMany(pair => pair.Value).ToList(); + } + + public IEnumerator>> GetAssembliesGroupedByTypeAsync(TestPlatform mode) + { + IAssemblyWrapper[] loadedAssemblies = m_EditorAssembliesProxy.loadedAssemblies; + + IDictionary> result = new Dictionary>() + { + {TestPlatform.EditMode, new List() }, + {TestPlatform.PlayMode, new List() } + }; + var filteredAssemblies = FilterAssembliesWithTestReference(loadedAssemblies); + + foreach (var loadedAssembly in filteredAssemblies) + { + var assemblyName = new FileInfo(loadedAssembly.Location).Name; + var scriptAssemblies = m_AllEditorScriptAssemblies.Where(x => x.Filename == assemblyName).ToList(); + var precompiledAssemblies = m_AllPrecompiledAssemblies.Where(x => new FileInfo(x.Path).Name == assemblyName).ToList(); + if (scriptAssemblies.Count < 1 && precompiledAssemblies.Count < 1) + { + continue; + } + + var assemblyFlags = scriptAssemblies.Any() ? scriptAssemblies.Single().Flags : precompiledAssemblies.Single().Flags; + var assemblyType = (assemblyFlags & AssemblyFlags.EditorOnly) == AssemblyFlags.EditorOnly ? TestPlatform.EditMode : TestPlatform.PlayMode; + result[assemblyType].Add(loadedAssembly); + yield return null; + } + + yield return result; + } + + private IAssemblyWrapper[] FilterAssembliesWithTestReference(IAssemblyWrapper[] loadedAssemblies) + { + var filteredResults = new Dictionary(); + foreach (var assembly in loadedAssemblies) + { + FilterAssemblyForTestReference(assembly, loadedAssemblies, filteredResults); + } + + return filteredResults.Where(pair => pair.Value).Select(pair => pair.Key).ToArray(); + } + + private void FilterAssemblyForTestReference(IAssemblyWrapper assemblyToFilter, IAssemblyWrapper[] loadedAssemblies, IDictionary filterResults) + { + if (filterResults.ContainsKey(assemblyToFilter)) + { + return; + } + + var references = assemblyToFilter.GetReferencedAssemblies(); + if (references.Any(IsTestReference)) + { + filterResults[assemblyToFilter] = true; + return; + } + + foreach (var reference in references) + { + var referencedAssembly = loadedAssemblies.FirstOrDefault(a => a.Name.Name == reference.Name); + if (referencedAssembly == null) + { + continue; + } + + FilterAssemblyForTestReference(referencedAssembly, loadedAssemblies, filterResults); + + if (filterResults[referencedAssembly]) + { + filterResults[assemblyToFilter] = true; + return; + } + } + + filterResults[assemblyToFilter] = false; + } + + private static bool IsTestReference(AssemblyName assemblyName) + { + return assemblyName.Name == k_NunitAssemblyName || + assemblyName.Name == k_TestRunnerAssemblyName || + assemblyName.Name == k_PerformanceTestingAssemblyName; + } + } +} \ No newline at end of file diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorLoadedTestAssemblyProvider.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorLoadedTestAssemblyProvider.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..efba6a7c95e5387f3eb2d4b7da4a8c874b24d3c7 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/EditorLoadedTestAssemblyProvider.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 033c884ba52437d49bc55935939ef1c6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/IEditorAssembliesProxy.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/IEditorAssembliesProxy.cs new file mode 100644 index 0000000000000000000000000000000000000000..35ec87d0e4be63c4afae44cf2f7dddad1a5077e2 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/IEditorAssembliesProxy.cs @@ -0,0 +1,9 @@ +using UnityEngine.TestTools.Utils; + +namespace UnityEditor.TestTools.TestRunner +{ + internal interface IEditorAssembliesProxy + { + IAssemblyWrapper[] loadedAssemblies { get; } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/IEditorAssembliesProxy.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/IEditorAssembliesProxy.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..ad00f55d890e5554277bb7904a8dceb05b01946f --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/IEditorAssembliesProxy.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 98808b11e78f6c84a841a6b4bc5a29d2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/IEditorCompilationInterfaceProxy.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/IEditorCompilationInterfaceProxy.cs new file mode 100644 index 0000000000000000000000000000000000000000..25defb7832eaddd23191a033d895d1777bdc3be0 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/IEditorCompilationInterfaceProxy.cs @@ -0,0 +1,10 @@ +using UnityEditor.Scripting.ScriptCompilation; + +namespace UnityEditor.TestTools.TestRunner +{ + internal interface IEditorCompilationInterfaceProxy + { + ScriptAssembly[] GetAllEditorScriptAssemblies(); + PrecompiledAssembly[] GetAllPrecompiledAssemblies(); + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/IEditorCompilationInterfaceProxy.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/IEditorCompilationInterfaceProxy.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..2bc608bf40bcdbabb10cc4224fa1136b8c17605b --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/IEditorCompilationInterfaceProxy.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 28c8fcb831e6e734a9f564bc4f495eba +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/IEditorLoadedTestAssemblyProvider.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/IEditorLoadedTestAssemblyProvider.cs new file mode 100644 index 0000000000000000000000000000000000000000..d54bda791e66513409ec928488d356fb91a1a9ad --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/IEditorLoadedTestAssemblyProvider.cs @@ -0,0 +1,12 @@ +using System.Collections.Generic; +using UnityEngine.TestTools; +using UnityEngine.TestTools.Utils; + +namespace UnityEditor.TestTools.TestRunner +{ + internal interface IEditorLoadedTestAssemblyProvider + { + List GetAssembliesGroupedByType(TestPlatform mode); + IEnumerator>> GetAssembliesGroupedByTypeAsync(TestPlatform mode); + } +} \ No newline at end of file diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/IEditorLoadedTestAssemblyProvider.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/IEditorLoadedTestAssemblyProvider.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..cbe48975ffbdaf0ce9f0589e006498c2a060b956 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/IEditorLoadedTestAssemblyProvider.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 936b6288befc460409cfdff3ac92fc95 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/ITestListCache.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/ITestListCache.cs new file mode 100644 index 0000000000000000000000000000000000000000..5df7a784e571d86addd30dcdfbea91561211afcd --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/ITestListCache.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using NUnit.Framework.Interfaces; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + interface ITestListCache + { + void CacheTest(TestPlatform platform, ITest test); + IEnumerator GetTestFromCacheAsync(TestPlatform platform); + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/ITestListCache.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/ITestListCache.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..41943d42122df6ee798d979ed19586933fb57da1 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/ITestListCache.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a704c010bcdb1ec4a9f3417b3c393164 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/ITestListCacheData.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/ITestListCacheData.cs new file mode 100644 index 0000000000000000000000000000000000000000..d11fe475fc363584c1bdee4da300f4c8a06cf4ac --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/ITestListCacheData.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using NUnit.Framework.Interfaces; +using UnityEngine.TestRunner.TestLaunchers; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + interface ITestListCacheData + { + List platforms { get; } + List cachedData { get; } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/ITestListCacheData.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/ITestListCacheData.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..b229c0cbfb5db08700e57207485f0012c7658137 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/ITestListCacheData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7043e9a330ac2d84a80a965ada4589ad +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/ITestListProvider.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/ITestListProvider.cs new file mode 100644 index 0000000000000000000000000000000000000000..b734f5361c4d8346b7c8bce4eac714c50e18c97d --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/ITestListProvider.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; +using NUnit.Framework.Interfaces; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + interface ITestListProvider + { + IEnumerator GetTestListAsync(TestPlatform platform); + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/ITestListProvider.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/ITestListProvider.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..b62929bc61b979ca6f0217607a2f5e73342d45ba --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/ITestListProvider.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 64689f8b25eadac4da519e96f514b653 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListCache.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListCache.cs new file mode 100644 index 0000000000000000000000000000000000000000..e69bfcbc79602c5297de24108a92468f53692d4e --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListCache.cs @@ -0,0 +1,56 @@ +using System.Collections.Generic; +using NUnit.Framework.Interfaces; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine.TestRunner.TestLaunchers; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class TestListCache : ITestListCache + { + private readonly ITestAdaptorFactory m_TestAdaptorFactory; + private readonly IRemoteTestResultDataFactory m_TestResultDataFactory; + private readonly ITestListCacheData m_TestListCacheData; + + public TestListCache(ITestAdaptorFactory testAdaptorFactory, IRemoteTestResultDataFactory testResultDataFactory, ITestListCacheData testListCacheData) + { + m_TestAdaptorFactory = testAdaptorFactory; + m_TestResultDataFactory = testResultDataFactory; + m_TestListCacheData = testListCacheData; + } + + public void CacheTest(TestPlatform platform, ITest test) + { + var index = m_TestListCacheData.platforms.IndexOf(platform); + if (index < 0) + { + m_TestListCacheData.cachedData.Add(test); + m_TestListCacheData.platforms.Add(platform); + } + else + { + m_TestListCacheData.cachedData[index] = test; + } + } + + public IEnumerator GetTestFromCacheAsync(TestPlatform platform) + { + var index = m_TestListCacheData.platforms.IndexOf(platform); + if (index < 0) + { + yield return null; + yield break; + } + + var testData = m_TestListCacheData.cachedData[index]; + yield return m_TestAdaptorFactory.Create(testData); + } + + [Callbacks.DidReloadScripts] + private static void ScriptReloaded() + { + TestListCacheData.instance.cachedData.Clear(); + TestListCacheData.instance.platforms.Clear(); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListCache.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListCache.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..ea8d09669c216a8a6049eadf581994d3d7aa3611 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListCache.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d685d97a1eb004f49afea0cc982ff728 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListCacheData.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListCacheData.cs new file mode 100644 index 0000000000000000000000000000000000000000..175082f1ebff80097ff8bfa093357b773691ff2a --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListCacheData.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; +using NUnit.Framework.Interfaces; +using UnityEngine; +using UnityEngine.TestRunner.TestLaunchers; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class TestListCacheData : ScriptableSingleton, ITestListCacheData + { + [SerializeField] + private List m_Platforms = new List(); + + [SerializeField] + private List m_CachedData = new List(); + + public List platforms + { + get { return m_Platforms; } + } + + public List cachedData + { + get { return m_CachedData; } + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListCacheData.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListCacheData.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..2ad79acaac61b3e34645a2a64bbb0a072ede1077 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListCacheData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f1b6399349763114d9361bc6dfcd025b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListJob.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListJob.cs new file mode 100644 index 0000000000000000000000000000000000000000..0df60c35e63468c1609a5bfed7256fbc90fd4e92 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListJob.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class TestListJob + { + private CachingTestListProvider m_TestListProvider; + private TestPlatform m_Platform; + private Action m_Callback; + private IEnumerator m_ResultEnumerator; + public TestListJob(CachingTestListProvider testListProvider, TestPlatform platform, Action callback) + { + m_TestListProvider = testListProvider; + m_Platform = platform; + m_Callback = callback; + } + + public void Start() + { + m_ResultEnumerator = m_TestListProvider.GetTestListAsync(m_Platform); + EditorApplication.update += EditorUpdate; + } + + private void EditorUpdate() + { + if (!m_ResultEnumerator.MoveNext()) + { + m_Callback(m_ResultEnumerator.Current); + EditorApplication.update -= EditorUpdate; + } + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListJob.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListJob.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..a17c091559380e7c184866f63d78f0809a08175e --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListJob.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dec9066d4afefe444be0dad3f137730d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListProvider.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListProvider.cs new file mode 100644 index 0000000000000000000000000000000000000000..1da846e93ff19d0413db28edd3e58c3258cf3314 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListProvider.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework.Interfaces; +using UnityEngine.TestTools; +using UnityEngine.TestTools.NUnitExtensions; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class TestListProvider : ITestListProvider + { + private readonly EditorLoadedTestAssemblyProvider m_AssemblyProvider; + private readonly UnityTestAssemblyBuilder m_AssemblyBuilder; + + public TestListProvider(EditorLoadedTestAssemblyProvider assemblyProvider, UnityTestAssemblyBuilder assemblyBuilder) + { + m_AssemblyProvider = assemblyProvider; + m_AssemblyBuilder = assemblyBuilder; + } + + public IEnumerator GetTestListAsync(TestPlatform platform) + { + var assembliesTask = m_AssemblyProvider.GetAssembliesGroupedByTypeAsync(platform); + while (assembliesTask.MoveNext()) + { + yield return null; + } + + var assemblies = assembliesTask.Current.Where(pair => platform.IsFlagIncluded(pair.Key)) + .SelectMany(pair => pair.Value.Select(assemblyInfo => Tuple.Create(assemblyInfo.Assembly, pair.Key))).ToArray(); + + var settings = UnityTestAssemblyBuilder.GetNUnitTestBuilderSettings(platform); + var test = m_AssemblyBuilder.BuildAsync(assemblies.Select(a => a.Item1).ToArray(), assemblies.Select(a => a.Item2).ToArray(), settings); + while (test.MoveNext()) + { + yield return null; + } + + yield return test.Current; + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListProvider.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListProvider.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..c0e66d53515ecfd810ae75d29160521be26bc70e --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestRunner/Utils/TestListProvider.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f15cbb987069826429540d0ea0937442 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/ITestSettings.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/ITestSettings.cs new file mode 100644 index 0000000000000000000000000000000000000000..d2720372c553b9b17dcee86c87b8f5d44e7a5776 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/ITestSettings.cs @@ -0,0 +1,22 @@ +using System; + +namespace UnityEditor.TestTools.TestRunner +{ + internal interface ITestSettings : IDisposable + { + ScriptingImplementation? scriptingBackend { get; set; } + + string Architecture { get; set; } + + ApiCompatibilityLevel? apiProfile { get; set; } + + bool? appleEnableAutomaticSigning { get; set; } + string appleDeveloperTeamID { get; set; } + ProvisioningProfileType? iOSManualProvisioningProfileType { get; set; } + string iOSManualProvisioningProfileID { get; set; } + ProvisioningProfileType? tvOSManualProvisioningProfileType { get; set; } + string tvOSManualProvisioningProfileID { get; set; } + + void SetupProjectParameters(); + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/ITestSettings.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/ITestSettings.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..9a8563c95f1d5511a3560b7ae4409cef0990a5c9 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/ITestSettings.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 83eda34b7da01e04aa894f268158b0c0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/ITestSettingsDeserializer.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/ITestSettingsDeserializer.cs new file mode 100644 index 0000000000000000000000000000000000000000..701c91d8f8e1f9b809adb6068728f8c97ebdf6b1 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/ITestSettingsDeserializer.cs @@ -0,0 +1,7 @@ +namespace UnityEditor.TestTools.TestRunner +{ + interface ITestSettingsDeserializer + { + ITestSettings GetSettingsFromJsonFile(string jsonFilePath); + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/ITestSettingsDeserializer.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/ITestSettingsDeserializer.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..72c587e718a77be937dd691ad7b7bf811bd9d868 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/ITestSettingsDeserializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d208a1684f8aa6a40ad91d6aa9600c14 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/TestSettings.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/TestSettings.cs new file mode 100644 index 0000000000000000000000000000000000000000..a5bdf7ad6be9eaca7c7321f7605a688261121686 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/TestSettings.cs @@ -0,0 +1,160 @@ +using System; + +namespace UnityEditor.TestTools.TestRunner +{ + internal class TestSettings : ITestSettings + { + private readonly TestSetting[] m_Settings = + { + new TestSetting( + settings => settings.scriptingBackend, + () => PlayerSettings.GetScriptingBackend(EditorUserBuildSettings.activeBuildTargetGroup), + implementation => PlayerSettings.SetScriptingBackend(EditorUserBuildSettings.activeBuildTargetGroup, implementation.Value)), + new TestSetting( + settings => settings.Architecture, + () => EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android ? PlayerSettings.Android.targetArchitectures.ToString() : null, + architecture => + { + if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android) + { + if (!string.IsNullOrEmpty(architecture)) + { + var targetArchitectures = (AndroidArchitecture)Enum.Parse(typeof(AndroidArchitecture), architecture, true); + PlayerSettings.Android.targetArchitectures = targetArchitectures; + } + } + }), + new TestSetting( + settings => settings.apiProfile, + () => PlayerSettings.GetApiCompatibilityLevel(EditorUserBuildSettings.activeBuildTargetGroup), + implementation => + { + if (Enum.IsDefined(typeof(ApiCompatibilityLevel), implementation.Value)) + { + PlayerSettings.SetApiCompatibilityLevel(EditorUserBuildSettings.activeBuildTargetGroup, + implementation.Value); + } + }), + new TestSetting( + settings => settings.appleEnableAutomaticSigning, + () => PlayerSettings.iOS.appleEnableAutomaticSigning, + enableAutomaticSigning => + { + if (enableAutomaticSigning != null) + PlayerSettings.iOS.appleEnableAutomaticSigning = enableAutomaticSigning.Value; + }), + new TestSetting( + settings => settings.appleDeveloperTeamID, + () => PlayerSettings.iOS.appleDeveloperTeamID, + developerTeam => + { + if (developerTeam != null) + PlayerSettings.iOS.appleDeveloperTeamID = developerTeam; + }), + new TestSetting( + settings => settings.iOSManualProvisioningProfileType, + () => PlayerSettings.iOS.iOSManualProvisioningProfileType, + profileType => + { + if (profileType != null) + PlayerSettings.iOS.iOSManualProvisioningProfileType = profileType.Value; + }), + new TestSetting( + settings => settings.iOSManualProvisioningProfileID, + () => PlayerSettings.iOS.iOSManualProvisioningProfileID, + provisioningUUID => + { + if (provisioningUUID != null) + PlayerSettings.iOS.iOSManualProvisioningProfileID = provisioningUUID; + }), + new TestSetting( + settings => settings.tvOSManualProvisioningProfileType, + () => PlayerSettings.iOS.tvOSManualProvisioningProfileType, + profileType => + { + if (profileType != null) + PlayerSettings.iOS.tvOSManualProvisioningProfileType = profileType.Value; + }), + new TestSetting( + settings => settings.tvOSManualProvisioningProfileID, + () => PlayerSettings.iOS.tvOSManualProvisioningProfileID, + provisioningUUID => + { + if (provisioningUUID != null) + PlayerSettings.iOS.tvOSManualProvisioningProfileID = provisioningUUID; + }), + }; + + private bool m_Disposed; + + public ScriptingImplementation? scriptingBackend { get; set; } + + public string Architecture { get; set; } + + public ApiCompatibilityLevel? apiProfile { get; set; } + + public bool? appleEnableAutomaticSigning { get; set; } + public string appleDeveloperTeamID { get; set; } + public ProvisioningProfileType? iOSManualProvisioningProfileType { get; set; } + public string iOSManualProvisioningProfileID { get; set; } + public ProvisioningProfileType? tvOSManualProvisioningProfileType { get; set; } + public string tvOSManualProvisioningProfileID { get; set; } + + public void Dispose() + { + if (!m_Disposed) + { + foreach (var testSetting in m_Settings) + { + testSetting.Cleanup(); + } + + m_Disposed = true; + } + } + + public void SetupProjectParameters() + { + foreach (var testSetting in m_Settings) + { + testSetting.Setup(this); + } + } + + private abstract class TestSetting + { + public abstract void Setup(TestSettings settings); + public abstract void Cleanup(); + } + + private class TestSetting : TestSetting + { + private T m_ValueBeforeSetup; + private Func m_GetFromSettings; + private Func m_GetCurrentValue; + private Action m_SetValue; + + public TestSetting(Func getFromSettings, Func getCurrentValue, Action setValue) + { + m_GetFromSettings = getFromSettings; + m_GetCurrentValue = getCurrentValue; + m_SetValue = setValue; + } + + public override void Setup(TestSettings settings) + { + m_ValueBeforeSetup = m_GetCurrentValue(); + var newValue = m_GetFromSettings(settings); + if (newValue != null) + { + m_SetValue(newValue); + } + } + + public override void Cleanup() + { + m_SetValue(m_ValueBeforeSetup); + } + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/TestSettings.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/TestSettings.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..23e6f5e21ab45ef49cf811dd39c7dda55b05b5c6 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/TestSettings.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6b32b6725087a0d4bb1670818d26996e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/TestSettingsDeserializer.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/TestSettingsDeserializer.cs new file mode 100644 index 0000000000000000000000000000000000000000..cdba06e962d2b31275e8b9dc795772413e0f9a95 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/TestSettingsDeserializer.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner +{ + /// + /// Handles deserialization of TestSettings from a provided json file path. + /// + internal class TestSettingsDeserializer : ITestSettingsDeserializer + { + private static readonly SettingsMap[] s_SettingsMapping = + { + new SettingsMap("scriptingBackend", (settings, value) => settings.scriptingBackend = value), + new SettingsMap("architecture", (settings, value) => settings.Architecture = value), + new SettingsMap("apiProfile", (settings, value) => settings.apiProfile = value), + new SettingsMap("appleEnableAutomaticSigning", (settings, value) => settings.appleEnableAutomaticSigning = value), + new SettingsMap("appleDeveloperTeamID", (settings, value) => settings.appleDeveloperTeamID = value), + new SettingsMap("iOSManualProvisioningProfileType", (settings, value) => settings.iOSManualProvisioningProfileType = value), + new SettingsMap("iOSManualProvisioningProfileID", (settings, value) => settings.iOSManualProvisioningProfileID = value), + new SettingsMap("tvOSManualProvisioningProfileType", (settings, value) => settings.tvOSManualProvisioningProfileType = value), + new SettingsMap("tvOSManualProvisioningProfileID", (settings, value) => settings.tvOSManualProvisioningProfileID = value), + }; + + private readonly Func m_TestSettingsFactory; + public TestSettingsDeserializer(Func testSettingsFactory) + { + m_TestSettingsFactory = testSettingsFactory; + } + + public ITestSettings GetSettingsFromJsonFile(string jsonFilePath) + { + var text = File.ReadAllText(jsonFilePath); + var settingsDictionary = Json.Deserialize(text) as Dictionary; + + var testSettings = m_TestSettingsFactory(); + if (settingsDictionary == null) + { + return testSettings; + } + + foreach (var settingsMap in s_SettingsMapping) + { + if (!settingsDictionary.ContainsKey(settingsMap.Key)) + { + continue; + } + + if (settingsMap.Type.IsEnum) + { + SetEnumValue(settingsMap.Key, settingsDictionary[settingsMap.Key], settingsMap.Type, value => settingsMap.ApplyToSettings(testSettings, value)); + } + else + { + SetValue(settingsMap.Key, settingsDictionary[settingsMap.Key], settingsMap.Type, value => settingsMap.ApplyToSettings(testSettings, value)); + } + } + + return testSettings; + } + + private abstract class SettingsMap + { + public string Key { get; } + public Type Type { get; } + protected SettingsMap(string key, Type type) + { + Key = key; + Type = type; + } + + public abstract void ApplyToSettings(ITestSettings settings, object value); + } + + private class SettingsMap : SettingsMap + { + private Action m_Setter; + public SettingsMap(string key, Action setter) : base(key, typeof(T)) + { + m_Setter = setter; + } + + public override void ApplyToSettings(ITestSettings settings, object value) + { + m_Setter(settings, (T)value); + } + } + + private static void SetEnumValue(string key, object value, Type type, Action setter) + { + object enumValue; + if (TryGetEnum(value as string, type, out enumValue)) + { + setter(enumValue); + return; + } + + var acceptedValues = string.Join(", ", Enum.GetValues(type).OfType().Select(val => val.ToString()).ToArray()); + + Debug.LogFormat("Could not convert '{0}' argument '{1}' to a valid {2}. Accepted values: {3}.", key, value, type.Name, acceptedValues); + } + + private static bool TryGetEnum(string value, Type type, out object enumValue) + { + try + { + enumValue = Enum.Parse(type, value, true); + return true; + } + catch (Exception) + { + enumValue = null; + return false; + } + } + + private static void SetValue(string key, object value, Type type, Action setter) + { + if (type.IsInstanceOfType(value)) + { + setter(value); + return; + } + + Debug.LogFormat("Could not convert '{0}' argument '{1}' to a valid {2}.", key, value, type.Name); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/TestSettingsDeserializer.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/TestSettingsDeserializer.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..4d50295dec451ffb6e456368cb9c88a3e1d8ec48 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/TestSettings/TestSettingsDeserializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 75e7d7a9a57458841a85fe42d9c9141f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/ITestRunnerApiMapper.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/ITestRunnerApiMapper.cs new file mode 100644 index 0000000000000000000000000000000000000000..f7dcacfe0d8817d2b704af5fe3aec22a3d08a02f --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/ITestRunnerApiMapper.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; +using UnityEditor.TestTools.TestRunner.Api; + +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + interface ITestRunnerApiMapper + { + string GetRunStateFromResultNunitXml(ITestResultAdaptor result); + TestState GetTestStateFromResult(ITestResultAdaptor result); + List FlattenTestNames(ITestAdaptor testsToRun); + TestPlanMessage MapTestToTestPlanMessage(ITestAdaptor testsToRun); + TestStartedMessage MapTestToTestStartedMessage(ITestAdaptor test); + TestFinishedMessage TestResultToTestFinishedMessage(ITestResultAdaptor result); + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/ITestRunnerApiMapper.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/ITestRunnerApiMapper.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..75e0ba237ccd7941a8b765367a03298dd7ec5fda --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/ITestRunnerApiMapper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6de79ae237e51554da96fd28f68b66a6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/IUtpLogger.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/IUtpLogger.cs new file mode 100644 index 0000000000000000000000000000000000000000..bdb96c13b2fd62b559992d33b4e80fbf9a047d9e --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/IUtpLogger.cs @@ -0,0 +1,7 @@ +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + interface IUtpLogger + { + void Log(Message msg); + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/IUtpLogger.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/IUtpLogger.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..dbd33aaca10940fdbca6621df822b321ed30f231 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/IUtpLogger.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9014630255533ed42915965b4065cde8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/IUtpMessageReporter.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/IUtpMessageReporter.cs new file mode 100644 index 0000000000000000000000000000000000000000..c2ddc3d12c2bd3d0a2ab8b3d1364d54ebcfd77c8 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/IUtpMessageReporter.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using UnityEditor.Compilation; +using UnityEditor.TestTools.TestRunner.Api; + +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + internal interface IUtpMessageReporter + { + void ReportTestFinished(ITestResultAdaptor result); + void ReportTestRunStarted(ITestAdaptor testsToRun); + void ReportTestStarted(ITestAdaptor test); + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/IUtpMessageReporter.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/IUtpMessageReporter.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..4c96a902523538262cc47b2463c8e1f093c64a7a --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/IUtpMessageReporter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 952b3dc7b47846947b37c8d3ae46579a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/Message.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/Message.cs new file mode 100644 index 0000000000000000000000000000000000000000..d10a5e4237cd6e4673dce286cabfe8a0829727ca --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/Message.cs @@ -0,0 +1,29 @@ +using System; +using System.Diagnostics; + +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + [Serializable] + internal abstract class Message + { + public string type; + // Milliseconds since unix epoch + public ulong time; + public int version; + public string phase; + public int processId; + + protected Message() + { + version = 2; + phase = "Immediate"; + processId = Process.GetCurrentProcess().Id; + AddTimeStamp(); + } + + public void AddTimeStamp() + { + time = Convert.ToUInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/Message.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/Message.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..bfc702bb83cd0c481097ccec1a37280a0161d0fe --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/Message.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 321dc2c0720f8dd4f9396ecdc12b8746 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestFinishedMessage.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestFinishedMessage.cs new file mode 100644 index 0000000000000000000000000000000000000000..66e18ff8363ac946982fea62d867bc5c6ee4e717 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestFinishedMessage.cs @@ -0,0 +1,18 @@ +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + internal class TestFinishedMessage : Message + { + public string name; + public TestState state; + public string message; + public ulong duration; // milliseconds + public ulong durationMicroseconds; + public string stackTrace; + + public TestFinishedMessage() + { + type = "TestStatus"; + phase = "End"; + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestFinishedMessage.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestFinishedMessage.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..15b951b9a8d35fbb28ef5ebb82d90d70ce46b3e6 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestFinishedMessage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 423fe2ef878fa1140a7e1f7f9e365815 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestPlanMessage.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestPlanMessage.cs new file mode 100644 index 0000000000000000000000000000000000000000..c0a76dad87e27345edd66b276b2f3ba8c891dda1 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestPlanMessage.cs @@ -0,0 +1,14 @@ +using System.Collections.Generic; + +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + internal class TestPlanMessage : Message + { + public List tests; + + public TestPlanMessage() + { + type = "TestPlan"; + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestPlanMessage.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestPlanMessage.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..c057f60c5e0e50e12e480b00f7e98adee2227c7c --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestPlanMessage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 28f79a0d7e64c2345bc46f8c4cf788f8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestRunnerApiMapper.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestRunnerApiMapper.cs new file mode 100644 index 0000000000000000000000000000000000000000..356ff8be89a9168eb48ae8d22b898d985443336d --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestRunnerApiMapper.cs @@ -0,0 +1,93 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Xml; +using UnityEditor.TestTools.TestRunner.Api; + +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + internal class TestRunnerApiMapper : ITestRunnerApiMapper + { + public TestPlanMessage MapTestToTestPlanMessage(ITestAdaptor testsToRun) + { + var testsNames = testsToRun != null ? FlattenTestNames(testsToRun) : new List(); + + var msg = new TestPlanMessage + { + tests = testsNames + }; + + return msg; + } + + public TestStartedMessage MapTestToTestStartedMessage(ITestAdaptor test) + { + return new TestStartedMessage + { + name = test.FullName + }; + } + + public TestFinishedMessage TestResultToTestFinishedMessage(ITestResultAdaptor result) + { + return new TestFinishedMessage + { + name = result.Test.FullName, + duration = Convert.ToUInt64(result.Duration * 1000), + durationMicroseconds = Convert.ToUInt64(result.Duration * 1000000), + message = result.Message, + state = GetTestStateFromResult(result), + stackTrace = result.StackTrace + }; + } + + public string GetRunStateFromResultNunitXml(ITestResultAdaptor result) + { + var doc = new XmlDocument(); + doc.LoadXml(result.ToXml().OuterXml); + return doc.FirstChild.Attributes["runstate"].Value; + } + + public TestState GetTestStateFromResult(ITestResultAdaptor result) + { + var state = TestState.Failure; + + if (result.TestStatus == TestStatus.Passed) + { + state = TestState.Success; + } + else if (result.TestStatus == TestStatus.Skipped) + { + state = TestState.Skipped; + + if (result.ResultState.ToLowerInvariant().EndsWith("ignored")) + state = TestState.Ignored; + } + else + { + if (result.ResultState.ToLowerInvariant().Equals("inconclusive")) + state = TestState.Inconclusive; + + if (result.ResultState.ToLowerInvariant().EndsWith("cancelled") || + result.ResultState.ToLowerInvariant().EndsWith("error")) + state = TestState.Error; + } + + return state; + } + + public List FlattenTestNames(ITestAdaptor test) + { + var results = new List(); + + if (!test.IsSuite) + results.Add(test.FullName); + + if (test.Children != null && test.Children.Any()) + foreach (var child in test.Children) + results.AddRange(FlattenTestNames(child)); + + return results; + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestRunnerApiMapper.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestRunnerApiMapper.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..47634b98a289a34667e471b0feb319d72efce501 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestRunnerApiMapper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2011a59d3f76b3d4a85cb53f945fceee +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestStartedMessage.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestStartedMessage.cs new file mode 100644 index 0000000000000000000000000000000000000000..c21464fc9b24dc1854b420b83d1329b82a287b82 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestStartedMessage.cs @@ -0,0 +1,15 @@ +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + internal class TestStartedMessage : Message + { + public string name; + public TestState state; + + public TestStartedMessage() + { + type = "TestStatus"; + phase = "Begin"; + state = TestState.Inconclusive; + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestStartedMessage.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestStartedMessage.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..18b53d1102b07c3d7150186512f172bb4c05d222 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestStartedMessage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bd3e81baa10021f4d877fa36382bab16 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestState.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestState.cs new file mode 100644 index 0000000000000000000000000000000000000000..223a73d548723ec8c0de2ddd7c5406cfc781cdec --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestState.cs @@ -0,0 +1,13 @@ +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + // This matches the state definitions expected by the Perl code, which in turn matches the NUnit 2 values... + internal enum TestState + { + Inconclusive = 0, + Skipped = 2, + Ignored = 3, + Success = 4, + Failure = 5, + Error = 6 + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestState.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestState.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..ac666417317571f33f00254ca4903f6912a24197 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/TestState.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 77f432980bb30084299a138e15c6f571 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UnityTestProtocolListener.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UnityTestProtocolListener.cs new file mode 100644 index 0000000000000000000000000000000000000000..09daf8dc40a698ddd24803e51a6a0ec4ffaa259d --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UnityTestProtocolListener.cs @@ -0,0 +1,35 @@ +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + internal class UnityTestProtocolListener : ScriptableObject, ICallbacks + { + private IUtpMessageReporter m_UtpMessageReporter; + + public UnityTestProtocolListener() + { + m_UtpMessageReporter = new UtpMessageReporter(new UtpDebugLogger()); + } + + public void RunStarted(ITestAdaptor testsToRun) + { + m_UtpMessageReporter.ReportTestRunStarted(testsToRun); + } + + public void RunFinished(ITestResultAdaptor testResults) + { + // Apparently does nothing :) + } + + public void TestStarted(ITestAdaptor test) + { + m_UtpMessageReporter.ReportTestStarted(test); + } + + public void TestFinished(ITestResultAdaptor result) + { + m_UtpMessageReporter.ReportTestFinished(result); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UnityTestProtocolListener.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UnityTestProtocolListener.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..8ba29bea4be4cf92937c2ad7f2a274a79c35c4aa --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UnityTestProtocolListener.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 900aac3710bc14542a8d164e3f0ff820 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UnityTestProtocolStarter.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UnityTestProtocolStarter.cs new file mode 100644 index 0000000000000000000000000000000000000000..fda5b620cb82ec7a83be1a7f3478631fad967aa2 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UnityTestProtocolStarter.cs @@ -0,0 +1,24 @@ +using System; +using System.Linq; +using UnityEditor.Compilation; +using UnityEditor.TestTools.TestRunner.Api; +using UnityEngine; +using UnityEngine.TestTools; + +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + [InitializeOnLoad] + internal static class UnityTestProtocolStarter + { + static UnityTestProtocolStarter() + { + var commandLineArgs = Environment.GetCommandLineArgs(); + if (commandLineArgs.Contains("-automated") && commandLineArgs.Contains("-runTests")) // wanna have it only for utr run + { + var api = ScriptableObject.CreateInstance(); + var listener = ScriptableObject.CreateInstance(); + api.RegisterCallbacks(listener); + } + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UnityTestProtocolStarter.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UnityTestProtocolStarter.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..540b31e06d17beeb27f214394451aa0e7d818d0f --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UnityTestProtocolStarter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1ac58cb55fc8daf4abd3945a2bbbb0c5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UtpDebuglogger.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UtpDebuglogger.cs new file mode 100644 index 0000000000000000000000000000000000000000..e32f6d282c697372ad94effb17039175f1f8491c --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UtpDebuglogger.cs @@ -0,0 +1,13 @@ +using UnityEngine; + +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + class UtpDebugLogger : IUtpLogger + { + public void Log(Message msg) + { + var msgJson = JsonUtility.ToJson(msg); + Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, null, "\n##utp:{0}", msgJson); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UtpDebuglogger.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UtpDebuglogger.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..7debc237e534fa4671d66282812ca050c32a962b --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UtpDebuglogger.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d0abdd8cb6b29a24c8ee19626ef741b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UtpMessageReporter.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UtpMessageReporter.cs new file mode 100644 index 0000000000000000000000000000000000000000..a9d6a344133b5df7b56d025a8dcd8c05579b2a54 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UtpMessageReporter.cs @@ -0,0 +1,46 @@ +using System.Collections.Generic; +using System.Linq; +using UnityEditor.Compilation; +using UnityEditor.TestTools.TestRunner.Api; + +namespace UnityEditor.TestTools.TestRunner.UnityTestProtocol +{ + internal class UtpMessageReporter : IUtpMessageReporter + { + public ITestRunnerApiMapper TestRunnerApiMapper; + public IUtpLogger Logger; + + public UtpMessageReporter(IUtpLogger utpLogger) + { + TestRunnerApiMapper = new TestRunnerApiMapper(); + Logger = utpLogger; + } + + public void ReportTestRunStarted(ITestAdaptor testsToRun) + { + var msg = TestRunnerApiMapper.MapTestToTestPlanMessage(testsToRun); + + Logger.Log(msg); + } + + public void ReportTestStarted(ITestAdaptor test) + { + if (test.IsSuite) + return; + + var msg = TestRunnerApiMapper.MapTestToTestStartedMessage(test); + + Logger.Log(msg); + } + + public void ReportTestFinished(ITestResultAdaptor result) + { + if (result.Test.IsSuite) + return; + + var msg = TestRunnerApiMapper.TestResultToTestFinishedMessage(result); + + Logger.Log(msg); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UtpMessageReporter.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UtpMessageReporter.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..c818d4fffc5358dbc36ccfdc1c7ba630a7e34f92 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.test-framework@1.1.22/UnityEditor.TestRunner/UnityTestProtocol/UtpMessageReporter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ebcc5f899d9277642868aeda9a17cbaf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: