简体   繁体   English

功能隐私和单元测试Haskell

[英]Function privacy and unit testing Haskell

How do you deal with function visibility and unit testing in Haskell? 你如何处理Haskell中的函数可见性和单元测试?

If you export every function in a module so that the unit tests have access to them, you risk other people calling functions that should not be in the public API. 如果导出模块中的每个函数以便单元测试可以访问它们,则会冒其他人调用不应该在公共API中的函数的风险。

I thought of using {-# LANGUAGE CPP #-} and then surrounding the exports with an #ifdef : 我想过使用{-# LANGUAGE CPP #-}然后用#ifdef包围导出:

{-# LANGUAGE CPP #-}

module SomeModule
#ifndef TESTING
( export1
, export2
)
#endif
where

Is there a better way? 有没有更好的办法?

The usual convention is to split your module into public and private parts, ie 通常的惯例是将您的模块拆分为公共和私有部分,即

module SomeModule.Internal where

-- ... exports all private methods

and then the public API 然后是公共API

module SomeModule where (export1, export2)

import SomeModule.Internal

Then you can import SomeModule.Internal in tests and other places where its crucial to get access to the internal implementation. 然后,您可以在测试和其他对其访问内部实现至关重要的地方导入SomeModule.Internal

The idea is that the users of your library never accidentally call the private API, but they can use it if the know what they are doing (debugging etc.). 我们的想法是,您的库的用户永远不会意外地调用私有API,但如果知道他们正在做什么(调试等),他们可以使用它。 This greatly increases the usability of you library compared to forcibly hiding the private API. 与强制隐藏私有API相比,这大大增加了库的可用性。

For testing you normally split the application in the cabal project file, between a library, the production executable, and a test-suite executable that tests the library functions, so the test assertion functions are kept apart. 对于测试,您通常将应用程序拆分在cabal项目文件中,库,生产可执行文件和测试库函数的测试套件可执行文件之间,因此测试断言功能保持分开。

For external function visibility you split the library modules between the "exposed-modules" section and the "other-modules" section. 对于外部功能可见性,您可以在“exposed-modules”部分和“other-modules”部分之间拆分库模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM