Форум программистов, компьютерный форум, киберфорум
8Observer8
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  

Mock for "cube_add" Blender API

Запись от 8Observer8 размещена 05.03.2019 в 21:37
Показов 3220 Комментарии 0
Метки blender, mock

Blog content

Mock-objects are useful if you use external editor like VSCode or IDE like PyCharm, Eclipse and so on, because you can use DI (Dependency Injection) and you can debug your code logic with breakpoints.

For example, we want to add a cube on a scene:

Python
1
bpy.ops.mesh.primitive_cube_add()
You can read about this API function in the documentation: primitive_cube_add
  • Create a work folder with the name: mock-object-for-primitive_cube_add-api
  • Open Blender and safe project in the work folder
  • Open "Scripting" tab in Blender from the top menu
  • Open your favourite Python editor. I use VSCode. You can read about how to use VSCode with Python here Python in Visual Studio Code
  • Create a file with the name "main.py" in you favourite Python editor. This file must be placed in the "mock-object-for-primitive_cube_add-api" folder
  • Write in the "main.py":
    Python
    1
    
    print("hello from blender")
    You can run this code from command line terminal or from VSCode internal terminal. Press in VSCode "Ctrl+`" and enter command:
    python main.py
    You will see in the console terminal this message:
    "hello from blender"
    If you opened "Scripting" tab in Blender you will see an ability to open Python script in Blender.
  • Click on the "Open" Button in Blender Script editor inside Blender
  • Choose the "main.py" file and click the "Open Text Block" button
  • Open the Blender console terminal. For this you need to select in the main menu of Blender "Window" and select "Toggle System Console"
  • Run the "main.py" script from Blender. For this you need to place your mouse pointer on text area and press "Alt+P" button
  • You will see this message in the Blender console terminal:
    "hello from blender"
    If you will change a code in an external editor like VSCode you need to reload in the Blender text editor. For this you need to press the "Alt+R+R" button

    You need to add only one file: "main.py" to the Blender text editor. Another files you need place in the work directory: "mock-object-for-primitive_cube_add-api"
  • Copy this code to the "main.py" file:

    main.py

    Python
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    
    import bpy
    import sys
    import os
     
    # Get a path to the directory with .blend file
    # There is the scripts in this directory
    dir = os.path.dirname(bpy.data.filepath)
     
    # Is the the directory in the list with included
    # directories? If no, include the directory
    if not dir in sys.path:
        sys.path.append(dir)
     
    import object3d_service
     
    # Reload module. It is necessary if you use
    # external editor like VSCode
    # For reloading module you need to press in
    # Blender: Alt + R + R
    import importlib
    importlib.reload(object3d_service)
     
    # Note. You do not need to open all scripts in Blender,
    # you need only this script
     
    from object3d_service import Object3DService
     
    def main():
        objectService = Object3DService()
        objectService.create_cube()
     
    if __name__ == "__main__":
        main()
    This is another files that you need to copy to the work directory:

    test_blender_service.py

    Python
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
    import unittest
    from unittest.mock import MagicMock
     
    from object3d_service import Object3DService
     
    class BlenderServiceTest(unittest.TestCase):
     
        def test_myTest(self):
            # Arrange
            object3DService = Object3DService()
            object3DService.blender_api.create_cube = MagicMock("create_cube")
            
            # Act
            object3DService.create_cube()
     
            # Assert
            object3DService.blender_api.create_cube.assert_called_once()
    object3d_service.py

    Python
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    from blender_api import BlenderAPI
     
    class Object3DService:
     
        def __init__(self):
            self.blender_api = BlenderAPI()
     
        def create_cube(self):
            self.blender_api.create_cube()
    blender_api.py

    Python
    1
    2
    3
    4
    5
    6
    
    import bpy
     
    class BlenderAPI:
     
        def create_cube(self):
            bpy.ops.mesh.primitive_cube_add()

Delete a default cube from the scene. Now you can reload Blender code editor ("Alt+R+R") and run the code ("Alt + P"). You will see that a new code will be created:

Нажмите на изображение для увеличения
Название: mock-object-primitive_cube_add.png
Просмотров: 957
Размер:	68.1 Кб
ID:	5300

You can set breakpoints in "main.py" because there are mock-object for Blender API. And you can run unit tests using this command:
python -m unittest
You will see that unit test are passed.
Метки blender, mock
Размещено в Без категории
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
Всего комментариев 0
Комментарии
 
Новые блоги и статьи
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
Фото: Daniel Greenwood
kumehtar 13.11.2025
Расскажи мне о Мире, бродяга
kumehtar 12.11.2025
— Расскажи мне о Мире, бродяга, Ты же видел моря и метели. Как сменялись короны и стяги, Как эпохи стрелою летели. - Этот мир — это крылья и горы, Снег и пламя, любовь и тревоги, И бескрайние. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru