Skip to content

Commit

Permalink
Use another way to process args; write tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Mr-Python-in-China committed Dec 18, 2024
1 parent ee0bdc3 commit a3fa96f
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 26 deletions.
1 change: 1 addition & 0 deletions cyaron/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@
from .compare_test import TestCompare
from .graph_test import TestGraph
from .vector_test import TestVector
from .general_test import TestGeneral
39 changes: 32 additions & 7 deletions cyaron/tests/compare_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@
class TestCompare(unittest.TestCase):

def setUp(self):
self.original_directory = os.getcwd()
self.temp_directory = tempfile.mkdtemp()
os.chdir(self.temp_directory)

def tearDown(self):
os.chdir(self.original_directory)
try:
shutil.rmtree(self.temp_directory)
except:
Expand Down Expand Up @@ -60,7 +62,10 @@ def test_noipstyle_incorrect(self):
self.assertTrue(False)

result = out.getvalue().strip()
self.assertEqual(result, "test_another_incorrect.out: !!!INCORRECT!!! On line 2 column 7, read 4, expected 3.")
self.assertEqual(
result,
"test_another_incorrect.out: !!!INCORRECT!!! On line 2 column 7, read 4, expected 3."
)

def test_fulltext_program(self):
with open("correct.py", "w") as f:
Expand All @@ -77,14 +82,24 @@ def test_fulltext_program(self):

try:
with captured_output() as (out, err):
Compare.program("python correct.py", "python incorrect.py", std=io, input=io, grader="FullText")
Compare.program("python correct.py",
"python incorrect.py",
std=io,
input=io,
grader="FullText")
except CompareMismatch as e:
self.assertEqual(e.name, 'python incorrect.py')
e = e.mismatch
self.assertEqual(e.content, '2\n')
self.assertEqual(e.std, '1\n')
self.assertEqual(e.content_hash, '53c234e5e8472b6ac51c1ae1cab3fe06fad053beb8ebfd8977b010655bfdd3c3')
self.assertEqual(e.std_hash, '4355a46b19d348dc2f57c046f8ef63d4538ebb936000f3c9ee954a27460dd865')
self.assertEqual(
e.content_hash,
'53c234e5e8472b6ac51c1ae1cab3fe06fad053beb8ebfd8977b010655bfdd3c3'
)
self.assertEqual(
e.std_hash,
'4355a46b19d348dc2f57c046f8ef63d4538ebb936000f3c9ee954a27460dd865'
)
else:
self.assertTrue(False)

Expand All @@ -106,7 +121,10 @@ def test_file_input(self):
io.input_writeln("233")

with captured_output() as (out, err):
Compare.program("python correct.py", std_program="python std.py", input=io, grader="NOIPStyle")
Compare.program("python correct.py",
std_program="python std.py",
input=io,
grader="NOIPStyle")

result = out.getvalue().strip()
correct_out = 'python correct.py: Correct'
Expand All @@ -120,7 +138,11 @@ def test_concurrent(self):
with open('std.py', 'w') as f:
f.write('print({})'.format(16))
with IO() as test:
Compare.program(*[(sys.executable, program) for program in programs], std_program=(sys.executable, 'std.py'), max_workers=None, input=test)
Compare.program(*[(sys.executable, program)
for program in programs],
std_program=(sys.executable, 'std.py'),
max_workers=None,
input=test)

ios = [IO() for i in range(16)]
try:
Expand All @@ -137,7 +159,10 @@ def test_timeout(self):
if sys.version_info >= (3, 3):
with IO() as test:
try:
Compare.program(((sys.executable, '-c', '__import__(\'time\').sleep(10)'), 1), std=test, input=test)
Compare.program(((sys.executable, '-c',
'__import__(\'time\').sleep(10)'), 1),
std=test,
input=test)
except subprocess.TimeoutExpired:
pass
else:
Expand Down
44 changes: 44 additions & 0 deletions cyaron/tests/general_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import subprocess
import unittest
import os
import tempfile
import shutil
import sys


class TestGeneral(unittest.TestCase):

def setUp(self):
self.original_directory = os.getcwd()
self.temp_directory = tempfile.mkdtemp()
os.chdir(self.temp_directory)

def tearDown(self):
os.chdir(self.original_directory)
try:
shutil.rmtree(self.temp_directory)
except:
pass

def test_randseed_arg(self):
with open("test_randseed.py", 'w', encoding='utf-8') as f:
f.write("import cyaron as c\n"
"c.process_args()\n"
"for i in range(10):\n"
" print(c.randint(1,1000000000),end=' ')\n")

env = os.environ.copy()
env['PYTHONPATH'] = self.original_directory + os.pathsep + env.get(
'PYTHONPATH', '')
result = subprocess.run([
sys.executable, 'test_randseed.py',
'--randseed=pinkrabbit147154220'
],
env=env,
stdout=subprocess.PIPE,
universal_newlines=True,
check=True)
self.assertEqual(
result.stdout,
"243842479 490459912 810766286 646030451 191412261 929378523 273000814 982402032 436668773 957169453 "
)
2 changes: 2 additions & 0 deletions cyaron/tests/io_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@
class TestIO(unittest.TestCase):

def setUp(self):
self.original_directory = os.getcwd()
self.temp_directory = tempfile.mkdtemp()
os.chdir(self.temp_directory)

def tearDown(self):
os.chdir(self.original_directory)
try:
shutil.rmtree(self.temp_directory)
except:
Expand Down
29 changes: 10 additions & 19 deletions cyaron/utils.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""Some utility functions."""
import sys
import random
from typing import List, Optional, cast, Any, Dict, Iterable, Tuple, Union
from typing import cast, Any, Dict, Iterable, Tuple, Union

__all__ = [
"ati", "list_like", "int_like", "strtolines", "make_unicode",
"unpack_kwargs", "get_seed_from_argv", "set_seed_from_argv"
"unpack_kwargs", "process_args"
]


Expand Down Expand Up @@ -69,22 +70,12 @@ def unpack_kwargs(
return rv


def get_seed_from_argv(argv: Optional[List[str]] = None):
def process_args():
"""
Calculate a random seed from the command-line arguments,
referencing the implementation of `testlib.h`, but with differing behavior.
https://github.com/MikeMirzayanov/testlib/blob/9ecb11126c16caeda2ba375e0084b3ddd03d4ace/testlib.h#L800
Process the command line arguments.
Now we support:
- randseed: set the random seed
"""
seed = 3905348978240129619
for s in sys.argv[1:] if argv is None else argv:
for c in s:
seed = seed * 0x5DEECE66D + ord(c) + 0xB
seed &= 0xFFFFFFFFFFFF
seed += 0x88A12C38
return seed & 0xFFFFFFFFFFFF


def set_seed_from_argv(argv: Optional[List[str]] = None, version: int = 2):
"""Set the random seed from the command-line arguments."""
random.seed(get_seed_from_argv(argv), version)
for s in sys.argv:
if s.startswith("--randseed="):
random.seed(s.split("=")[1])

0 comments on commit a3fa96f

Please sign in to comment.