Friday, August 2, 2013

Work notes; unit testing and vim

Redactor

Installing comfortable mexican sofa

https://github.com/comfy/comfortable-mexican-sofa

Rails generator and haml?! I want ERB please!

mvim ~/.rvm/gems/ruby-1.9.3-p194@rails328/gems/comfortable_mexican_sofa-1.8.4/lib/comfortable_mexican_sofa/engine.rb

# comment out 'haml-rails'
# require 'haml-rails'

Of course, when your done generating new code, you will need to enable it again or comfy won't work right.

Integrate a different wysiwyg tool for content editing.

https://github.com/comfy/comfortable-mexican-sofa/issues/321 https://github.com/comfy/comfortable-mexican-sofa/wiki/Replacing-default-wysiwyg-editor-with-redactor

Not ckeditor, but it should be very similar to this: https://github.com/comfy/comfortable-mexican-sofa/wiki/Replacing-default-wysiwyg-editor-with-redactor

https://github.com/comfy/comfortable-mexican-sofa/issues/321

Uploading images

http://imperavi.com/redactor/docs/images/ http://guides.rubyonrails.org/form_helpers.html

Vim

Save replace value in vim

let @y = ''

let @z = '/<pre [^>]\+\+><return>'
let @z .= 'v/><return>'
let @z .= '"yy'

normal @z
http://superuser.com/questions/575831/save-replace-value-in-vim

