def test_wkhtmltopdf(self):
"""Should run wkhtmltopdf to generate a PDF"""
title = 'A test template.'
template = loader.get_template('sample.html')
temp_file = render_to_temporary_file(template, context={'title': title})
try:
# Standard call
pdf_output = wkhtmltopdf(pages=[temp_file.name])
self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output)
# Single page
pdf_output = wkhtmltopdf(pages=temp_file.name)
self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output)
# Unicode
pdf_output = wkhtmltopdf(pages=[temp_file.name], title=u'?')
self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output)
# Invalid arguments
self.assertRaises(CalledProcessError,
wkhtmltopdf, pages=[])
finally:
temp_file.close()
python类b()的实例源码
def test_pdf_template_view_unicode(self, show_content=False):
"""Test PDFTemplateView with unicode content."""
view = UnicodeContentPDFTemplateView.as_view(
filename=self.pdf_filename,
show_content_in_browser=show_content,
template_name=self.template
)
# As PDF
request = RequestFactory().get('/')
response = view(request)
self.assertEqual(response.status_code, 200)
response.render()
fileheader = self.attached_fileheader
if show_content:
fileheader = self.inline_fileheader
self.assertEqual(response['Content-Disposition'],
fileheader.format(self.pdf_filename))
# not sure how we can test this as the contents is all encoded...
# best we can do for the moment is check it's a pdf and it worked.
# self.assertTrue('?' in response.content)
self.assertTrue(response.content.startswith(b'%PDF-'))
self.assertTrue(response.content.endswith(b'%%EOF\n'))
def test_post(self):
# Build a fake file
fake_file = ContentFile(b("A boring example document"))
fake_file.name = 'test.txt'
# Submit
post_data = {
'title': "Test document",
'file': fake_file,
}
response = self.client.post(reverse('wagtaildocs:add'), post_data)
# User should be redirected back to the index
self.assertRedirects(response, reverse('wagtaildocs:index'))
# Document should be created, and be placed in the root collection
self.assertTrue(models.Document.objects.filter(title="Test document").exists())
root_collection = Collection.get_first_root_node()
self.assertEqual(
models.Document.objects.get(title="Test document").collection,
root_collection
)
def test_post(self):
# Build a fake file
fake_file = ContentFile(b("A boring example document"))
fake_file.name = 'test.txt'
# Submit
post_data = {
'title': "Test document",
'file': fake_file,
}
response = self.client.post(reverse('wagtaildocs:add'), post_data)
# User should be redirected back to the index
self.assertRedirects(response, reverse('wagtaildocs:index'))
# Document should be created in the 'evil plans' collection,
# despite there being no collection field in the form, because that's the
# only one the user has access to
self.assertTrue(models.Document.objects.filter(title="Test document").exists())
self.assertEqual(
models.Document.objects.get(title="Test document").collection,
self.evil_plans_collection
)
def test_post(self):
# Build a fake file
fake_file = ContentFile(b("A boring example document"))
fake_file.name = 'test.txt'
# Submit title change
post_data = {
'title': "Test document changed!",
'file': fake_file,
}
response = self.client.post(reverse('wagtaildocs:edit', args=(self.document.id,)), post_data)
# User should be redirected back to the index
self.assertRedirects(response, reverse('wagtaildocs:index'))
# Document title should be changed
self.assertEqual(models.Document.objects.get(id=self.document.id).title, "Test document changed!")
def test_post(self):
# Build a fake file
fake_file = ContentFile(b("A boring example document"))
fake_file.name = 'test.txt'
# Submit
post_data = {
'title': "Test document",
'file': fake_file,
}
response = self.client.post(reverse('wagtaildocs:chooser_upload'), post_data)
# Check that the response is a javascript file saying the document was chosen
self.assertTemplateUsed(response, 'wagtaildocs/chooser/document_chosen.js')
self.assertContains(response, "modal.respond('documentChosen'")
# Document should be created
self.assertTrue(models.Document.objects.filter(title="Test document").exists())
def test_post(self):
# Build a fake file
fake_file = ContentFile(b("A boring example document"))
fake_file.name = 'test.txt'
# Submit
post_data = {
'title': "Test document",
'file': fake_file,
}
response = self.client.post(reverse('wagtaildocs:chooser_upload'), post_data)
# Check that the response is a javascript file saying the document was chosen
self.assertTemplateUsed(response, 'wagtaildocs/chooser/document_chosen.js')
self.assertContains(response, "modal.respond('documentChosen'")
# Document should be created
doc = models.Document.objects.filter(title="Test document")
self.assertTrue(doc.exists())
# Document should be in the 'evil plans' collection
self.assertEqual(doc.get().collection, self.evil_plans_collection)
def add_document(self, **params):
# Build a fake file
fake_file = ContentFile(b("A boring example document"))
fake_file.name = 'test.txt'
# Submit
post_data = {
'title': "Test document",
'file': fake_file,
}
post_data.update(params)
response = self.client.post(reverse('wagtaildocs:add'), post_data)
# User should be redirected back to the index
self.assertRedirects(response, reverse('wagtaildocs:index'))
# Document should be created
doc = models.Document.objects.filter(title=post_data['title'])
self.assertTrue(doc.exists())
return doc.first()
def post_shopify_webhook(self, topic = None, domain = None, data = None, headers = None, send_hmac = True):
"""
Simulate a webhook being sent to the application's webhook endpoint with the provided parameters.
"""
# Set defaults.
domain = 'test.myshopify.com' if domain is None else domain
data = {} if data is None else data
headers = {} if headers is None else headers
# Dump data as a JSON string.
data = json.dumps(data)
# Add required headers.
headers['HTTP_X_SHOPIFY_TEST'] = 'true'
headers['HTTP_X_SHOPIFY_SHOP_DOMAIN'] = domain
# Add optional headers.
if topic:
headers['HTTP_X_SHOPIFY_TOPIC'] = topic
if send_hmac:
headers['HTTP_X_SHOPIFY_HMAC_SHA256'] = six.text_type(get_hmac(six.b(data), settings.SHOPIFY_APP_API_SECRET))
return self.client.post(self.webhook_url, data = data, content_type = 'application/json', **headers)
def test_filepreviews_generate_when_creating_doc(self):
setup_mock()
PreviewableDocument.objects.create(
title='Test document',
file=ContentFile(b('Hello world'), 'test1.txt')
)
self.assertEqual(len(responses.calls), 1)
def test_filepreviews_generate_when_updating_file(self):
setup_mock()
document = PreviewableDocument.objects.create(
title='Test document',
file=ContentFile(b('Hello world'), 'test1.txt')
)
document.file = ContentFile(b('Hello world'), 'test2.txt')
document.save()
self.assertEqual(len(responses.calls), 2)
def test_filepreviews_doesnt_generate_if_settings_not_enabled(self):
setup_mock()
self.settings.api_key = ''
self.settings.api_secret = ''
self.settings.save()
PreviewableDocument.objects.create(
title='Test document',
file=ContentFile(b('Hello world'), 'test1.txt')
)
self.assertEqual(len(responses.calls), 0)
def test_wkhtmltopdf_with_unicode_content(self):
"""A wkhtmltopdf call should render unicode content properly"""
title = u'?'
template = loader.get_template('unicode.html')
temp_file = render_to_temporary_file(template, context={'title': title})
try:
pdf_output = wkhtmltopdf(pages=[temp_file.name])
self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output)
finally:
temp_file.close()
def test_pdf_template_view(self, show_content=False):
"""Test PDFTemplateView."""
view = PDFTemplateView.as_view(filename=self.pdf_filename,
show_content_in_browser=show_content,
template_name=self.template,
footer_template=self.footer_template)
# As PDF
request = RequestFactory().get('/')
response = view(request)
self.assertEqual(response.status_code, 200)
response.render()
fileheader = self.attached_fileheader
if show_content:
fileheader = self.inline_fileheader
self.assertEqual(response['Content-Disposition'],
fileheader.format(self.pdf_filename))
self.assertTrue(response.content.startswith(b'%PDF-'))
self.assertTrue(response.content.endswith(b'%%EOF\n'))
# As HTML
request = RequestFactory().get('/?as=html')
response = view(request)
self.assertEqual(response.status_code, 200)
response.render()
self.assertFalse(response.has_header('Content-Disposition'))
self.assertTrue(response.content.startswith(b'<html>'))
# POST
request = RequestFactory().post('/')
response = view(request)
self.assertEqual(response.status_code, 405)
def setUp(self):
self.source = BytesIO(six.b('file-contents'))
def test_not_image(self):
"""
Non-images raise an exception.
"""
self.assertRaises(
IOError,
source_generators.pil_image, BytesIO(six.b('not an image')))
def test_activation_nonexistent_key(self):
"""
Attempting to activate with a non-existent key (i.e., one not
associated with any account) fails.
"""
# Due to the way activation keys are constructed during
# registration, this will never be a valid key.
invalid_key = hashlib.sha1(six.b('foo')).hexdigest()
self.failIf(RegistrationProfile.objects.activate_user(invalid_key))
def test_post_with_collections(self):
root_collection = Collection.get_first_root_node()
evil_plans_collection = root_collection.add_child(name="Evil plans")
# Build a fake file
fake_file = ContentFile(b("A boring example document"))
fake_file.name = 'test.txt'
# Submit
post_data = {
'title': "Test document",
'file': fake_file,
'collection': evil_plans_collection.id,
}
response = self.client.post(reverse('wagtaildocs:add'), post_data)
# User should be redirected back to the index
self.assertRedirects(response, reverse('wagtaildocs:index'))
# Document should be created, and be placed in the Evil Plans collection
self.assertTrue(models.Document.objects.filter(title="Test document").exists())
root_collection = Collection.get_first_root_node()
self.assertEqual(
models.Document.objects.get(title="Test document").collection,
evil_plans_collection
)
def setUp(self):
self.login()
# Build a fake file
fake_file = ContentFile(b("A boring example document"))
fake_file.name = 'test.txt'
# Create a document to edit
self.document = models.Document.objects.create(title="Test document", file=fake_file)
def setUp(self):
self.login()
# Create a document for running tests on
self.doc = Document.objects.create(
title="Test document",
file=ContentFile(b("Simple text document")),
)
def test_add_post(self):
"""
This tests that a POST request to the add view saves the document and returns an edit form
"""
response = self.client.post(reverse('wagtaildocs:add_multiple'), {
'files[]': SimpleUploadedFile('test.png', b"Simple text document"),
}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
# Check response
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertTemplateUsed(response, 'wagtaildocs/multiple/edit_form.html')
# Check document
self.assertIn('doc', response.context)
self.assertEqual(response.context['doc'].title, 'test.png')
self.assertTrue(response.context['doc'].file_size)
# check that it is in the root collection
doc = Document.objects.get(title='test.png')
root_collection = Collection.get_first_root_node()
self.assertEqual(doc.collection, root_collection)
# Check form
self.assertIn('form', response.context)
self.assertEqual(response.context['form'].initial['title'], 'test.png')
# Check JSON
response_json = json.loads(response.content.decode())
self.assertIn('doc_id', response_json)
self.assertIn('form', response_json)
self.assertIn('success', response_json)
self.assertEqual(response_json['doc_id'], response.context['doc'].id)
self.assertTrue(response_json['success'])
# form should not contain a collection chooser
self.assertNotIn('Collection', response_json['form'])
def edit_document(self, **params):
# Build a fake file
fake_file = ContentFile(b("A boring example document"))
fake_file.name = 'test.txt'
# Create a document without tags to edit
document = models.Document.objects.create(title="Test document", file=fake_file)
# Build another fake file
another_fake_file = ContentFile(b("A boring example document"))
another_fake_file.name = 'test.txt'
# Submit
post_data = {
'title': "Test document changed!",
'file': another_fake_file,
}
post_data.update(params)
response = self.client.post(reverse('wagtaildocs:edit', args=(document.id,)), post_data)
# User should be redirected back to the index
self.assertRedirects(response, reverse('wagtaildocs:index'))
# Document should be changed
doc = models.Document.objects.filter(title=post_data['title'])
self.assertTrue(doc.exists())
return doc.first()
def test_content(self):
self.assertEqual(b"".join(self.get().streaming_content), b"A boring example document")
def test_add_post_with_collections(self):
"""
This tests that a POST request to the add view saves the document
and returns an edit form, when collections are active
"""
root_collection = Collection.get_first_root_node()
evil_plans_collection = root_collection.add_child(name="Evil plans")
response = self.client.post(reverse('wagtaildocs:add_multiple'), {
'files[]': SimpleUploadedFile('test.png', b"Simple text document"),
'collection': evil_plans_collection.id
}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
# Check response
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertTemplateUsed(response, 'wagtaildocs/multiple/edit_form.html')
# Check document
self.assertIn('doc', response.context)
self.assertEqual(response.context['doc'].title, 'test.png')
self.assertTrue(response.context['doc'].file_size)
# check that it is in the 'evil plans' collection
doc = Document.objects.get(title='test.png')
root_collection = Collection.get_first_root_node()
self.assertEqual(doc.collection, evil_plans_collection)
# Check form
self.assertIn('form', response.context)
self.assertEqual(response.context['form'].initial['title'], 'test.png')
# Check JSON
response_json = json.loads(response.content.decode())
self.assertIn('doc_id', response_json)
self.assertIn('form', response_json)
self.assertIn('success', response_json)
self.assertEqual(response_json['doc_id'], response.context['doc'].id)
self.assertTrue(response_json['success'])
# form should contain a collection chooser
self.assertIn('Collection', response_json['form'])