'Ensure that field substitutions occur properly in exec_js functions.'

def test_exec_js_field_sub(self):

    class Comment(EmbeddedDocument, ):
        content = StringField(db_field='body')
    class BlogPost(Document, ):
        name = StringField(db_field='doc-name')
        comments = ListField(EmbeddedDocumentField(Comment), db_field='cmnts')
    BlogPost.drop_collection()
    comments1 = [Comment(content='cool'), Comment(content='yay')]
    post1 = BlogPost(name='post1', comments=comments1)
    post1.save()
    comments2 = [Comment(content='nice    stuff')]
    post2 = BlogPost(name='post2', comments=comments2)
    post2.save()
    code = "\n                                function    getComments()    {\n                                                var    comments    =    [];\n                                                db[collection].find(query).forEach(function(doc)    {\n                                                                var    docComments    =    doc[~comments];\n                                                                for    (var    i    =    0;    i    <    docComments.length;    i++)    {\n                                                                                comments.push({\n                                                                                                'document':    doc[~name],\n                                                                                                'comment':    doc[~comments][i][~comments.content]\n                                                                                });\n                                                                }\n                                                });\n                                                return    comments;\n                                }\n                                "
    sub_code = BlogPost.objects._sub_js_fields(code)
    code_chunks = ['doc["cmnts"];', 'doc["doc-name"],', 'doc["cmnts"][i]["body"]']
    for chunk in code_chunks:
        self.assertTrue((chunk in sub_code))
    results = BlogPost.objects.exec_js(code)
    expected_results = [{u'comment': u'cool', u'document': u'post1'}, {u'comment': u'yay', u'document': u'post1'}, {u'comment': u'nice    stuff', u'document': u'post2'}]
    self.assertEqual(results, expected_results)
    code = '{{~comments.content}}'
    sub_code = BlogPost.objects._sub_js_fields(code)
    self.assertEqual('cmnts.body', sub_code)
    BlogPost.drop_collection()