Clear out @y register. Search for desired string, start selecting until specified pattern, and while selection is active, shove it in the @y register ("Yy would append to the @y register).

Formatting columns in a selected block

:%!column -t

"in visual mode
:!column -t

" establish columns by splitting on Tab character
" Ctrl-V, Tab to generate '^I'
:%!column -t -s "^I"
http://stackoverflow.com/questions/1229900/reformat-in-vim-for-a-nice-column-layout

Because my files didn't have a space I had to use :%!column -t -s ','. It removes the commas, so they're not technicaly csv files anymore. But arranges them beautifully, which is what I needed.

http://stackoverflow.com/questions/1229900/reformat-in-vim-for-a-nice-column-layout

To format only the content of the visual block, delimit on :

:!column -t -s '<tab>'

Works like a champ.

Using marks

   ma     set mark a at current cursor location
  'a      jump to line of mark a (first non-blank character in line)
  `a      jump to position (line and column) of mark a 
  :marks  list all the current marks 
http://vim.wikia.com/wiki/Using_marks

Substitute with contents of register or lines range from elsewhere in file in Vim

:%s/foo/\=@a/g
http://stackoverflow.com/questions/662734/substitute-with-contents-of-register-or-lines-range-from-elsewhere-in-file-in-vi

No other replacement values can be included with '\=@a'. Otherwise, it won't work.

Vim - if/elseif/else statements in for loop (command mode)

:for i in range(1,10) | if i > 5 | put =i | endif | endfor
http://stackoverflow.com/questions/6544903/vim-if-elseif-else-statements-in-for-loop-command-mode

Get statement on a single line

While Loops

while c <= 4
  let total += c
  let c += 1
endwhile
http://learnvimscriptthehardway.stevelosh.com/chapters/36.html

Simple enough.

Cool things to do with substitutions

http://vim.wikia.com/wiki/Search_and_replace

How to concatenate

let s .= '%' . i . 'T'
http://stackoverflow.com/questions/4911692/what-does-in-vim-scripts-mean

Like Bash, the spaces are crucially important. Items must be separated by a space on either side.

Wonderful and comprehensive resource!

Other ways to substitute

http://stackoverflow.com/questions/2156405/how-do-i-do-a-g-with-a-concatenating-of-submatches-in-vim

Appending to a register using the capital version of the register letter

    "Kyy
http://stackoverflow.com/questions/1497958/how-to-use-vim-registers

Wow! This stuff is cryptic.

What is 'f' and 'F' and how do they work?

F)vi(
http://learnvimscriptthehardway.stevelosh.com/chapters/15.html

:normal! is something we'll talk about in a later chapter, but for now it's enough to know that it is a command used to simulate pressing keys in normal mode. For example, running :normal! dddd will delete two lines, just like pressing dddd. The at the end of the mapping is what executes the :normal! command.

http://learnvimscriptthehardway.stevelosh.com/chapters/15.html

(f)ind character; (f)next, (F)previous

(vi)select block body delimited by '()', '{}', '<>', or '[]'

Escaping single quotes is easy, but a little verbose

"'" . x . "'"
http://vim.1045645.n5.nabble.com/escape-and-td1200763.html

Remember, the spaces between concatenated strings is important!

Search only over a visual range

/\%Vpattern

<div>hello</div>
http://vim.wikia.com/wiki/Search_only_over_a_visual_range

This saved my skin; the trick is to create a highlighted range, escape, and then use the substitution flag '\%V' to limit substitution to the last selected block. When including a '^' before the flag, it means the first in the selection, not each line in the selection. Interesting...

Getting zen-code to format snippet using multi-line

    let @z = 'gvj<escape>A<return><return><escape>gv<c-y>,div.notes>p*<return>'

A little difficult to see from code snippet, but add a line to the currently selected block, add a couple of new lines after the block, select the last selected block again and then execute the zen-code command.

Ruby; Rails

Error, Ruby on Rails: Encoding::UndefinedConversionError in CoursesController#attachment “\xFF” from ASCII-8BIT to UTF-8

  ...
  File.open(Rails.root.join('public', 'upload', uploaded_io.original_filename), 'wb') do |file|
    file.write(uploaded_io.read)
  end
http://stackoverflow.com/questions/13909812/error-ruby-on-rails-encodingundefinedconversionerror-in-coursescontrollerat

Try to open the file in binary mode ('wb' instead of 'w')

http://stackoverflow.com/questions/13909812/error-ruby-on-rails-encodingundefinedconversionerror-in-coursescontrollerat

Uploading files

<%= form_for @person do |f| %>
  <%= f.file_field :picture %>
<% end %>
http://guides.rubyonrails.org/form_helpers.html

Html

Pure CSS Blockquote Styling

<blockquote>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae!
<cite>Somebody famous</cite>
</blockquote>
http://www.webmaster-source.com/2012/04/24/pure-css-blockquote-styling/

I'm trying to use this to format quotes in my blog.

Twitter Bootstrap reference (for v2.3.2)

    <div class="row">
    <div class="span4">...</div>
    <div class="span8">...</div>
    </div>
http://getbootstrap.com/2.3.2/scaffolding.html

The new version has some rather significant changes.

CMS

Allow use of ERB in cms

https://github.com/comfy/comfortable-mexican-sofa/issues/67

I have fixed the initializer changing disable_irb=true to allow_irb=false to match the Configuration class definition. My fork is at https://github.com/dsapala/comfortable-mexican-sofa . Feel free to pull commit 6706ff2 for that change.

https://github.com/comfy/comfortable-mexican-sofa/issues/67

Java; Unit Test Mocking

Maven setup for the Mockito API with JUnit

<properties>
    <powermock.version>1.5.1</powermock.version>
</properties>
<dependencies>
   <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-module-junit4-legacy</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
   </dependency>
   <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-api-mockito</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
   </dependency>
</dependencies>
http://code.google.com/p/powermock/wiki/Mockito_maven

I'm beginning to concede that Mockito is the option most similar to Ruby style mocking.

mockito mock a constructor with parameter

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class MockA {
    @Test
    public void test_not_mocked() throws Throwable {
        assertThat(new A("random string").check(), equalTo("checked random string"));
    }
    @Test
    public void test_mocked() throws Throwable {
         A a = mock(A.class); 
         when(a.check()).thenReturn("test");
         PowerMockito.whenNew(A.class).withArguments(Mockito.anyString()).thenReturn(a);
         assertThat(new A("random string").check(), equalTo("test"));
    }
}
http://stackoverflow.com/questions/13364406/mockito-mock-a-constructor-with-parameter

Mocking constructors requires something extra from just Mockito.

Mocking Static Method

   @PrepareForTest(Static.class); // Static.class contains static methods
        PowerMockito.mockStatic(Static.class);   
        Mockito.when(Static.firstStaticMethod(param)).thenReturn(value);
http://code.google.com/p/powermock/wiki/MockitoUsage

how do I mock Class myVar in Mockito (or PowerMock if needed)?

class FooBar {
  static class Factory {
    static FooBar instance;
    FooBar getInstance() {
      if (instance == null) {
        instance = new FooBar();
      }
      return instance;
    }
  }
  // ...
}
http://stackoverflow.com/questions/13057933/how-do-i-mock-class-extends-list-myvar-in-mockito-or-powermock-if-needed

Mockito is designed exclusively for mocking instances of objects. Under the hood, the mock method actually creates a proxy that receives calls to all non-final methods, and logs and stubs those calls as needed. There's no good way to use Mockito to replace a function on the Class object itself.

http://stackoverflow.com/questions/13057933/how-do-i-mock-class-extends-list-myvar-in-mockito-or-powermock-if-needed

Maven configuration for using PowerMockito?

http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CC8QFjAA&url=http%3A%2F%2Fmvnrepository.com%2Fartifact%2Forg.powermock&ei=PyT8UfTwL8HKiAKxmYHICQ&usg=AFQjCNHKogX9smNHkXFJn6B7xxvH2SHKOA&sig2=8Sn64TLEqcyaFNVx_Lua8w&bvm=bv.50165853,d.cGE

It appears the site was down when I tried to capture data into my blog entry.

Mockito documentation (1.6)

 //Let's import Mockito statically so that the code looks clearer
 import static org.mockito.Mockito.*;
 
 //mock creation
 List mockedList = mock(List.class);
 
 //using mock object
 mockedList.add("one");
 mockedList.clear();
 
 //verification
 verify(mockedList).add("one");
 verify(mockedList).clear();
http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Mockito.html

It appears this has a little guide of common uses for Mockito.

Mockito matchers

  //stubbing using anyInt() argument matcher
  when(mockedList.get(anyInt())).thenReturn("element");
  
  //following prints "element"
  System.out.println(mockedList.get(999));
  
  //you can also verify using argument matcher
  verify(mockedList).get(anyInt());
http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Matchers.html

Testing with Mockito - Tutorial

http://www.vogella.com/articles/Mockito/article.html

Fruzenshtein's notes on JUnit and Mockito

    ...  
        @Mock  
        IContainer coffeeContainer;  
        @Mock  
        IContainer waterContainer;  
    ...  
http://fruzenshtein.com/junit-and-mockito/

Mockito - 2 minute tutorial

public class CustomiizeMethodBehaviour  
{  
    public static void main(String[] args)  
    {  
        List myMockedList = mock(List.class);   
        when(myMockedList .get(0)).thenReturn("target");  
          
        System.out.println(myMockedList .get(0));  
    }  
}  
http://www.2min2code.com/articles/mockito_intro/stubbing_method_hardcoded

Mockito documentation (1.9.5)

http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#1

Obviously, more comprehensive than the 1.6 version.

JRuby Array to Java Array

{"options"=>["Option One", "Option Two"]}["options"].to_java :string

[1, 2, 3].to_java(:int)
http://stackoverflow.com/questions/1532606/jruby-array-to-java-array

Taming the beast: Using JRuby and RSpec to test a J2EE application

require 'java'
include_class 'org.springframework.context.ApplicationContext'
include_class
  'org.springframework.context.support.ClassPathXmlApplicationContext'
describe "Calculator" do
  it "should add numbers correctly" do
    application_context =
      ClassPathXmlApplicationContext.new "ApplicationContext.xml"
    calculator =  application_context.getBean "calculatorService"
    calculator.sum([1, 2]).should == 3
    calculator.sum([2, 2]).should == 4
    calculator.sum([2, 3, 4]).should == 9
  end
end
http://patshaughnessy.net/2009/6/25/taming-the-beast-using-jruby-and-rspec-to-test-a-j2ee-application

Working with J2EE applications is something like wandering in a jungle: you never quite know what wild animal you’ll find around the next corner... whatever it is, you’re guaranteed to spend countless hours wasting time learning things you really didn’t want to know.

[Let me] show how you can get your J2EE application under control by using JRuby and RSpec.

http://patshaughnessy.net/2009/6/25/taming-the-beast-using-jruby-and-rspec-to-test-a-j2ee-application

Mock File class and NullPointerException

java.lang.NullPointerException at java.io.File.(File.java:308)

File folder = Mockito.mock(File.class);
when(folder.getPath()).thenReturn("C:\temp\");
File file = new Agent().createNewFile(folder, "fileName");
http://stackoverflow.com/questions/3515011/mock-file-class-and-nullpointerexception/3515129#3515129

RSpec, JRuby, Mocking, and Multiple Interfaces

http://blog.nicksieger.com/articles/2006/12/01/rspec-jruby-mocking-and-multiple-interfaces/

The prospect of doing behavior-driven development in Java has just taken a step closer with the news of RSpec running on JRuby. This is already a big step that will have an impact on Ruby and Java programmers alike in a number of ways."

http://blog.nicksieger.com/articles/2006/12/01/rspec-jruby-mocking-and-multiple-interfaces/
he prospect of doing behavior-driven development in Java has just taken a step closer with the news of RSpec running on JRuby. This is already a big step that will have an impact on Ruby and Java programmers alike in a number of ways."

The RMock 2.0.0 user guide

http://rmock.sourceforge.net/documentation/xdoc.html

JRuby for the Win

http://winstonyw.com/assets/downloads/JRubyForTheWin.pdf

A PDF document that contains some of the authors notes on JTestR, a product I had hoped would do the job. It appears that it fell off the table awhile back in 2009. Sad, really.

RSpec 1.3.0 Documentation; Configuration

Spec::Runner.configure do |config|
  config.mock_with :rspec, :mocha, :flexmock, or :rr
end
http://rspec.rubyforge.org/rspec/1.3.0/classes/Spec/Runner/Configuration.html

Admittedly, this example is deprecated. See a more recent version of RSpec.

JtestR documentation; Mocking

functional_tests do
  test "that a new HashMap can be created based on another map" do
    map = Map.new

    map.expects(:size).returns(0)

    iter = Iterator.new
    iter.expects(:hasNext).returns(false)

    set = Set.new
    set.expects(:iterator).returns(iter)

    map.expects(:entrySet).returns(set)

    assert_equal 0, HashMap.new(map).size
  end
end
http://jtestr.codehaus.org/Mocks

Only problem is the mocked bindings disappear once execution enters the actual Java code :(

JtestR documentation; Getting Started

http://jtestr.codehaus.org/Getting+Started

Mocking JRuby

  require 'test/unit'
  require 'rubygems'
  require 'mocha'

  ...

    def test_filling_removes_inventory_if_in_stock
      order = OrderImpl.new(TALISKER, 50)
      warehouse = Warehouse.new
      warehouse.stubs(:hasInventory).with(TALISKER, 50).returns(true)
      warehouse.stubs(:remove).with(TALISKER, 50)

      order.fill(warehouse)
      assert order.is_filled
    end  
http://memeagora.blogspot.com/2007/10/mocking-jruby.html

Testing is one of the easy ways to sneak JRuby into your organization because it is easier to write tests in dynamic languages (especially mock object tests) and it isn't code that is deployed, so it eases the minds of the furniture police somewhat.

http://memeagora.blogspot.com/2007/10/mocking-jruby.html

Mocking core Java classes with jmockit

  import mockit.*;
  import java.math.*;

  public class Test {
    public static void main(String[] args) {
      Mockit.redefineMethods(BigDecimal.class, new BigDecimalMock());
      System.err.println(BigDecimal.ONE.add(BigDecimal.ONE));
    }
  }
http://evan.tiggerpalace.com/articles/2008/05/02/mocking-core-java-classes-with-jmockit/

So, yes, Virginia, it is possible to mock core classes... To make this work practically would likely necessitate launching a separate VM so as to 'scope' the mock to a particular test.

Fugly.

http://evan.tiggerpalace.com/articles/2008/05/02/mocking-core-java-classes-with-jmockit/

Bash

zen coding multiple elements with children

.br-title>span^.br-content>cfoutput
http://stackoverflow.com/questions/16739994/zen-coding-multiple-elements-with-children

Highlighted block is applied to the last child selector.

Java

Setting the classpath

java -classpath example

java -cp example
http://javarevisited.blogspot.com/2011/01/how-classpath-work-in-java.html

Java Initialize an int array in a constructor

data = new int[]{0, 0, 0};
http://stackoverflow.com/questions/8068470/java-initialize-an-int-array-in-a-constructor

No comments:

Post a Comment