Function privacy and unit testing Haskell

孤街浪徒 提交于 2019-12-03 02:14:40

问题


How do you deal with function visibility and unit testing in 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.

I thought of using {-# LANGUAGE CPP #-} and then surrounding the exports with an #ifdef:

{-# LANGUAGE CPP #-}

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

Is there a better way?


回答1:


The usual convention is to split your module into public and private parts, i.e.

module SomeModule.Internal where

-- ... exports all private methods

and then the public 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.

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.). This greatly increases the usability of you library compared to forcibly hiding the private API.




回答2:


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.

For external function visibility you split the library modules between the "exposed-modules" section and the "other-modules" section.



来源:https://stackoverflow.com/questions/14379185/function-privacy-and-unit-testing-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!