class PutRequests(APITestCase):
    def setUp(self):
        self.client = APIClient()
        self.user = User(username='******')
        self.user.set_password('test')
        self.user.save()
        self.snippetToUpdate = Snippet(code='print(999)', id=100)
        self.snippetToUpdate.save()

    # Unauthroized access, should delete
    def test_put_not_validated(self):
        request = self.client.put('http://127.0.0.1:8000/snippets/100/', {
            'code': 'print(123)',
        })
        self.assertIsNotNone(request)
        self.assertEqual(request.status_code, 403)

    # Unauthroized access, should delete
    def test_put_not_validated(self):
        self.client.login(username='******', password='******')
        request = self.client.put('http://127.0.0.1:8000/snippets/100/', {
            'code': 'print(123)',
        })
        self.assertIsNotNone(request)
        self.assertEqual(request.status_code, 200)
 def setUp(self):
     self.client = APIClient()
     self.user = User(username='******')
     self.user.set_password('test')
     self.user.save()
     self.snippetToDelete = Snippet(code='print(999)', id=100)
     self.snippetToDelete.save()
Ejemplo n.º 3
0
 def test_snippets(self):
     from snippets.models import Snippet
     s = Snippet(name='test1', snippet='my test snippet')
     s.save()
     tmpl = "{% load snippet_tags %}{% get_snippet test1 %}"
     ctxt = template.Context({})
     out = template.Template(tmpl).render(ctxt)
     self.assertEqual(out, 'my test snippet')
Ejemplo n.º 4
0
 def test_validation_visibilty_fails_with_wrong_input(self):
     # need to include text and slug because validation error
     # will be raised on those and we wouldn't know if its because of visibility
     snippet = Snippet(visibility='AS', text='nothing', slug='nothing')
     # fails django database validation, but error is not raised on database level
     # remember: snippet.save() does not auto call .full_clean
     with self.assertRaises(ValidationError):
         snippet.full_clean()
Ejemplo n.º 5
0
class TestSnippet(TestCase):
    def setUp(self):
        self.snippet = Snippet(code='print "pytest da hora"\n')
        self.snippet.save()

    def test_save(self):
        print(self.snippet.code)
        self.assertEqual(self.snippet.code, 'print "pytest da hora"\n')
    def setUp(self):
        snippet = Snippet(code='foo = "bar"\n')
        snippet.save()

        self.snippet = Snippet(code='print "hello, world"\n')
        self.snippet.save()

        self.serializer = SnippetSerializer(self.snippet)
Ejemplo n.º 7
0
 def create_snippet(code, owner):
     snippet = Snippet(title='test',
                       code=code,
                       linenos=True,
                       language='python',
                       style='friendly',
                       owner=owner)
     snippet.save()
Ejemplo n.º 8
0
    def test_snippets(self):
        from snippets.models import Snippet

        s = Snippet(name="test1", snippet="my test snippet")
        s.save()
        tmpl = "{% load snippet_tags %}{% get_snippet test1 %}"
        ctxt = template.Context({})
        out = template.Template(tmpl).render(ctxt)
        self.assertEqual(out, "my test snippet")
Ejemplo n.º 9
0
def create(request):
  if request.method == "GET":
    form = SnippetForm()  
  elif request.method == "POST":
    form = SnippetForm(request.POST)
    if form.is_valid():
      data = form.cleaned_data
      snippet = Snippet(title=data.get('title'), content=data.get('content'))
      snippet.save()
      return redirect('view',snippet.id)
  return render(request, 'snippets/create.html',{'form':form})
Ejemplo n.º 10
0
class SnippetTestCase(TestCase):
    def setUp(self):
        self.snippet1 = Snippet(code='foo = "bar"\n')
        self.snippet1.save()

        self.snippet2 = Snippet(code='print "hello, world"\n')
        self.snippet2.save()

    def testSerializerSnippet(self):
        # 序列化其中一个实例:
        serializer = SnippetSerializer(self.snippet2)
        print serializer.data
        # {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language':u'python', 'style': u'friendly'}

    def testRenderSnippet(self):
        # 序列化其中一个实例:
        serializer = SnippetSerializer(self.snippet2)
        print serializer.data
        # {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language':u'python', 'style': u'friendly'}

        # 以上代码已将snippet实例转化为Python基本数据类型, 接下来我们完成序列化:
        content = JSONRenderer().render(serializer.data)
        print content
        # '{"pk": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false,    "language": "python", "style": "friendly"}'

    def testCreateSnippet(self):
        # 序列化其中一个实例:
        serializer = SnippetSerializer(self.snippet2)
        print serializer.data
        # {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language':u'python', 'style': u'friendly'}

        # 以上代码已将snippet实例转化为Python基本数据类型, 接下来我们完成序列化:
        content = JSONRenderer().render(serializer.data)
        print content
        # '{"pk": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false,    "language": "python", "style": "friendly"}'

        # 反序列化也是类似的, 首先将stream转为python基本类型:
        stream = BytesIO(content)
        data = JSONParser().parse(stream)

        # 然后我们将它转化为snippet实例:
        serializer = SnippetSerializer(data=data)
        self.assertEqual(serializer.is_valid(), True)
        # True
        print serializer.object
        # <Snippet: Snippet object>

    def testSerializerAllSnippet(self):
        # 当我们输入参数many=True时, serializer还能序列化queryset:

        serializer = SnippetSerializer(Snippet.objects.all(), many=True)
        print serializer.data
    def handle(self, *args, **options):
        Snippet.objects.all().delete()
        print(repr(SnippetSerializer()))

        snippet = Snippet(code='foo = "bar"\n')
        snippet.save()

        snippet = Snippet(code='print "hello, world"\n')
        snippet.save()

        serializer = SnippetSerializer(snippet)
        print('serializer.data')
        print(serializer.data)

        content = JSONRenderer().render(serializer.data)
        print('content')
        print(content)

        stream = BytesIO(content)
        print('stream')
        print(stream)
        data = JSONParser().parse(stream)
        print('data')
        print(data)

        serializer = SnippetSerializer(data=data)
        if serializer.is_valid():
            print('serializer.validated_data')
            print(serializer.validated_data)
            serializer.save()

        serializers = SnippetSerializer(Snippet.objects.all(), many=True)
        print('serializers.data')
        print(serializers.data)
Ejemplo n.º 12
0
class SnippetAddTest(TestCase):
    def setUp(self):
        user = User.objects.create(username='******')
        self.code = 'ps -ef|grep grep'
        self.snippet1 = Snippet(code=self.code, owner=user)
        self.code = 'sudo nmap -p 8000'
        self.snippet2 = Snippet(code=self.code, owner=user)

    def test_add_snippet(self):
        old_object_count = Snippet.objects.count()
        self.snippet1.save()
        new_object_count = Snippet.objects.count()
        self.assertNotEqual(old_object_count, new_object_count)
        self.snippet2.save()
        newer_object_count = Snippet.objects.count()
        self.assertNotEqual(new_object_count, newer_object_count)
Ejemplo n.º 13
0
 def test_it_should_serialize(self):
     user = User(username="******")
     snippet = Snippet(title='title123',owner = user)
     serializer = SnippetSerializer(snippet, context={
         'request': None,
     })
     self.assertTrue(serializer.data["title"]=='title123') 
Ejemplo n.º 14
0
    def test_save_one_test(self):
        snippet = Snippet(code='foo = "bar\n"')
        snippet.save()

        snippet = Snippet(code='print("hello world")\n')
        snippet.save()

        serializer = SnippetSerializer(snippet)
        print(serializer.data)
Ejemplo n.º 15
0
 def test_valid(self):
     params = {
         'title': 'hello world',
         'code': 'print("Hello World")',
         'description': 'Just printing "Hello World"',
     }
     snippet = Snippet()
     form = SnippetForm(params, instance=snippet)
     self.assertTrue(form.is_valid())
Ejemplo n.º 16
0
 def test_slugify_not_called_if_title_is_same(self):
     snippet = Snippet(title="My slug is brand new")
     snippet.save()
     with patch('snippets.models.slugify') as slugify_mock:
         slugify_mock.return_value = 'my-slug-is-changed'
         snippet.views = 0
         snippet.save()
     self.assertFalse(slugify_mock.called)
Ejemplo n.º 17
0
    def test_can_load_snippet_detail_page_properly(self):
        snippet = Snippet(title='title', body='body', author=self.user)
        snippet.save()

        # invalid (not logged in)
        response = self.client.get(reverse('snippet_details', args=(snippet.slug,)), follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertRedirects(response, reverse('home') + '?next=/snippets/%s/' % snippet.slug)

        # invalid (logged-in but snippet is not yet approved and user is not the snippet author)
        self.client.login(username=self.USERNAME2, password=self.PASSWORD2)
        response = self.client.get(reverse('snippet_details', args=(snippet.slug,)), follow=True)
        self.assertEqual(response.status_code, 404)

        # valid (if the author is the current logged in user)
        self.client.login(username=self.USERNAME, password=self.PASSWORD)
        response = self.client.get(reverse('snippet_details', args=(snippet.slug,)))
        self.assertEqual(response.status_code, 200)
        self.assertIsNotNone(response.context['snippet'])
class TestTutorial(TestCase):
    def setUp(self):
        snippet = Snippet(code='foo = "bar"\n')
        snippet.save()

        self.snippet = Snippet(code='print "hello, world"\n')
        self.snippet.save()

        self.serializer = SnippetSerializer(self.snippet)

    def test_serializer(self):
        self.assertEquals(
            self.serializer.data, {
                'pk': 2, 'title': u'', 'code': u'print "hello, world"\n',
                'linenos': False, 'language': u'python', 'style': u'friendly'})

    def test_json_renderer(self):
        content = JSONRenderer().render(self.serializer.data)
        self.assertEquals(
            content,
            '{"pk": 2, "title": "", "code": "print \\"hello, world\\"\\n", '
            '"linenos": false, "language": "python", "style": "friendly"}')

    def test_stream(self):
        content = JSONRenderer().render(self.serializer.data)
        stream = StringIO.StringIO(content)
        data = JSONParser().parse(stream)

        serializer = SnippetSerializer(data=data)
        self.assertTrue(serializer.is_valid())
        for attribute in ('title', 'code', 'linenos', 'language', 'style'):
            self.assertEquals(getattr(serializer.object, attribute),
                              getattr(self.snippet, attribute))

    def test_serialize_all(self):
        serializer = SnippetSerializer(Snippet.objects.all(), many=True)
        self.assertEquals(
            serializer.data,
            [{'pk': 1, 'title': u'', 'code': u'foo = "bar"\n',
              'linenos': False, 'language': u'python',
              'style': u'friendly'},
             {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n',
              'linenos': False, 'language': u'python', 'style': u'friendly'}])
Ejemplo n.º 19
0
def index(request):
    user0 = User.objects.get(username='******')
    print(user0)
    # user = User(username='******', password='******', email='*****@*****.**')
    # user.save()
    snippet = Snippet(owner=user0, code='foo = "bar"\n')
    snippet.save()
    user2 = User.objects.get(username='******')
    snippet2 = Snippet(owner=user2, code='print("hello, world")\n')
    snippet2.save()
    serializer_context = {
        'request': request,
    }
    serializer = SnippetSerializer(snippet, context=serializer_context)
    print('#######################')
    print(type(serializer.data))
    print(serializer.data)
    """
    <class 'rest_framework.utils.serializer_helpers.ReturnDict'>
    {'id': 34, 'title': '', 'code': 'foo = "bar"\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}
    """
    content = JSONRenderer().render(serializer.data)  #把字典类型转化为字节流
    print('#######################')
    print(type(content))
    print(content)
    """
    <class 'bytes'>
    b'{"id":31,"title":"","code":"foo = \\"bar\\"\\n","linenos":false,"language":"python","style":"friendly"}'
    """
    import io
    stream = io.BytesIO(content)
    data = JSONParser().parse(stream)  #把字节流转换为字典类型
    print('#######################')
    print(type(data))
    print(data)
    """
    <class 'dict'>
    {'id': 31, 'title': '', 'code': 'foo = "bar"\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}
    """
    serializer_context2 = {
        'request': request,
    }
    serializer2 = SnippetSerializer(data=data, context=serializer_context2)
    if serializer2.is_valid():
        serializer2.save()
    serializer3 = SnippetSerializer(Snippet.objects.all(), many=True)
    print('#######################')
    print(type(serializer3)
          )  #<class 'rest_framework.serializers.ListSerializer'> 列出所有的值
    print(serializer3.data)
    #Snippet.objects.all().delete()
    return render(request, 'index.html')
Ejemplo n.º 20
0
 def render(self, context):
     
     user_obj = template.resolve_variable('user', context)
     snippet = False
     try:
         snippet = Snippet.objects.get(slug=self.slug)
     except:
         
         # snippet does not exist, so create it, if the user has permission
         if user_obj.has_perm('add_snippet'):
             #TODO validate slug format
             snippet = Snippet(slug=self.slug, html='(new snippet: ' + self.slug + ')')
             snippet.save()
     if snippet:
         if user_obj.has_perm('change_snippet'):
             return '<span class="snippet" data-slug="' + self.slug + '"><a href="/admin/snippets/snippet/' + str(snippet.id) + '">edit</a>' + snippet.html + '</span>'
         else:
             return snippet.html
     else:
         return ''
Ejemplo n.º 21
0
 def test_validation_url_hash_is_unique(self):
     # pk is url_hash
     # alternatively, we can place another assert
     snippet = Snippet(pk='12345678')
     # save does not call full_clean; the model does not seem to care that text is empty (full_clean would)
     # even though by default blank=False and null=False
     snippet.save()
     snippet2_ = Snippet(pk='12345678', text='nothing', slug='nothing')
     with self.assertRaises(ValidationError) as ve:
         snippet2_.full_clean()
     self.assertEqual(
         ve.exception.message_dict,
         {'url_hash': ['Snippet with this Url hash already exists.']})
Ejemplo n.º 22
0
def snippet_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        snippet = Snippet(code='foo = "bar"\n')
        snippet.save()
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        data = json.loads(request.body)
        serializer = SnippetSerializer(data=data)
        logger = logging.getLogger("django")
        logger.info(serializer)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)
Ejemplo n.º 23
0
    def test_delete_snippet(self):
        snippet = Snippet(title='title', body='body', author=self.user)
        snippet.save()

        # invalid (not logged-in)
        response = self.client.post(reverse('snippet_delete', args=(snippet.slug,)))
        self.assertRedirects(response, reverse('home') + '?next=/snippets/title/delete/')

        # invalid (logged-in, not snippet owner)
        self.client.login(username=self.USERNAME2, password=self.PASSWORD2)
        response = self.client.post(reverse('snippet_delete', \
            args=(snippet.slug,)), follow=True)
        self.assertRedirects(response, reverse('user_snippets', args=(self.user2.profile.slug,)))       
        self.assertIn("Sorry you can't delete that snippet because you are not the snippet author.", \
            response.content.replace('&#39;', "'"))

        # valid (logged-in, snippet owner)
        self.client.login(username=self.USERNAME, password=self.PASSWORD)
        response = self.client.post(reverse('snippet_delete', args=(snippet.slug,)))
        self.assertRedirects(response, reverse('snippets'))
class DeleteRequests(APITestCase):
    def setUp(self):
        self.client = APIClient()
        self.user = User(username='******')
        self.user.set_password('test')
        self.user.save()
        self.snippetToDelete = Snippet(code='print(999)', id=100)
        self.snippetToDelete.save()

    # Unauthorized access, request should return a 403
    def test_delete_not_validated(self):
        request = self.client.delete('http://127.0.0.1:8000/snippets/100/')
        self.assertIsNotNone(request)
        self.assertEqual(request.status_code, 403)

    # User can delete this object as they are logged in
    def test_delete_validated(self):
        self.client.login(username='******', password='******')
        request = self.client.delete('http://127.0.0.1:8000/snippets/100/')
        self.assertIsNotNone(request)
        self.assertEqual(request.status_code, 204)
Ejemplo n.º 25
0
 def update(self, instance: Snippet, validated_data):
     """
     Update and return an existing `Snippet` instance. given the validated data.
     """
     instance.title = validated_data.get('title', instance.title)
     instance.code = validated_data.get('code', instance.title)
     instance.linenos = validated_data.get('linenos', instance.title)
     instance.language = validated_data.get('language', instance.title)
     instance.style = validated_data.get('style', instance.title)
     instance.save()
     return instance
    def setUp(self):
        snippet = Snippet(code='foo = "bar"\n')
        snippet.save()

        self.snippet = Snippet(code='print "hello, world"\n')
        self.snippet.save()

        self.serializer = SnippetSerializer(self.snippet)
Ejemplo n.º 27
0
def snippet_new(request):
	if request.method == 'POST':
		# Process Form Input
		title = request.POST.get('title', False)
		desc = request.POST.get('description', False)
		code = request.POST.get('code', False)
		language = request.POST.get('language', False)

		#Save created snippet
		snippet = Snippet()
		snippet.title = title
		snippet.description = desc
		snippet.code = code
		snippet.language = language
		snippet.creation_date = datetime.now()
		snippet.save()
		
		return redirect('snippets:list')
	elif request.method == 'GET':
		return TemplateResponse(request, 'snippets/snippet_new.html', {})
Ejemplo n.º 28
0
def restore_object(attrs, instance=None):
    """
    Create or update a new snippet instance.
    """
    if instance:
        # Update existing instance
        instance.title = attrs['title']
        instance.code = attrs['code']
        instance.linenos = attrs['linenos']
        instance.language = attrs['language']
        instance.style = attrs['style']
        return instance

    # Create new instance
    return Snippet(**attrs)
Ejemplo n.º 29
0
def snippets(request, id=None):
    api = API(request)
    if id is None:
        if api.get:
            snippets = Snippet.list()
            return api.respond(
            	snippets,
            	detail=0,
            	template='snippets/list.html',
            	context={
            		'languages':['js','jl','py','r']
            	}
            )
    else:
        if api.get:
            snippet = Snippet.get(
                id=id
            )
            return api.respond(
            	snippet,
            	template='snippets/get.html'
            )
        elif api.put:
            snippet = Snippet.put(
                user=request.user,
                id=id,
                spec=api.data
            )
            return api.respond(
            	snippet,
            	detail=0
            )

    raise API.MethodNotAllowedError(
        method=request.method
    )
Ejemplo n.º 30
0
    def restore_object(self, attrs, instance=None):
        """
        Create or update a new snippet instance, given a dictionary
        of deserialized field values.

        If we didn't define restore_object, then deserializing would
        simply return a dictionary of items.
        """
        if instance:
            # Update existing instance
            instance.title = attrs.get('title', instance.title)
            instance.code = attrs.get('code', instance.code)
            instance.value = attrs.get('value', instance.value)
            return instance

        return Snippet(**attrs)
Ejemplo n.º 31
0
    def setUp(self):
        user = User()
        user.password = '******'
        user.email = '*****@*****.**'
        user.save()

        for snippet_id in range(self.number_of_snippets):
            snippet = Snippet()
            snippet.code = 'Snippet: #{snippet_id}'
            snippet.owner_id = user.pk
            snippet.save()
Ejemplo n.º 32
0
    def restore_object(self, attrs, instance=None):
        """
		Create or update a new snippet instance, given a dictionary
		of deserialized field values.

		Note that if we don't define this method, then deserializing
		data will simply return a dictionary of items.
		"""
        owner = serializers.Field(source='owner.username')
        if instance:
            instance.title = attrs.get('title', instance.title)
            instance.code = attrs.get('code', instance.code)
            instance.linenos = attrs.get('linenos', instance.linenos)
            instance.language = attrs.get('language', instance.language)
            instance.style = attrs.get('style', instance.style)
            return instance
        return Snippet(**attrs)
