def test_copy_into(self): # directory into directory source_d = testdata.create_files({ "foo.txt": testdata.get_words(), "bar/che.txt": testdata.get_words(), }) d = testdata.create_dir() d.copy_into(source_d) self.assertTrue("foo.txt" in d) self.assertTrue("bar/che.txt" in d) source_f = testdata.create_file("foo.txt", testdata.get_words()) # file into directory d = testdata.create_dir() d.copy_into(source_f) self.assertTrue(source_f.basename in d) dest_f = d.get_file(source_f.basename) self.assertEqual(source_f.contents(), dest_f.contents()) # file into file dest_f = testdata.create_file("foo.txt", testdata.get_words()) self.assertNotEqual(source_f.contents(), dest_f.contents()) dest_f.copy_into(source_f) self.assertEqual(source_f.contents(), dest_f.contents()) self.assertTrue(source_f.contents() in dest_f.contents())
def test_content(self): n = Note() plain = testdata.get_words() n.plain = plain self.assertTrue(plain in n.content) html = "<p>{}</p>".format(testdata.get_words()) n.html = html self.assertFalse(plain in n.content) self.assertTrue(HTML(html).plain() in n.content)
def test_drafts(self): project_dir, output_dir = get_dirs({ 'input/_draft/foo.md': testdata.get_words(), 'input/notdraft/_bar.md': testdata.get_words(), }) s = Site(project_dir, output_dir) s.output() self.assertFalse(os.path.isfile(os.path.join(str(output_dir), '_draft', 'index.html'))) self.assertFalse(os.path.isfile(os.path.join(str(output_dir), 'notdraft', 'index.html'))) self.assertEqual(0, len(s.posts))
def test_get_words(self): v = testdata.get_words(word_count=2) self.assertEqual(1, len(re.findall(r'\s+', v))) v = testdata.get_words(word_count=2, as_str=False) self.assertEqual(2, len(v)) v = testdata.get_words(as_str=False) self.assertGreater(len(v), 0) v = testdata.get_words() self.assertNotEqual(u"", v)
def test_list_field(self): from prom import Field, Orm class ListFieldOrm(Orm): interface = self.get_interface() foo = Field(list) with self.assertRaises(ValueError): ListFieldOrm.install() lf = ListFieldOrm() lf.foo = [testdata.get_words(), testdata.get_words()] with self.assertRaises(ValueError): lf.save()
def test_get_file(self): f = testdata.get_file() self.assertFalse(f.exists()) f.write(testdata.get_words()) self.assertTrue(f.exists()) f = testdata.get_file("foobar.txt") self.assertTrue(f.endswith("foobar.txt")) words = testdata.get_words() with f.open("w+") as fp: fp.write(words) self.assertEqual(words, f.contents())
def test_crud(self): nb = Notebook() self.assertIsNone(nb.guid) self.assertIsNone(nb.name) self.assertIsNone(nb.created) self.assertIsNone(nb.updated) name = testdata.get_unicode_words(1) nb.name = name self.assertEqual(name, nb.name) nb.save() self.assertIsNotNone(nb.guid) self.assertEqual(name, nb.name) self.assertIsNotNone(nb.created) self.assertIsNotNone(nb.updated) updated = nb.updated name2 = testdata.get_words(1) nb.name = name2 self.assertNotEqual(name, nb.name) time.sleep(1) nb.save() self.assertEqual(name2, nb.name) self.assertNotEqual(updated, nb.updated)
def get_fields(self, schema, **field_kwargs): """return the fields of orm with randomized data""" fields = {} for k, v in schema.fields.items(): if v.is_pk(): continue if issubclass(v.type, basestring): fields[k] = testdata.get_words() elif issubclass(v.type, int): fields[k] = testdata.get_int32() elif issubclass(v.type, long): fields[k] = testdata.get_int64() elif issubclass(v.type, datetime.datetime): fields[k] = testdata.get_past_datetime() elif issubclass(v.type, float): fields[k] = testdata.get_float() elif issubclass(v.type, bool): fields[k] = True if random.randint(0, 1) == 1 else False else: raise ValueError("{}".format(v.type)) fields.update(field_kwargs) return fields
def test_chunked(self): filepath = testdata.create_file("filename.txt", testdata.get_words(500)) controller_prefix = 'wsgi.post_chunked' c = self.create_client(controller_prefix, [ "import hashlib", "from endpoints import Controller", "class Bodykwargs(Controller):", " def POST(self, **kwargs):", " return hashlib.md5(kwargs['file'].file.read()).hexdigest()", "", "class Bodyraw(Controller):", " def POST(self, **kwargs):", " return len(self.request.body)", "", ]) size = c.post_chunked('/bodyraw', { "foo": "bar", "baz": "che" }, filepath=filepath) self.assertGreater(int(size), 0) with codecs.open(filepath, "rb", encoding="UTF-8") as fp: h1 = hashlib.md5(fp.read().encode("UTF-8")).hexdigest() h2 = c.post_chunked('/bodykwargs', { "foo": "bar", "baz": "che" }, filepath=filepath) self.assertEqual(h1, h2.strip('"'))
def test_crud(self): n = Note() title = testdata.get_ascii() plain = testdata.get_words() n.title = title n.plain = plain n.save() guid = n.guid n.title = testdata.get_ascii() n.plain = testdata.get_words() n.save() self.assertEqual(guid, n.guid) self.assertNotEqual(title, n.title) self.assertNotEqual(plain, n.plain)
def test_message_encode_decode(self): fields = {"foo": testdata.get_words(), "bar": testdata.get_int()} i = self.get_encrypted_interface() im = self.create_message(name="message-lifecycle", interface=i, **fields) cipher_text = im.body im2 = i.create_message(name="message-lifecycle", body=cipher_text) self.assertEqual(fields, im2.fields)
def test_copy_to(self): """https://github.com/Jaymon/testdata/issues/30""" source_d = testdata.create_files({ "foo.txt": testdata.get_words(), "bar/che.txt": testdata.get_words(), }) dest_d = testdata.create_dir() source_d.copy_to(dest_d) self.assertTrue("foo.txt" in dest_d) self.assertTrue("bar/che.txt" in dest_d) source_f = testdata.create_file("foo.txt", testdata.get_words()) dest_f = testdata.get_file() self.assertFalse(dest_f.exists()) source_f.copy_to(dest_f) self.assertEqual(source_f.contents(), dest_f.contents())
def get_count_posts(cls, count): post_files = {} for x in range(count): name = testdata.get_ascii(8) post_files["{}.md".format(name)] = testdata.get_words() s = cls.get_site(post_files) s.compile() return s.posts if len(s.posts) else s.auxs
def test_contents_decode_error(self): base_d = testdata.create_dir() os.chdir(base_d) f = base_d.create_file("bytes.txt", testdata.get_words()) c = testdata.get_contents(f) self.assertTrue(isinstance(c, ContentBytes)) c = testdata.get_contents(f, encoding="UTF-8") self.assertTrue(isinstance(c, ContentString))
def test_digital(self): nit = Item(price=100, body={ "url": testdata.get_url(), "title": testdata.get_words(), "digital": True, "price": 1.0 }, uuid="foo") self.assertTrue(" (digital)" in nit.title)
def test_dup(self): t1 = self.create_instance(name=testdata.get_words(1)) self.assertIsNone(t1.guid) t1.save() self.assertIsNotNone(t1.guid) t2 = self.create_instance(name=t1.name) self.assertIsNone(t2.guid) t2.save() self.assertEqual(t1.guid, t2.guid)
def test_create_files(self): ts = { "foo/1.txt": testdata.get_words(), "foo/2.txt": testdata.get_words(), "/bar/3.txt": testdata.get_words(), "/bar/che/4.txt": testdata.get_words(), } path = testdata.create_files(ts) self.assertEqual(list(path.files()), list(path)) count = 0 for f in path: for rp, v in ts.items(): if rp in f: count += 1 self.assertEqual(v, f.contents()) self.assertLess(0, count)
def test_encode_decode(self): s = testdata.get_words() b = Base64.encode(s) self.assertTrue(isinstance(b, unicode)) self.assertNotEqual(b, s) s2 = Base64.decode(b) self.assertTrue(isinstance(s2, unicode)) self.assertNotEqual(b, s2) self.assertEqual(s, s2)
def test_new_old_price(self): uuid = testdata.get_hash() body = { "url": testdata.get_url(), "title": testdata.get_words(), } oit = WatchlistItem.create(price=10, body=dict(body), uuid=uuid) it = Item(price=1, body=dict(body), uuid=uuid) s = it.html_detail() self.assertTrue("<b>$1.00</b>" in s) self.assertTrue("was <b>$10.00</b>" in s)
def test_tags(self): n = Note() self.assertEqual([], n.tags) n.tags.append(testdata.get_words(1)) n.tags.append(testdata.get_words(1)) for t in n.tags: self.assertTrue(isinstance(t, Tag)) self.assertFalse(t.guid) n.title = testdata.get_words() n.plain = testdata.get_words() n.save() for t in n.tags: self.assertTrue(t.guid) n2 = Note.query.is_guid(n.guid).one() tag_guids = set(t.guid for t in n.tags) tag_guids2 = set(t.guid for t in n2.tags) self.assertEqual(tag_guids, tag_guids2)
def test_is_notebook(self): nb = random.choice(list(Notebook.query.get())) ns1 = self.get_query().is_notebook(nb.name).get() ns2 = self.get_query().is_notebook(nb.guid).get() ns3 = self.get_query().is_notebook(nb).get() self.assertTrue(len(ns1) == len(ns2) == len(ns3)) for ns in [ns1, ns2, ns3]: for n in ns: self.assertEqual(nb.guid, n.notebook_guid) with self.assertRaises(ValueError): self.get_query().is_notebook(testdata.get_words())
def test_href(self): p = get_post({ 'che.txt': testdata.get_words(), 'foo.md': "\n".join([ "full [link](http://foo.com)", "full [path](/bar)", "file [path](che.txt)", "file [relative link](//bar.com)", "" ]) }) html = p.html self.assertRegexpMatches(html, '\"http://foo.com\"') self.assertRegexpMatches(html, '\"//{}/bar\"'.format(p.config.host)) self.assertRegexpMatches(html, '\"//{}/[^\/]+/che.txt\"'.format(p.config.host)) self.assertRegexpMatches(html, '\"//bar.com\"')
def test_async(self): start = time.time() c = Command("sleep 1.0") c.run_async() mid = time.time() r = c.join() stop = time.time() self.assertTrue((stop - start) > 0.5) self.assertTrue((mid - start) < 0.5) self.assertEqual(0, r.returncode) s = testdata.get_words() c = Command("echo {}".format(s)) c.run_async() r = c.join() self.assertEqual(s, r.strip())
def test_response_body_1(self): server = self.create_server(contents=[ "from endpoints import Controller", "class Default(Controller):", " def POST(self, **kwargs):", " content_type = '{};charset={}'.format(kwargs['content_type'], self.encoding)", " self.response.set_header('content-type', content_type)", " return kwargs['body']", ]) body = {'foo': testdata.get_words()} c = self.create_client(json=True) r = c.post('/', {'content_type': 'plain/text', 'body': body}) self.assertEqual(ByteString(body), r._body) self.assertEqual(String(body), r.body) r = c.post('/', {'content_type': 'application/json', 'body': body}) self.assertEqual(json.dumps(body), r.body) r = c.post('/', {'content_type': 'application/json', 'body': {}}) self.assertEqual("{}", r.body)
def get_item(item=None, **kwargs): if item: body = dict(item.newest.body) body.update(kwargs) body.setdefault("uuid", item.uuid) kwargs = body price = kwargs.pop("price", testdata.get_int(1000)) uuid = kwargs.pop("uuid", testdata.get_hash()) kwargs.setdefault("url", testdata.get_url()) kwargs.setdefault("digital", testdata.get_bool()) kwargs.setdefault("image", testdata.get_url()) kwargs.setdefault("title", testdata.get_words()) if isinstance(price, float): kwargs["price"] = price price = int(price * 100.0) else: kwargs["price"] = float(price) * 0.01 it = Item(price=price, body=kwargs, uuid=uuid) return it
def test_contents(self): base_d = testdata.create_dir() os.chdir(base_d) # check scanning failure with self.assertRaises(IOError): c = ContentString("foo", encoding="UTF-8") # check scanning success foo_f = base_d.create_file("testdata/foo.txt", testdata.get_words()) c = ContentString("foo", encoding="UTF-8") self.assertEqual(foo_f.contents(), c) # check passed in directory c = ContentString("foo", base_d.child("testdata"), encoding="UTF-8") self.assertEqual(foo_f.contents(), c) # check direct match c = ContentString("foo.txt", encoding="UTF-8") self.assertEqual(foo_f.contents(), c) # check wrapper c = testdata.get_contents("foo", encoding="UTF-8") self.assertEqual(foo_f.contents(), c)
def test_html(self): n = Note() nb = testdata.random.choice(list(Notebook.query.get())) html_doc = """ <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ self.assertIsNone(n.guid) n.title = testdata.get_words() n.html = html_doc n.notebook = nb n.save() self.assertIsNotNone(n.guid) n2 = Note.query.is_guid(n.guid).one()
def test_truncate(self): """turns out aws descriptions can only be 256 characters""" d = Description(testdata.get_words(200)) self.assertGreater(256, len(d))