33"""
44
55from uuid import uuid4
6+ import pytest
67from common .block import Block
7- from common .fragment import Fragment
8+ from common .exceptions import InvalidBlockUUIDError
9+ from common .fragment import APIFragment , Fragment
10+ from common .pool import Pool
811from common .utils import bytes_to_str
912
1013
@@ -19,6 +22,13 @@ def _create_test_block(size):
1922 return block
2023
2124
25+ def _create_test_pool_and_block (block_size ):
26+ pool = Pool (name = "test_pool" , owner = Pool .Owner .LOCAL )
27+ block = _create_test_block (block_size )
28+ pool .add_block (block )
29+ return (pool , block )
30+
31+
2232def test_fragment_init ():
2333 """
2434 Initialize a fragment.
@@ -113,3 +123,42 @@ def test_fragment_to_mgmt():
113123 "size" : 5 ,
114124 "data" : bytes_to_str (bytes .fromhex ("0001020304" )),
115125 }
126+
127+
128+ def test_to_api ():
129+ """
130+ Create an APIFragment for a Fragment.
131+ """
132+ block = _create_test_block (10 )
133+ fragment = Fragment .allocate (block , 5 )
134+ api_fragment = fragment .to_api ()
135+ assert api_fragment .block_uuid == str (block .uuid )
136+ assert api_fragment .start == 0
137+ assert api_fragment .size == 5
138+
139+
140+ def test_from_api_success ():
141+ """
142+ Create a Fragment from a valid APIFragment.
143+ """
144+ # pylint: disable=protected-access
145+ (pool , block ) = _create_test_pool_and_block (10 )
146+ api_fragment = APIFragment (block_uuid = str (block .uuid ), start = 0 , size = 5 )
147+ fragment = Fragment .from_api (api_fragment , pool )
148+ assert fragment .block == block
149+ assert fragment .start == 0
150+ assert fragment .size == 5
151+ assert fragment .data == bytes .fromhex ("0001020304" )
152+ assert block .nr_used_bytes == 5
153+ assert block ._data == bytes .fromhex ("00000000000506070809" )
154+
155+
156+ def test_from_api_bad_uuid ():
157+ """
158+ Attempt to create a Fragment from a bad APIFragment (invalid block UUID).
159+ """
160+ # pylint: disable=protected-access
161+ (pool , block ) = _create_test_pool_and_block (10 )
162+ api_fragment = APIFragment (block_uuid = "not-a-uuid" , start = 0 , size = 5 )
163+ with pytest .raises (InvalidBlockUUIDError ):
164+ fragment = Fragment .from_api (api_fragment , pool )
0 commit comments