Ejemplo n.º 33
0
    def restore_object(self, attrs, instance=None):
        """
        Create or update a new snippet instance, given a dictionary of
        deserialized field values

        If this method isn't defined, deserializing data will simply return a
        dictionary of items
        """
        if instance:
            # update existing instance
            instance.title = attrs.get('title', instance.title)
            instance.code = attrs.get('code', instance.code)
            instance.linenos = attrs.get('language', instance.language)
            instance.style = attrs.get('style', instance.style)
            return instance

        # create a new instance
        return Snippet(**attrs)
Ejemplo n.º 34
0
    def restore_object(self, attrs, instance=None):
        """
        Create or update a new snippet instance, given a dict
        of deserialized field values.

        Note that if we don't define this method, then 
        deserealizing data will simply return a dict of items.
        """
        if instance:
            # Update existing instance
            instance.title = attrs.get('title', instance.title)
            instance.code = attrs.get('code', instance.code)
            instance.linenos = attrs.get('linenos', instance.linenos)
            instance.language = attrs.get('language', instance.language)
            instance.style = attrs.get('style', instance.style)
            return instance

        # Create new instance
        return Snippet(**attrs)
Ejemplo n.º 35
0
def savesnippet(request, pk=0):

    mediaDict = determineMediaType(request.POST['media'])

    e = Snippet(title = request.POST['title'],
                url = request.POST['url'],
                text = request.POST['text'],
                media = mediaDict['media'],
                mediaType = mediaDict['mediaType'],
                date_added = datetime.datetime.now(),
                last_viewed = datetime.datetime.now(),
                width = 'w0',
                height = 100)

    if request.POST['title'] == '' and request.POST['text'] == '' and request.POST['media'] != '':
        e.width = 'w0'

    if mediaDict['mediaType'] == '2':
        e.width = 'w1'

    if pk != 0:
        s = get_object_or_404(Snippet, pk=pk)
        s.delete()

    e.save(force_insert=True)

    tags = request.POST['tags']
    if tags != '':
        tagslist = tags.split(',')

        for tag in tagslist:
            try:
                k = Keyword.objects.get(keyword=tag)
            except ObjectDoesNotExist:
                k = Keyword(keyword=tag)
                k.save()

            e.keywords.add(k)
    

    e.save()

    return redirect('/snippets/')
Ejemplo n.º 36
0
 def post(self, request, *args, **kwargs):
     # Si el usuario no estaba autenticado, no puede crear snippets. Lo redireccionamos al login
     if request.user.is_authenticated == False:
         return redirect('/login')
     # Usuario que va a crear el snippet
     snippet_user = User.objects.get(username=request.user.username)
     # Datos del formulario de creación del snippet
     form = SnippetForm(request.POST, instance=Snippet(user=snippet_user))
     # Si el formulario es válido
     if form.is_valid():
         # Nombre y descripción del snippet para enviar el mail
         snippet_name = form.cleaned_data['name']
         snippet_description = form.cleaned_data['description']
         # Creamos el snippet
         form.save()
         # Enviar mail al usuario avisando que se creó un snippet
         # Se usa celery para hacer el proceso de envío de mail de forma asincrónica
         sendEmailInSnippetCreation.delay(snippet_name, snippet_description,
                                          snippet_user.email)
     # Redirecciono al index
     return redirect('/')
