Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Recently I had a good time avoiding a few dependencies. I am developing a project using Django and it go to a size, where I felt I should add testing to it.

But to test things, I would need instances of model classes. However, I didn't want to have to specify all the required fields every time I needed an instance for a test. The fields might be mandatory, but not always relevant for each test. Such a field needs to be filled, but not necessarily by me in the test code. I knew from earlier projects, that Faker generates random data and in the past I have thought it shouldn't be difficult to write a thing that generates random strings and numbers and ids for fields, and recursively other required entities. So I decided to write it myself [1], rather than introducing factory boy and faker as dependencies.

Sure those libraries will have a lot more features, but my code is simple and does what I need and I gained additional understanding of the complications with Django's model handling.

I also suspect, that factory boy has to hack around some issues, that I avoided by always creating entities in the database, which most of my code is doing anyway. I am not sure how they solved creating instances of models, that have many to many fields without persisting the entities in the database for example, because Django raises an error when one tries to do set a value for such a many to many field, without storing the entity in the database first, so that it gets an id. Which makes sense. So I suspect there is quite some magic in that dependency, that I don't need for now.

What's more is, that my factory functions are just as easy to use, if not easier. I simply do `factory_for_model(MyModel)(kwargs)`. It is also easy to add more functionality like `gen_multiple(factory, count)` for example. Uniqueness is more difficult, due to how Django's fields and models are compared. But as far as I understand neither does Faker do uniqueness out of the box. I may be wrong about that though.

I also developed a decorator for pytest functions, that helps me avoiding long test names and instead puts a test description in the decorator arguments. Those sentence long test names have previously annoyed me and always caused linting to attack me for it.

[1]: https://codeberg.org/ZelphirKaltstahl/web-app-vocabulary-tra...



Test-only dependencies should be maintained separately from functional dependencies.

For standardized things like testing, I'm not sure if DIY makes sense. Even if you use 10% of its capabilities, sticking with an established test framework makes your codebase more maintainable and easier for others to contribute to.


The test framework is established though. I am still using pytest.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: