python第三方库系列之十八--python/django test库

        django是属于python语音的web框架,要说django測试。也能够先说说python的測试。django能够用python的方式測试,当然,django也基于python封装了一个自己的測试库。
一、python的測试--unitest库
def my_func(a_list, idx):
    return a_list[idx]
    
import unittest
class MyFuncTestCase(unittest.TestCase):
    def testBasic(self):
        a = ['larry', 'curly', 'moe']
        self.assertEqual(my_func(a, 0), 'larry')
        self.assertEqual(my_func(a, 1), 'curly')
二、django的測试--django.utils.unittest库、django.test.client库。
(1)django.utils.unittest库
更高级一点的,引用django封装的unittest。对了,这样写另一个优点:測试case能够直接用django里的models,操作数据库很方便。


from django.utils import unittest
from myapp.models import Animal


class AnimalTestCase(unittest.TestCase):
    def setUp(self):
        self.lion = Animal.objects.create(name="lion", sound="roar")
        self.cat = Animal.objects.create(name="cat", sound="meow")


    def test_animals_can_speak(self):
        """Animals that can speak are correctly identified"""
        self.assertEqual(self.lion.speak(), 'The lion says "roar"')
        self.assertEqual(self.cat.speak(), 'The cat says "meow"')
(2)django.test.client库
django作为web的服务端,要測试其服务功能,必须模拟一个client,訪问服务端验证
from django.utils import unittest
from django.test.client import Client


class SimpleTest(unittest.TestCase):
    def setUp(self):
        # Every test needs a client.
        self.client = Client()


    def test_details(self):
        # Issue a GET request.
        response = self.client.get('/customer/details/')


        # Check that the response is 200 OK.
        self.assertEqual(response.status_code, 200)


        # Check that the rendered context contains 5 customers.
        self.assertEqual(len(response.context['customers']), 5)
或者更高级的。直接用from django.test.TestCase
from django.test import TestCase


class SimpleTest(TestCase):
    def test_details(self):
        response = self.client.get('/customer/details/')
        self.assertEqual(response.status_code, 200)


    def test_index(self):
        response = self.client.get('/customer/index/')
        self.assertEqual(response.status_code, 200)
三、数据库使用

假设你測试时候还须要初始化数据库,那TestCase.fixtures帮你了。

并且,django在測试的时候。会帮你创建一个新的数据库名为:test_原有数据库名。

这样能够防止真实数据库被弄脏。

你能够这样初始化你的数据库:
from django.test import TestCase
from myapp.models import Animal


class AnimalTestCase(TestCase):
    fixtures = ['mammals.json', 'birds']


    def setUp(self):
        # Test definitions as before.
        call_setup_methods()


    def testFluffyAnimals(self):
        # A test that uses the fixtures.
        call_some_test_code()
那有人就问了:mammals.json怎么来的呢?格式是什么呢?事实上这个文件是用python manage.py dumpdata命令来的。有关这个命令的文档请google之。文件格式大概例如以下:
[
    {
        "pk": 1,
        "model": "apps.animal",
        "fields": {
            "status": 1,
            "gmt_modified": "2015-07-06T14:05:38",
            "gmt_created": "2015-07-06T14:05:38",
            "alive": 1,
            "info": ""
        }
    },
    {
        "pk": 2,
        "model": "apps.animal",
        "fields": {
            "status": 0,
            "gmt_modified": "2015-07-06T14:05:53",
            "gmt_created": "2015-07-06T14:05:53",
            "alive": 1,
            "info": ""
        }
    }
]
事实上,django.test这个包还有非常多其它的功能,不能一一列举,具体能够看django官方文档。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是Python+Django实现FP-Growth算法的代码示例: 首先是FP树的实现: ```python class TreeNode: def __init__(self, name, count, parent_node): self.name = name self.count = count self.parent_node = parent_node self.children = {} self.node_link = None def increase_count(self, count): self.count += count ``` 接下来是构建FP树的函数: ```python def create_tree(dataset, min_support): header_table = {} for transaction in dataset: for item in transaction: header_table[item] = header_table.get(item, 0) + dataset[transaction] for item in list(header_table.keys()): if header_table[item] < min_support: del(header_table[item]) freq_item_set = set(header_table.keys()) if len(freq_item_set) == 0: return None, None for item in header_table: header_table[item] = [header_table[item], None] root_node = TreeNode('Null Set', 1, None) for transaction, count in dataset.items(): local_dict = {} for item in transaction: if item in freq_item_set: local_dict[item] = header_table[item][0] if len(local_dict) > 0: ordered_items = [v[0] for v in sorted(local_dict.items(), key=lambda p: p[1], reverse=True)] update_tree(ordered_items, root_node, header_table, count) return root_node, header_table ``` 接下来是更新FP树的函数: ```python def update_tree(items, curr_node, header_table, count): if items[0] in curr_node.children: curr_node.children[items[0]].increase_count(count) else: curr_node.children[items[0]] = TreeNode(items[0], count, curr_node) if header_table[items[0]][1] is None: header_table[items[0]][1] = curr_node.children[items[0]] else: update_header(header_table[items[0]][1], curr_node.children[items[0]]) if len(items) > 1: update_tree(items[1:], curr_node.children[items[0]], header_table, count) ``` 接下来是更新头指针表的函数: ```python def update_header(node_to_test, target_node): while(node_to_test.node_link is not None): node_to_test = node_to_test.node_link node_to_test.node_link = target_node ``` 然后是挖掘频繁项集的函数: ```python def mine_tree(header_table, min_support, prefix, freq_item_list): sorted_items = [v[0] for v in sorted(header_table.items(), key=lambda p: p[1][0])] for item in sorted_items: new_freq_set = prefix.copy() new_freq_set.add(item) freq_item_list.append(new_freq_set) conditional_pattern_bases = find_prefix_path(item, header_table[item][1]) conditional_tree, conditional_header_table = create_tree(conditional_pattern_bases, min_support) if conditional_header_table is not None: mine_tree(conditional_header_table, min_support, new_freq_set, freq_item_list) ``` 最后是寻找条件模式基的函数: ```python def find_prefix_path(item, node): conditional_pattern_bases = {} while node is not None: prefix_path = [] ascend_tree(node, prefix_path) if len(prefix_path) > 1: conditional_pattern_bases[frozenset(prefix_path[1:])] = node.count node = node.node_link return conditional_pattern_bases def ascend_tree(node, prefix_path): if node.parent_node is not None: prefix_path.append(node.name) ascend_tree(node.parent_node, prefix_path) ``` 以上就是Python+Django实现FP-Growth算法的代码示例,可以根据实际需求进行修改和优化,以适应不同的数据集和应用场景。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值