如何编写可测试的bash shell代码? [英] How to write unit testable bash shell code?

查看:109
本文介绍了如何编写可测试的bash shell代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在OOP大学中,有很多关于如何设计和重构的信息代码以使其易于进行单元测试.但我想知道如何应用/翻译这些原则/做法(使

In the OOP universum, there is a lot of information on how to desgin and refactor code to make it unit testing friendly. But I wonder, how to apply/translate those principles/practices (make mocking easier etc.) to shell scripting, which is obviously different programming.

我必须处理非常庞大的代码库;许多可执行和不可执行的过程,大型函数,较大的全局状态,许多环境变量,以及通过重定向/管道和(不必要)使用外部实用程序进行各处(不必要的)进程间通信和文件处理.

I have to tackle a very huge code base; many executable and non-executable procedures, large functions, big global state, many environment variables, and everywhere (unnecessary) interprocess communication and file handling through redirection/pipelines and (unnecessary) use of external utilities.

如何重构shell代码(或在一开始就对其进行设计),以便能够使用bats和嘲笑插件之类的框架进行良好的"自动化单元测试?

How to refactor shell code (or design it in the beginning) to be able to make "good" automated unit tests with a framework like bats and a mocking-plugin?

推荐答案

单元测试用于隔离代码中的发现错误.但是,典型的shell代码主要是与其他可执行文件或操作系统的交互. Shell代码交互中存在的问题类型朝着以下方向发展:我是否以正确的顺序用正确格式的参数值以正确的顺序调用正确的可执行文件,并且输出的形式是我期望的形式要测试所有这些,您不应该应用单元测试,而应该进行集成测试.

Unit-testing is for findings bugs in the isolated code. Typical shell code, however, is dominated by interactions with other executables or the operating system. The type of problems that lies in interactions in shell code goes in the direction of, am I calling the right executables in the right order with the arguments in the right order with properly formatted argument values, and are the outputs in the form I expect them to be etc. To test all this, you should not apply unit-testing, but integration testing instead.

但是,有一些适合单元测试的shell代码.例如,这是在外壳内执行计算或执行字符串操作的代码.我什至认为调用某些基本工具(例如basename)的外壳代码适合进行单元测试(如果愿意,可以将这些工具解释为标准库"的一部分).

However, there is shell code that is suitable for unit-testing. This is, for example, code performing computations within the shell, or string manipulations. I would even consider shell code with calls to certain fundamental tools like basename as suitable for unit-testing (interpreting such tools as being part of the 'standard library' if you like).

如何在外壳中使那些适合进行单元测试的代码部分实际可以通过单元测试进行测试?根据我的经验,最有用的方法之一是将交互与计算分开.即,尝试将计算部分放在要测试的单独的外壳函数中,或提取交互作用占主导地位的部分在单独的外壳函数中.这样可以节省大量的模拟工作.

How to make those code parts in a shell that are suitable for being unit-tested actually testable with unit-testing? One of the most useful approaches in my experience is to separate interactions from computations. That is, try to put the computational parts in separate shell functions to be tested, or extract the interaction dominated parts in separate shell functions. That saves you a lot of mocking effort.

这篇关于如何编写可测试的bash shell代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