Ejemplo n.º 37
0
def working_with_serializers():
    from snippets.models import Snippet
    from snippets.serializers import SnippetSerializer
    from rest_framework.renderers import JSONRenderer
    from rest_framework.parsers import JSONParser

    code1 = '''foo = "bar"
    def display(var):
        print("var:", var)'''
    code2 = '''const foo = "bar"
    const display = var => console.log("var:", var)
    '''
    # create Snippet instances
    snippet1 = Snippet(code=code1)
    snippet2 = Snippet(code=code2)

    # save instances to the db
    snippet1.save()
    snippet2.save()

    # create serializer instance
    serializer = SnippetSerializer(snippet)
    serializer.data  # => in native types (not exactly but this will do)

    # render the data to json
    content = JSONRenderer().render(serializer.data)  # => bytes(string)

    # deserialization
    from django.utils.six import BytesIO

    stream = BytesIO(content)
    data = JSONParser().parse(stream)  # => absolute native types

    # restore native types to fully populated object instance
    serializer = SnippetSerializer(data=data)
    serializer.is_valid()  # => True
    serializer.validated_data  # => almost native types
    serializer.save()  # => save instance to db
class TestTutorial(TestCase):
    def setUp(self):
        snippet = Snippet(code='foo = "bar"\n')
        snippet.save()

        self.snippet = Snippet(code='print "hello, world"\n')
        self.snippet.save()

        self.serializer = SnippetSerializer(self.snippet)

    def test_serializer(self):
        self.assertEquals(
            self.serializer.data,
            {
                "pk": 2,
                "title": u"",
                "code": u'print "hello, world"\n',
                "linenos": False,
                "language": u"python",
                "style": u"friendly",
            },
        )

    def test_json_renderer(self):
        content = JSONRenderer().render(self.serializer.data)
        self.assertEquals(
            content,
            '{"pk": 2, "title": "", "code": "print \\"hello, world\\"\\n", '
            '"linenos": false, "language": "python", "style": "friendly"}',
        )

    def test_stream(self):
        content = JSONRenderer().render(self.serializer.data)
        stream = StringIO.StringIO(content)
        data = JSONParser().parse(stream)

        serializer = SnippetSerializer(data=data)
        self.assertTrue(serializer.is_valid())
        for attribute in ("title", "code", "linenos", "language", "style"):
            self.assertEquals(getattr(serializer.object, attribute), getattr(self.snippet, attribute))

    def test_serialize_all(self):
        serializer = SnippetSerializer(Snippet.objects.all(), many=True)
        self.assertEquals(
            serializer.data,
            [
                {
                    "pk": 1,
                    "title": u"",
                    "code": u'foo = "bar"\n',
                    "linenos": False,
                    "language": u"python",
                    "style": u"friendly",
                },
                {
                    "pk": 2,
                    "title": u"",
                    "code": u'print "hello, world"\n',
                    "linenos": False,
                    "language": u"python",
                    "style": u"friendly",
                },
            ],
        )
Ejemplo n.º 39
0
def snippet(slug):
    """ Retrieves a named text snippet """
    try:
        return Snippet.get(slug)
    except Exception:
        return ''
Ejemplo n.º 40
0
    def test_saving_and_retrieving_items(self):
        first_snippet = Snippet()
        first_snippet.snippet = 'first snippet'
        first_snippet.source_title = 'The Book of Me'
        first_snippet.author = 'David Gillies'
        first_snippet.source_type = 'Book'
        first_snippet.notes = 'bla'
        first_snippet.save()

        second_snippet = Snippet()
        second_snippet.snippet = 'second snippet'
        second_snippet.source_title = 'The Book of Her'
        second_snippet.author = 'Mrs Gillies'
        second_snippet.source_type = 'Book'
        second_snippet.notes = 'bla'
        second_snippet.save()

        saved_snippets = Snippet.objects.all()
        self.assertEqual(saved_snippets.count(), 2)

        first_saved_snippet = saved_snippets[0]
        second_saved_snippet = saved_snippets[1]
        self.assertEqual(first_saved_snippet.author, 'David Gillies')
        self.assertEqual(second_saved_snippet.author, 'Mrs Gillies')
Ejemplo n.º 41
0
from snippets.models import Snippet
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser

snippet=Snippet(code='foo="bar"\n')
snippet.save()

snippet=Snippet(code='print "hello,world"\n')
snippet.save()

Ejemplo n.º 42
0
 def get_visible_snippets(self):
     return Snippet.get_visible(self.user)