prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>test_view_list_all_medications.py<|end_file_name|><|fim▁begin|>from django.test import TestCase
from medicine.models import Medicine
from medicine.views import ListAllMedicines
from user.models import HealthProfessional
class TestListAllMedicines(TestCase):
def setUp(self):
# Making a HealthProfessional
self.view = ListAllMedicines
# Making medicati
self.medicine = Medicine()
self.medicine.name = "Medicamento Teste"
self.medicine.active_ingredient = "Teste Lab"
self.medicine.save()
self.listing = Medicine.objects.all()
def test_medicine_is_show(self):
<|fim_middle|>
<|fim▁end|> | instance = self.view()
self.assertEqual(instance.get_queryset()[0], self.listing[0]) |
<|file_name|>test_view_list_all_medications.py<|end_file_name|><|fim▁begin|>from django.test import TestCase
from medicine.models import Medicine
from medicine.views import ListAllMedicines
from user.models import HealthProfessional
class TestListAllMedicines(TestCase):
def <|fim_middle|>(self):
# Making a HealthProfessional
self.view = ListAllMedicines
# Making medicati
self.medicine = Medicine()
self.medicine.name = "Medicamento Teste"
self.medicine.active_ingredient = "Teste Lab"
self.medicine.save()
self.listing = Medicine.objects.all()
def test_medicine_is_show(self):
instance = self.view()
self.assertEqual(instance.get_queryset()[0], self.listing[0])
<|fim▁end|> | setUp |
<|file_name|>test_view_list_all_medications.py<|end_file_name|><|fim▁begin|>from django.test import TestCase
from medicine.models import Medicine
from medicine.views import ListAllMedicines
from user.models import HealthProfessional
class TestListAllMedicines(TestCase):
def setUp(self):
# Making a HealthProfessional
self.view = ListAllMedicines
# Making medicati
self.medicine = Medicine()
self.medicine.name = "Medicamento Teste"
self.medicine.active_ingredient = "Teste Lab"
self.medicine.save()
self.listing = Medicine.objects.all()
def <|fim_middle|>(self):
instance = self.view()
self.assertEqual(instance.get_queryset()[0], self.listing[0])
<|fim▁end|> | test_medicine_is_show |
<|file_name|>permute.py<|end_file_name|><|fim▁begin|># File permute.py
def permute1(seq):<|fim▁hole|> return [seq] # Empty sequence
else:
res = []
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute1(rest): # Permute the others
res.append(seq[i:i+1] + x) # Add node at front
return res
def permute2(seq):
if not seq: # Shuffle any sequence: generator
yield seq # Empty sequence
else:
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute2(rest): # Permute the others
yield seq[i:i+1] + x # Add node at front<|fim▁end|> | if not seq: # Shuffle any sequence: list |
<|file_name|>permute.py<|end_file_name|><|fim▁begin|># File permute.py
def permute1(seq):
<|fim_middle|>
def permute2(seq):
if not seq: # Shuffle any sequence: generator
yield seq # Empty sequence
else:
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute2(rest): # Permute the others
yield seq[i:i+1] + x # Add node at front
<|fim▁end|> | if not seq: # Shuffle any sequence: list
return [seq] # Empty sequence
else:
res = []
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute1(rest): # Permute the others
res.append(seq[i:i+1] + x) # Add node at front
return res |
<|file_name|>permute.py<|end_file_name|><|fim▁begin|># File permute.py
def permute1(seq):
if not seq: # Shuffle any sequence: list
return [seq] # Empty sequence
else:
res = []
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute1(rest): # Permute the others
res.append(seq[i:i+1] + x) # Add node at front
return res
def permute2(seq):
<|fim_middle|>
<|fim▁end|> | if not seq: # Shuffle any sequence: generator
yield seq # Empty sequence
else:
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute2(rest): # Permute the others
yield seq[i:i+1] + x # Add node at front |
<|file_name|>permute.py<|end_file_name|><|fim▁begin|># File permute.py
def permute1(seq):
if not seq: # Shuffle any sequence: list
<|fim_middle|>
else:
res = []
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute1(rest): # Permute the others
res.append(seq[i:i+1] + x) # Add node at front
return res
def permute2(seq):
if not seq: # Shuffle any sequence: generator
yield seq # Empty sequence
else:
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute2(rest): # Permute the others
yield seq[i:i+1] + x # Add node at front
<|fim▁end|> | return [seq] # Empty sequence |
<|file_name|>permute.py<|end_file_name|><|fim▁begin|># File permute.py
def permute1(seq):
if not seq: # Shuffle any sequence: list
return [seq] # Empty sequence
else:
<|fim_middle|>
def permute2(seq):
if not seq: # Shuffle any sequence: generator
yield seq # Empty sequence
else:
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute2(rest): # Permute the others
yield seq[i:i+1] + x # Add node at front
<|fim▁end|> | res = []
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute1(rest): # Permute the others
res.append(seq[i:i+1] + x) # Add node at front
return res |
<|file_name|>permute.py<|end_file_name|><|fim▁begin|># File permute.py
def permute1(seq):
if not seq: # Shuffle any sequence: list
return [seq] # Empty sequence
else:
res = []
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute1(rest): # Permute the others
res.append(seq[i:i+1] + x) # Add node at front
return res
def permute2(seq):
if not seq: # Shuffle any sequence: generator
<|fim_middle|>
else:
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute2(rest): # Permute the others
yield seq[i:i+1] + x # Add node at front
<|fim▁end|> | yield seq # Empty sequence |
<|file_name|>permute.py<|end_file_name|><|fim▁begin|># File permute.py
def permute1(seq):
if not seq: # Shuffle any sequence: list
return [seq] # Empty sequence
else:
res = []
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute1(rest): # Permute the others
res.append(seq[i:i+1] + x) # Add node at front
return res
def permute2(seq):
if not seq: # Shuffle any sequence: generator
yield seq # Empty sequence
else:
<|fim_middle|>
<|fim▁end|> | for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute2(rest): # Permute the others
yield seq[i:i+1] + x # Add node at front |
<|file_name|>permute.py<|end_file_name|><|fim▁begin|># File permute.py
def <|fim_middle|>(seq):
if not seq: # Shuffle any sequence: list
return [seq] # Empty sequence
else:
res = []
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute1(rest): # Permute the others
res.append(seq[i:i+1] + x) # Add node at front
return res
def permute2(seq):
if not seq: # Shuffle any sequence: generator
yield seq # Empty sequence
else:
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute2(rest): # Permute the others
yield seq[i:i+1] + x # Add node at front
<|fim▁end|> | permute1 |
<|file_name|>permute.py<|end_file_name|><|fim▁begin|># File permute.py
def permute1(seq):
if not seq: # Shuffle any sequence: list
return [seq] # Empty sequence
else:
res = []
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute1(rest): # Permute the others
res.append(seq[i:i+1] + x) # Add node at front
return res
def <|fim_middle|>(seq):
if not seq: # Shuffle any sequence: generator
yield seq # Empty sequence
else:
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute2(rest): # Permute the others
yield seq[i:i+1] + x # Add node at front
<|fim▁end|> | permute2 |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text<|fim▁hole|>
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc<|fim▁end|> | |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
<|fim_middle|>
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | """ A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text) |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
<|fim_middle|>
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
<|fim_middle|>
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | """ Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
<|fim_middle|>
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text) |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
<|fim_middle|>
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | """ A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno) |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
<|fim_middle|>
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | self.start_lineno = start_lineno
self.end_lineno = end_lineno |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
<|fim_middle|>
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | """ Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0]) |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
<|fim_middle|>
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno) |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
<|fim_middle|>
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | """ Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
<|fim_middle|>
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {} |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
<|fim_middle|>
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | """ Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index() |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
<|fim_middle|>
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | """ Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line) |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
<|fim_middle|>
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | """ We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
<|fim_middle|>
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | """ Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
<|fim_middle|>
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | """ Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
<|fim_middle|>
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | """ Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
<|fim_middle|>
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | """ Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
<|fim_middle|>
<|fim▁end|> | """ Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
<|fim_middle|>
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | from io import StringIO |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
<|fim_middle|>
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | from io import StringIO |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
<|fim_middle|>
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0]) |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
<|fim_middle|>
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | nxt = file.__next__ |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
<|fim_middle|>
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | nxt = file.next |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
<|fim_middle|>
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0]) |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
<|fim_middle|>
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | self.current_block.add(string, start, end, line) |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
<|fim_middle|>
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | self.new_noncomment(start[0], end[0]) |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
<|fim_middle|>
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line) |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
<|fim_middle|>
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | self.new_comment(string, start, end, line) |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
<|fim_middle|>
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | self.current_block.add(string, start, end, line) |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
<|fim_middle|>
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | self.current_block.add(string, start, end, line) |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
<|fim_middle|>
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
<|fim_middle|>
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | self.index[block.start_lineno] = prev |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
<|fim_middle|>
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | self.make_index() |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
<|fim_middle|>
<|fim▁end|> | name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def <|fim_middle|>(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | __init__ |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def <|fim_middle|>(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | add |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def <|fim_middle|>(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | __repr__ |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def <|fim_middle|>(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | __init__ |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def <|fim_middle|>(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | add |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def <|fim_middle|>(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | __repr__ |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def <|fim_middle|>(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | __init__ |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def <|fim_middle|>(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | process_file |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def <|fim_middle|>(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | process_token |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def <|fim_middle|>(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | new_noncomment |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def <|fim_middle|>(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | new_comment |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def <|fim_middle|>(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | make_index |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def <|fim_middle|>(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | search_for_comment |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def <|fim_middle|>(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | strip_comment_marker |
<|file_name|>comment_eater.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def <|fim_middle|>(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
<|fim▁end|> | get_class_traits |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># automate/server/user/views.py
#################
#### imports ####
#################
#from flask import render_template, Blueprint, url_for, \
# redirect, flash, request
#from flask_login import login_user, logout_user, login_required
#from automate.server import bcrypt, db
#from automate.server import db
#from automate.server.models import User
#from automate.server.user.forms import LoginForm, RegisterForm
################
#### config ####
################
#user_blueprint = Blueprint('user', __name__,)
################
#### routes ####
################
#@user_blueprint.route('/register', methods=['GET', 'POST'])
#def register():
# form = RegisterForm(request.form)
# if form.validate_on_submit():
# user = User(
# email=form.email.data,
# password=form.password.data
# )
# db.session.add(user)
# db.session.commit()
#
# login_user(user)
#
# flash('Thank you for registering.', 'success')
# return redirect(url_for("user.members"))
#
# return render_template('user/register.html', form=form)<|fim▁hole|>#def login():
# form = LoginForm(request.form)
# if form.validate_on_submit():
# user = User.query.filter_by(email=form.email.data).first()
# if user:
# #if user and bcrypt.check_password_hash(
# # user.password, request.form['password']):
# # login_user(user)
# flash('You are logged in. Welcome!', 'success')
# return redirect(url_for('user.members'))
# else:
# flash('Invalid email and/or password.', 'danger')
# return render_template('user/login.html', form=form)
# return render_template('user/login.html', title='Please Login', form=form)
#
#
#@user_blueprint.route('/logout')
#@login_required
#def logout():
# logout_user()
# flash('You were logged out. Bye!', 'success')
# return redirect(url_for('main.home'))
#
#
#@user_blueprint.route('/members')
#@login_required
#def members():
# return render_template('user/members.html')
#<|fim▁end|> | #
#
#@user_blueprint.route('/login', methods=['GET', 'POST']) |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager<|fim▁hole|>
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]<|fim▁end|> | from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
<|fim_middle|>
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
<|fim_middle|>
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | return create_actor(DummyNode()) |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
<|fim_middle|>
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | assert actor().set_port_property(port_type, port_name, port_property, value) is expected |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
<|fim_middle|>
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
<|fim_middle|>
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
<|fim_middle|>
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled() |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
<|fim_middle|>
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
} |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
<|fim_middle|>
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
<|fim_middle|>
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
<|fim_middle|>
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members() |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
<|fim_middle|>
<|fim▁end|> | assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7] |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
<|fim_middle|>
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
<|fim_middle|>
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
<|fim_middle|>
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY) |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
<|fim_middle|>
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | assert not actor.fsm.transition_to.called |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
<|fim_middle|>
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | assert set(test_state[k]) == v |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
<|fim_middle|>
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | assert test_state[k] == v |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def <|fim_middle|>(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | create_actor |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def <|fim_middle|>():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | actor |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def <|fim_middle|>(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | test_set_port_property |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def <|fim_middle|>(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | test_did_connect |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def <|fim_middle|>(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | test_did_disconnect |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def <|fim_middle|>(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | test_enabled |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def <|fim_middle|>():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | test_connections |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def <|fim_middle|>(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | test_state |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def <|fim_middle|>(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | test_set_signature |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def <|fim_middle|>(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def test_requirements(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | test_component |
<|file_name|>test_actor.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from mock import Mock
from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.south.endpoint import LocalOutEndpoint, LocalInEndpoint
from calvin.actor.actor import Actor
pytestmark = pytest.mark.unittest
def create_actor(node):
actor_manager = ActorManager(node)
actor_id = actor_manager.new('std.Identity', {})
actor = actor_manager.actors[actor_id]
actor._calvinsys = Mock()
return actor
@pytest.fixture
def actor():
return create_actor(DummyNode())
@pytest.mark.parametrize("port_type,port_name,port_property,value,expected", [
("invalid", "", "", "", False),
("in", "missing", "", "", False),
("out", "missing", "", "", False),
("out", "token", "missing", "", False),
("in", "token", "missing", "", False),
("out", "token", "name", "new_name", True),
("out", "token", "name", "new_name", True),
])
def test_set_port_property(port_type, port_name, port_property, value, expected):
assert actor().set_port_property(port_type, port_name, port_property, value) is expected
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(False, False, False),
(False, True, False),
(True, False, False),
(True, True, True),
])
def test_did_connect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_connect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.ENABLED)
assert actor._calvinsys.scheduler_wakeup.called
else:
assert not actor.fsm.transition_to.called
assert not actor._calvinsys.scheduler_wakeup.called
@pytest.mark.parametrize("inport_ret_val,outport_ret_val,expected", [
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
])
def test_did_disconnect(actor, inport_ret_val, outport_ret_val, expected):
for port in actor.inports.values():
port.is_connected = Mock(return_value=inport_ret_val)
for port in actor.outports.values():
port.is_connected = Mock(return_value=outport_ret_val)
actor.fsm = Mock()
actor.did_disconnect(None)
if expected:
actor.fsm.transition_to.assert_called_with(Actor.STATUS.READY)
else:
assert not actor.fsm.transition_to.called
def test_enabled(actor):
actor.enable()
assert actor.enabled()
actor.disable()
assert not actor.enabled()
def test_connections():
node = DummyNode()
node.id = "node_id"
actor = create_actor(node)
inport = actor.inports['token']
outport = actor.outports['token']
port = Mock()
port.id = "x"
peer_port = Mock()
peer_port.id = "y"
inport.attach_endpoint(LocalInEndpoint(port, peer_port))
outport.attach_endpoint(LocalOutEndpoint(port, peer_port))
assert actor.connections(node) == {
'actor_id': actor.id,
'actor_name': actor.name,
'inports': {inport.id: (node, "y")},
'outports': {outport.id: [(node, "y")]}
}
def test_state(actor):
inport = actor.inports['token']
outport = actor.outports['token']
correct_state = {
'_component_members': set([actor.id]),
'_deployment_requirements': [],
'_managed': set(['dump', '_signature', 'id', '_deployment_requirements', 'name', 'credentials']),
'_signature': None,
'dump': False,
'id': actor.id,
'inports': {'token': {'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {inport.id: 0},
'readers': [inport.id],
'tentative_read_pos': {inport.id: 0},
'write_pos': 0},
'id': inport.id,
'name': 'token'}},
'name': '',
'outports': {'token': {'fanout': 1,
'fifo': {'N': 5,
'fifo': [{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'},
{'data': 0, 'type': 'Token'}],
'read_pos': {},
'readers': [],
'tentative_read_pos': {},
'write_pos': 0},
'id': outport.id,
'name': 'token'}}}
test_state = actor.state()
for k, v in correct_state.iteritems():
# Read state use list to support JSON serialization
if isinstance(v, set):
assert set(test_state[k]) == v
else:
assert test_state[k] == v
@pytest.mark.parametrize("prev_signature,new_signature,expected", [
(None, "new_val", "new_val"),
("old_val", "new_val", "old_val")
])
def test_set_signature(actor, prev_signature, new_signature, expected):
actor.signature_set(prev_signature)
actor.signature_set(new_signature)
assert actor._signature == expected
def test_component(actor):
actor.component_add(1)
assert 1 in actor.component_members()
actor.component_add([2, 3])
assert 2 in actor.component_members()
assert 3 in actor.component_members()
actor.component_remove(1)
assert 1 not in actor.component_members()
actor.component_remove([2, 3])
assert 2 not in actor.component_members()
assert 3 not in actor.component_members()
def <|fim_middle|>(actor):
assert actor.requirements_get() == []
actor.requirements_add([1, 2, 3])
assert actor.requirements_get() == [1, 2, 3]
actor.requirements_add([4, 5])
assert actor.requirements_get() == [4, 5]
actor.requirements_add([6, 7], extend=True)
assert actor.requirements_get() == [4, 5, 6, 7]
<|fim▁end|> | test_requirements |
<|file_name|>Login.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016-2017 University of Dundee & Open Microscopy Environment.
# All Rights Reserved.
# Use is subject to license terms supplied in LICENSE.txt
#
import requests
from Parse_OMERO_Properties import USERNAME, PASSWORD, OMERO_WEB_HOST, \
SERVER_NAME
session = requests.Session()
# Start by getting supported versions from the base url...
api_url = '%s/api/' % OMERO_WEB_HOST
print "Starting at:", api_url
r = session.get(api_url)<|fim▁hole|>versions = r.json()['data']
# use most recent version...
version = versions[-1]
# get the 'base' url
base_url = version['url:base']
r = session.get(base_url)
# which lists a bunch of urls as starting points
urls = r.json()
servers_url = urls['url:servers']
login_url = urls['url:login']
projects_url = urls['url:projects']
save_url = urls['url:save']
schema_url = urls['url:schema']
# To login we need to get CSRF token
token_url = urls['url:token']
token = session.get(token_url).json()['data']
print 'CSRF token', token
# We add this to our session header
# Needed for all POST, PUT, DELETE requests
session.headers.update({'X-CSRFToken': token,
'Referer': login_url})
# List the servers available to connect to
servers = session.get(servers_url).json()['data']
print 'Servers:'
for s in servers:
print '-id:', s['id']
print ' name:', s['server']
print ' host:', s['host']
print ' port:', s['port']
# find one called SERVER_NAME
servers = [s for s in servers if s['server'] == SERVER_NAME]
if len(servers) < 1:
raise Exception("Found no server called '%s'" % SERVER_NAME)
server = servers[0]
# Login with username, password and token
payload = {'username': USERNAME,
'password': PASSWORD,
# 'csrfmiddlewaretoken': token, # Using CSRFToken in header instead
'server': server['id']}
r = session.post(login_url, data=payload)
login_rsp = r.json()
assert r.status_code == 200
assert login_rsp['success']
eventContext = login_rsp['eventContext']
print 'eventContext', eventContext
# Can get our 'default' group
groupId = eventContext['groupId']
# With successful login, request.session will contain
# OMERO session details and reconnect to OMERO on
# each subsequent call...
# List projects:
# Limit number of projects per page
payload = {'limit': 2}
data = session.get(projects_url, params=payload).json()
assert len(data['data']) < 3
print "Projects:"
for p in data['data']:
print ' ', p['@id'], p['Name']
# Create a project:
projType = schema_url + '#Project'
# Need to specify target group
url = save_url + '?group=' + str(groupId)
r = session.post(url, json={'Name': 'API TEST foo', '@type': projType})
assert r.status_code == 201
project = r.json()['data']
project_id = project['@id']
print 'Created Project:', project_id, project['Name']
# Get project by ID
project_url = projects_url + str(project_id) + '/'
r = session.get(project_url)
project = r.json()
print project
# Update a project
project['Name'] = 'API test updated'
r = session.put(save_url, json=project)
# Delete a project:
r = session.delete(project_url)<|fim▁end|> | # we get a list of versions |
<|file_name|>Login.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016-2017 University of Dundee & Open Microscopy Environment.
# All Rights Reserved.
# Use is subject to license terms supplied in LICENSE.txt
#
import requests
from Parse_OMERO_Properties import USERNAME, PASSWORD, OMERO_WEB_HOST, \
SERVER_NAME
session = requests.Session()
# Start by getting supported versions from the base url...
api_url = '%s/api/' % OMERO_WEB_HOST
print "Starting at:", api_url
r = session.get(api_url)
# we get a list of versions
versions = r.json()['data']
# use most recent version...
version = versions[-1]
# get the 'base' url
base_url = version['url:base']
r = session.get(base_url)
# which lists a bunch of urls as starting points
urls = r.json()
servers_url = urls['url:servers']
login_url = urls['url:login']
projects_url = urls['url:projects']
save_url = urls['url:save']
schema_url = urls['url:schema']
# To login we need to get CSRF token
token_url = urls['url:token']
token = session.get(token_url).json()['data']
print 'CSRF token', token
# We add this to our session header
# Needed for all POST, PUT, DELETE requests
session.headers.update({'X-CSRFToken': token,
'Referer': login_url})
# List the servers available to connect to
servers = session.get(servers_url).json()['data']
print 'Servers:'
for s in servers:
print '-id:', s['id']
print ' name:', s['server']
print ' host:', s['host']
print ' port:', s['port']
# find one called SERVER_NAME
servers = [s for s in servers if s['server'] == SERVER_NAME]
if len(servers) < 1:
<|fim_middle|>
server = servers[0]
# Login with username, password and token
payload = {'username': USERNAME,
'password': PASSWORD,
# 'csrfmiddlewaretoken': token, # Using CSRFToken in header instead
'server': server['id']}
r = session.post(login_url, data=payload)
login_rsp = r.json()
assert r.status_code == 200
assert login_rsp['success']
eventContext = login_rsp['eventContext']
print 'eventContext', eventContext
# Can get our 'default' group
groupId = eventContext['groupId']
# With successful login, request.session will contain
# OMERO session details and reconnect to OMERO on
# each subsequent call...
# List projects:
# Limit number of projects per page
payload = {'limit': 2}
data = session.get(projects_url, params=payload).json()
assert len(data['data']) < 3
print "Projects:"
for p in data['data']:
print ' ', p['@id'], p['Name']
# Create a project:
projType = schema_url + '#Project'
# Need to specify target group
url = save_url + '?group=' + str(groupId)
r = session.post(url, json={'Name': 'API TEST foo', '@type': projType})
assert r.status_code == 201
project = r.json()['data']
project_id = project['@id']
print 'Created Project:', project_id, project['Name']
# Get project by ID
project_url = projects_url + str(project_id) + '/'
r = session.get(project_url)
project = r.json()
print project
# Update a project
project['Name'] = 'API test updated'
r = session.put(save_url, json=project)
# Delete a project:
r = session.delete(project_url)
<|fim▁end|> | raise Exception("Found no server called '%s'" % SERVER_NAME) |
<|file_name|>p144.py<|end_file_name|><|fim▁begin|>inside = lambda x, y: 4*x*x+y*y <= 100
def coll(sx, sy, dx, dy):
m = 0
for p in range(32):
m2 = m + 2**(-p)
if inside(sx + dx * m2, sy + dy * m2): m = m2
return (sx + dx*m, sy + dy*m)
def norm(x, y):
l = (x*x + y*y)**0.5
return (x/l, y/l)
sx, sy = 0, 10.1
dx, dy = 1.4, -19.7
<|fim▁hole|> break
mx, my = norm(1, -4*sx/sy)
d = mx*dx + my*dy
dx, dy = -dx + 2 * mx * d, -dy + 2 * my * d<|fim▁end|> | for I in range(999):
sx, sy = coll(sx, sy, dx, dy)
if sy > 0 and abs(sx) <= 0.01:
print(I) |
<|file_name|>p144.py<|end_file_name|><|fim▁begin|>inside = lambda x, y: 4*x*x+y*y <= 100
def coll(sx, sy, dx, dy):
<|fim_middle|>
def norm(x, y):
l = (x*x + y*y)**0.5
return (x/l, y/l)
sx, sy = 0, 10.1
dx, dy = 1.4, -19.7
for I in range(999):
sx, sy = coll(sx, sy, dx, dy)
if sy > 0 and abs(sx) <= 0.01:
print(I)
break
mx, my = norm(1, -4*sx/sy)
d = mx*dx + my*dy
dx, dy = -dx + 2 * mx * d, -dy + 2 * my * d
<|fim▁end|> | m = 0
for p in range(32):
m2 = m + 2**(-p)
if inside(sx + dx * m2, sy + dy * m2): m = m2
return (sx + dx*m, sy + dy*m) |
<|file_name|>p144.py<|end_file_name|><|fim▁begin|>inside = lambda x, y: 4*x*x+y*y <= 100
def coll(sx, sy, dx, dy):
m = 0
for p in range(32):
m2 = m + 2**(-p)
if inside(sx + dx * m2, sy + dy * m2): m = m2
return (sx + dx*m, sy + dy*m)
def norm(x, y):
<|fim_middle|>
sx, sy = 0, 10.1
dx, dy = 1.4, -19.7
for I in range(999):
sx, sy = coll(sx, sy, dx, dy)
if sy > 0 and abs(sx) <= 0.01:
print(I)
break
mx, my = norm(1, -4*sx/sy)
d = mx*dx + my*dy
dx, dy = -dx + 2 * mx * d, -dy + 2 * my * d
<|fim▁end|> | l = (x*x + y*y)**0.5
return (x/l, y/l) |
<|file_name|>p144.py<|end_file_name|><|fim▁begin|>inside = lambda x, y: 4*x*x+y*y <= 100
def coll(sx, sy, dx, dy):
m = 0
for p in range(32):
m2 = m + 2**(-p)
if inside(sx + dx * m2, sy + dy * m2): <|fim_middle|>
return (sx + dx*m, sy + dy*m)
def norm(x, y):
l = (x*x + y*y)**0.5
return (x/l, y/l)
sx, sy = 0, 10.1
dx, dy = 1.4, -19.7
for I in range(999):
sx, sy = coll(sx, sy, dx, dy)
if sy > 0 and abs(sx) <= 0.01:
print(I)
break
mx, my = norm(1, -4*sx/sy)
d = mx*dx + my*dy
dx, dy = -dx + 2 * mx * d, -dy + 2 * my * d
<|fim▁end|> | m = m2 |
<|file_name|>p144.py<|end_file_name|><|fim▁begin|>inside = lambda x, y: 4*x*x+y*y <= 100
def coll(sx, sy, dx, dy):
m = 0
for p in range(32):
m2 = m + 2**(-p)
if inside(sx + dx * m2, sy + dy * m2): m = m2
return (sx + dx*m, sy + dy*m)
def norm(x, y):
l = (x*x + y*y)**0.5
return (x/l, y/l)
sx, sy = 0, 10.1
dx, dy = 1.4, -19.7
for I in range(999):
sx, sy = coll(sx, sy, dx, dy)
if sy > 0 and abs(sx) <= 0.01:
<|fim_middle|>
mx, my = norm(1, -4*sx/sy)
d = mx*dx + my*dy
dx, dy = -dx + 2 * mx * d, -dy + 2 * my * d
<|fim▁end|> | print(I)
break |
<|file_name|>p144.py<|end_file_name|><|fim▁begin|>inside = lambda x, y: 4*x*x+y*y <= 100
def <|fim_middle|>(sx, sy, dx, dy):
m = 0
for p in range(32):
m2 = m + 2**(-p)
if inside(sx + dx * m2, sy + dy * m2): m = m2
return (sx + dx*m, sy + dy*m)
def norm(x, y):
l = (x*x + y*y)**0.5
return (x/l, y/l)
sx, sy = 0, 10.1
dx, dy = 1.4, -19.7
for I in range(999):
sx, sy = coll(sx, sy, dx, dy)
if sy > 0 and abs(sx) <= 0.01:
print(I)
break
mx, my = norm(1, -4*sx/sy)
d = mx*dx + my*dy
dx, dy = -dx + 2 * mx * d, -dy + 2 * my * d
<|fim▁end|> | coll |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.