首页 文章 精选 留言 我的

精选列表

搜索[类],共10000篇文章
优秀的个人博客,低调大师

每日一博 | Go testing.common 公共类源码剖析

简介 我们知道单元测试函数需要传递一个testing.T类型的参数,而性能测试函数需要传递一个testing.B类型的参数,该参数可用于控制测试的流程,比如标记测试失败等。 testing.T和testing.B属于testing包中的两个数据类型,该类型提供一系列的方法用于控制函数执行流程,考虑到二者有一定的相似性,所以Go实现时抽象出一个testing.common作为一个基础类型,而testing.T和testing.B则属于testing.common的扩展。 本节,我们重点看testing.common,通过其成员及方法,来了解其实现原理。 数据结构 // common holds the elements common between T and B and // captures common methods such as Errorf. type common struct { mu sync.RWMutex // guards this group of fields output []byte // Output generated by test or benchmark. w io.Writer // For flushToParent. ran bool // Test or benchmark (or one of its subtests) was executed. failed bool // Test or benchmark has failed. skipped bool // Test of benchmark has been skipped. done bool // Test is finished and all subtests have completed. helpers map[string]struct{} // functions to be skipped when writing file/line info chatty bool // A copy of the chatty flag. finished bool // Test function has completed. hasSub int32 // written atomically raceErrors int // number of races detected during test runner string // function name of tRunner running the test parent *common level int // Nesting depth of test or benchmark. creator []uintptr // If level > 0, the stack trace at the point where the parent called t.Run. name string // Name of test or benchmark. start time.Time // Time test or benchmark started duration time.Duration barrier chan bool // To signal parallel subtests they may start. signal chan bool // To signal a test is done. sub []*T // Queue of subtests to be run in parallel. } common.mu 读写锁,仅用于控制本数据内的成员访问。 common.output 存储当前测试产生的日志,每产生一条日志则追加到该切片中,待测试结束后再一并输出。 common.w 子测试执行结束需要把产生的日志输送到父测试中的output切片中,传递时需要考虑缩进等格式调整,通过w把日志传递到父测试。 common.ran 仅表示是否已执行过。比如,跟据某个规范筛选测试,如果没有测试被匹配到的话,则common.ran为false,表示没有测试运行过。 common.failed 如果当前测试执行失败,则置为true。 common.skipped 标记当前测试是否已跳过。 common.done 表示当前测试及其子测试已结束,此状态下再执行Fail()之类的方法标记测试状态会产生panic。 common.helpers 标记当前为函数为help函数,其中打印的日志,在记录日志时不会显示其文件名及行号。 common.chatty 对应命令行中的-v参数,默认为false,true则打印更多详细日志。 common.finished 如果当前测试结束,则置为true。 common.hasSub 标记当前测试是否包含子测试,当测试使用t.Run()方法启动子测试时,t.hasSub则置为1。 common.raceErrors 竞态检测错误数。 common.runner 执行当前测试的函数名。 common.parent 如果当前测试为子测试,则置为父测试的指针。 common.level 测试嵌套层数,比如创建子测试时,子测试嵌套层数就会加1。 common.creator 测试函数调用栈。 common.name 记录每个测试函数名,比如测试函数TestAdd(t *testing.T), 其中t.name即“TestAdd”。 测试结束,打印测试结果会用到该成员。 common.start 记录测试开始的时间。 common.duration 记录测试所花费的时间。 common.barrier 用于控制父测试和子测试执行的channel,如果测试为Parallel,则会阻塞等待父测试结束后再继续。 common.signal 通知当前测试结束。 common.sub 子测试列表。 成员方法 common.Name() // Name returns the name of the running test or benchmark. func (c *common) Name() string { return c.name } 该方法直接返回common结构体中存储的名称。 common.Fail() // Fail marks the function as having failed but continues execution. func (c *common) Fail() { if c.parent != nil { c.parent.Fail() } c.mu.Lock() defer c.mu.Unlock() // c.done needs to be locked to synchronize checks to c.done in parent tests. if c.done { panic("Fail in goroutine after " + c.name + " has completed") } c.failed = true } Fail()方法会标记当前测试为失败,然后继续运行,并不会立即退出当前测试。如果是子测试,则除了标记当前测试结果外还通过c.parent.Fail()来标记父测试失败。 common.FailNow() func (c *common) FailNow() { c.Fail() c.finished = true runtime.Goexit() } FailNow()内部会调用Fail()标记测试失败,还会标记测试结束并退出当前测试协程。 可以简单的把一个测试理解为一个协程,FailNow()只会退出当前协程,并不会影响其他测试协程,但要保证在当前测试协程中调用FailNow()才有效,不可以在当前测试创建的协程中调用该方法。 common.log() func (c *common) log(s string) { c.mu.Lock() defer c.mu.Unlock() c.output = append(c.output, c.decorate(s)...) } common.log()为内部记录日志入口,日志会统一记录到common.output切片中,测试结束时再统一打印出来。 日志记录时会调用common.decorate()进行装饰,即加上文件名和行号,还会做一些其他格式化处理。 调用common.log()的方法,有Log()、Logf()、Error()、Errorf()、Fatal()、Fatalf()、Skip()、Skipf()等。 注意:单元测试中记录的日志只有在执行失败或指定了-v参数才会打印,否则不会打印。而在性能测试中则总是被打印出来,因为是否打印日志有可能影响性能测试结果。 common.Log(args ...interface{}) func (c *common) Log(args ...interface{}) { c.log(fmt.Sprintln(args...)) } common.Log()方法用于记录简单日志,通过fmt.Sprintln()方法生成日志字符串后记录。 common.Logf(format string, args ...interface{}) func (c *common) Logf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) } common.Logf()方法用于格式化记录日志,通过fmt.Sprintf()生成字符串后记录。 common.Error(args ...interface{}) // Error is equivalent to Log followed by Fail. func (c *common) Error(args ...interface{}) { c.log(fmt.Sprintln(args...)) c.Fail() } common.Error()方法等同于common.Log()+common.Fail(),即记录日志并标记失败,但测试继续进行。 common.Errorf(format string, args ...interface{}) // Errorf is equivalent to Logf followed by Fail. func (c *common) Errorf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) c.Fail() } common.Errorf()方法等同于common.Logf()+common.Fail(),即记录日志并标记失败,但测试继续进行。 common.Fatal(args ...interface{}) // Fatal is equivalent to Log followed by FailNow. func (c *common) Fatal(args ...interface{}) { c.log(fmt.Sprintln(args...)) c.FailNow() } common.Fatal()方法等同于common.Log()+common.FailNow(),即记录日志、标记失败并退出当前测试。 common.Fatalf(format string, args ...interface{}) // Fatalf is equivalent to Logf followed by FailNow. func (c *common) Fatalf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) c.FailNow() } common.Fatalf()方法等同于common.Logf()+common.FailNow(),即记录日志、标记失败并退出当前测试。 common.skip() func (c *common) skip() { c.mu.Lock() defer c.mu.Unlock() c.skipped = true } common.skip()方法标记当前测试为已跳过状态,比如测试中检测到某种条件,不再继续测试。该函数仅标记测试跳过,与测试结果无关。测试结果仍然取决于common.failed。 common.SkipNow() func (c *common) SkipNow() { c.skip() c.finished = true runtime.Goexit() } common.SkipNow()方法标记测试跳过,并标记测试结束,最后退出当前测试。 common.Skip(args ...interface{}) // Skip is equivalent to Log followed by SkipNow. func (c *common) Skip(args ...interface{}) { c.log(fmt.Sprintln(args...)) c.SkipNow() } common.Skip()方法等同于common.Log()+common.SkipNow()。 common.Skipf(format string, args ...interface{}) // Skipf is equivalent to Logf followed by SkipNow. func (c *common) Skipf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) c.SkipNow() } common.Skipf()方法等同于common.Logf() + common.SkipNow()。 common.Helper() // Helper marks the calling function as a test helper function. // When printing file and line information, that function will be skipped. // Helper may be called simultaneously from multiple goroutines. func (c *common) Helper() { c.mu.Lock() defer c.mu.Unlock() if c.helpers == nil { c.helpers = make(map[string]struct{}) } c.helpers[callerName(1)] = struct{}{} } common.Helper()方法标记当前函数为help函数,所谓help函数,即其中打印的日志,不记录help函数的函数名及行号,而是记录上一层函数的函数名和行号。 赠人玫瑰手留余香,如果觉得不错请给个赞~ 本篇文章已归档到GitHub项目,求星~ 点我即达

优秀的个人博客,低调大师

java加密工具类,可设置对应的加解密key

public class AesEncryptUtil { //使用AES-128-CBC加密模式,key需要为16位,key和iv可以相同! private static String KEY ="whshenke20180606"; private static String IV ="whshenke20180606"; /** * 加密方法 * @param data 要加密的数据 * @param key 加密key * @param iv 加密iv * @return 加密的结果 * @throws Exception */ public static String encrypt(String data, String key, String iv) throws Exception { try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");//"算法/模式/补码方式" int blockSize = cipher.getBlockSize(); byte[] dataBytes = data.getBytes(); int plaintextLength = dataBytes.length; if (plaintextLength % blockSize != 0) { plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize)); } byte[] plaintext = new byte[plaintextLength]; System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length); SecretKeySpec keyspec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); byte[] encrypted = cipher.doFinal(plaintext); return Base64Util.encode(encrypted); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 解密方法 * @param data 要解密的数据 * @param key 解密key * @param iv 解密iv * @return 解密的结果 * @throws Exception whshenke20180606 */ public static String desEncrypt(String data, String key, String iv) { try { byte[] encrypted1 = Base64Util.decode(data); Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original, "UTF-8"); return originalString; } catch (Exception e) { //e.printStackTrace(); return null; } } /** * 使用默认的key和iv加密 * @param data * @return * @throws Exception */ public static String encrypt(String data) throws Exception { return encrypt(data, KEY, IV); } /** * 使用默认的key和iv解密 * @param data * @return * @throws Exception */ public static String desEncrypt(String data){ return desEncrypt(data, KEY, IV); } /** * 测试 */ public static void main(String args[]) throws Exception { //KNnAbiCvFxispeG+wS01jA== //KNnAbiCvFxispeG+wS01jA== //KNnAbiCvFxispeG+wS01jA== String test = "测试"; String data = null; String key = "dufy20170329java"; String iv = "dufy20170329java"; // data = encrypt(test, key, iv); //KNnAbiCvFxispeG+wS01jA== System.out.println(data); System.out.println(desEncrypt("8XguKV2aprVwg4UqEie7f9gkr7xDaSKrGZZD7x1J3uISWkvQAtpq8hpkskwi V+8bJmRcmQWIZ4sRom37GB7w7O4AH+HjH5ixViJ7k6bx+oEFVWSmIqKEj4e5 lMcyXgcXpTB8IGnt1WKS2p7Qnn+cjA==", key, iv)); } }

优秀的个人博客,低调大师

Python爬虫之多线程下载程序类电子书

近段时间,笔者发现一个神奇的网站:http://www.allitebooks.com/ ,该网站提供了大量免费的编程方面的电子书,是技术爱好者们的福音。其页面如下: 那么我们是否可以通过Python来制作爬虫来帮助我们实现自动下载这些电子书呢?答案是yes. 笔者在空闲时间写了一个爬虫,主要利用urllib.request.urlretrieve()函数和多线程来下载这些电子书。 首先呢,笔者的想法是先将这些电子书的下载链接网址储存到本地的txt文件中,便于永久使用。其Python代码(Ebooks_spider.py)如下, 该代码仅下载第一页的10本电子书作为示例: # -*- coding:utf-8 -*- # 本爬虫用来下载http://www.allitebooks.com/中的电子书 # 本爬虫将需要下载的书的链接写入txt文件,便于永久使用 # 网站http://www.allitebooks.com/提供编程方面的电子书 # 导入必要的模块 import urllib.request from bs4 import BeautifulSoup # 获取网页的源代码 def get_content(url): html = urllib.request.urlopen(url) content = html.read().decode('utf-8') html.close() return content # 将762个网页的网址储存在list中 base_url = 'http://www.allitebooks.com/' urls = [base_url] for i in range(2, 762): urls.append(base_url + 'page/%d/' % i) # 电子书列表,每一个元素储存每本书的下载地址和书名 book_list =[] # 控制urls的数量,避免书下载过多导致空间不够!!! # 本例只下载前3页的电子书作为演示 # 读者可以通过修改url[:3]中的数字,爬取自己想要的网页书,最大值为762 for url in urls[:1]: try: # 获取每一页书的链接 content = get_content(url) soup = BeautifulSoup(content, 'lxml') book_links = soup.find_all('div', class_="entry-thumbnail hover-thumb") book_links = [item('a')[0]['href'] for item in book_links] print('\nGet page %d successfully!' % (urls.index(url) + 1)) except Exception: book_links = [] print('\nGet page %d failed!' % (urls.index(url) + 1)) # 如果每一页书的链接获取成功 if len(book_links): for book_link in book_links: # 下载每一页中的电子书 try: content = get_content(book_link) soup = BeautifulSoup(content, 'lxml') # 获取每本书的下载网址 link = soup.find('span', class_='download-links') book_url = link('a')[0]['href'] # 如果书的下载链接获取成功 if book_url: # 获取书名 book_name = book_url.split('/')[-1] print('Getting book: %s' % book_name) book_list.append(book_url) except Exception as e: print('Get page %d Book %d failed' % (urls.index(url) + 1, book_links.index(book_link))) # 文件夹 directory = 'E:\\Ebooks\\' # 将书名和链接写入txt文件中,便于永久使用 with open(directory+'book.txt', 'w') as f: for item in book_list: f.write(str(item)+'\n') print('写入txt文件完毕!') 可以看到,上述代码主要爬取的是静态页面,因此效率非常高!运行该程序,显示结果如下: 在book.txt文件中储存了这10本电子书的下载地址,如下: 接着我们再读取这些下载链接,用urllib.request.urlretrieve()函数和多线程来下载这些电子书。其Python代码(download_ebook.py)如下: # -*- coding:utf-8 -*- # 本爬虫读取已写入txt文件中的电子书的链接,并用多线程下载 import time from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED import urllib.request # 利用urllib.request.urlretrieve()下载PDF文件 def download(url): # 书名 book_name = 'E:\\Ebooks\\'+url.split('/')[-1] print('Downloading book: %s'%book_name) # 开始下载 urllib.request.urlretrieve(url, book_name) print('Finish downloading book: %s'%book_name) #完成下载 def main(): start_time = time.time() # 开始时间 file_path = 'E:\\Ebooks\\book.txt' # txt文件路径 # 读取txt文件内容,即电子书的链接 with open(file_path, 'r') as f: urls = f.readlines() urls = [_.strip() for _ in urls] # 利用Python的多线程进行电子书下载 # 多线程完成后,进入后面的操作 executor = ThreadPoolExecutor(len(urls)) future_tasks = [executor.submit(download, url) for url in urls] wait(future_tasks, return_when=ALL_COMPLETED) # 统计所用时间 end_time = time.time() print('Total cost time:%s'%(end_time - start_time)) main() 运行上述代码,结果如下: 再去文件夹中查看文件: 可以看到这10本书都已成功下载,总共用时327秒,每本书的平均下载时间为32.7,约半分钟,而这些书的大小为87.7MB,可见效率相当高的! 怎么样,看到爬虫能做这些多有意思的事情,不知此刻的你有没有心动呢?心动不如行动,至理名言~~ 本次代码已上传github, 地址为: https://github.com/percent4/Examples-of-Python-Spiders . 注意:本人现已开通两个微信公众号: 用Python做数学(微信号为:python_math)以及轻松学会Python爬虫(微信号为:easy_web_scrape), 欢迎大家关注哦~~

优秀的个人博客,低调大师

Swift的类,及存储属性,计算发发样码

进入机械的学习模式, 就是把代友敲完。 以期能加深些记忆。 struct Resolution { var width = 0 var height = 0 } class VideoMode { var resolution = Resolution() var interlaced = false var frameRate = 0.0 var name: String? } let someResolution = Resolution(width: 640, height: 480) let someVideoMode = VideoMode() print("The width of someResolution is \(someResolution.width)") someVideoMode.resolution.width = 1280 print("The width of someVedioMode is \(someVideoMode.resolution.width)") let hd = Resolution(width: 1920, height: 1080) var cinema = hd cinema.width = 2048 print("cienma is now \(cinema.width) pixels wide") print("hd is still \(hd.width) pixels width") enum CompassPoint { case North, South, East, West } var currentDirection = CompassPoint.West let rememberedDirection = currentDirection currentDirection = .East if rememberedDirection == .West { print("The remembered direction is still .West") } let tenEighty = VideoMode() tenEighty.resolution = hd tenEighty.interlaced = true tenEighty.name = "1080i" tenEighty.frameRate = 25.0 let alsoTenEighty = tenEighty alsoTenEighty.frameRate = 30.0 print("The frameRate property of tenEighty is now \(tenEighty.frameRate)") struct Point { var x = 0.0, y = 0.0 } struct Size { var width = 0.0, height = 0.0 } struct Rect { var origin = Point() var size = Size() var center: Point { get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point(x: centerX, y: centerY) } set(newCenter) { origin.x = newCenter.x - (size.width / 2) origin.y = newCenter.y - (size.height / 2) } } } var square = Rect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 10.0, height: 10.0)) let initialSquareCenter = square.center square.center = Point(x: 15.0, y: 15.0) print("square.origin is now at (\(square.origin.x), \(square.origin.y))") class StepCounter { var totalSteps: Int = 0 { willSet(newTotalSteps) { print("About to set totalSteps to \(newTotalSteps)") } didSet { if totalSteps > oldValue { print("Added \(totalSteps - oldValue) steps") } } } } let stepCounter = StepCounter() stepCounter.totalSteps = 200 stepCounter.totalSteps = 360 stepCounter.totalSteps = 896 struct SomeStructure { static var storedTypeProperty = "Some value" static var computedTypeProperty: Int { return 1 } } enum SomeEnumeration { static var storedTypeProperty = "Some value" static var computedTypeProperty: Int { return 6 } } class SomeClass { static var storedTypeProperty = "Some value" static var computedTypeProperty: Int { return 27 } class var overrideableComputedTypeProperty: Int { return 107 } } print(SomeStructure.storedTypeProperty) SomeStructure.storedTypeProperty = "Another value" print(SomeStructure.storedTypeProperty) print(SomeEnumeration.computedTypeProperty) print(SomeClass.computedTypeProperty)

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

用户登录
用户注册
修改密码
忘记密码